18#include "filemanager.h"
22#include <QVersionNumber>
24#include "fileformat.h"
26#include "layercamera.h"
31 srand(
static_cast<uint
>(time(
nullptr)));
40 handleOpenProjectError(Status::FILE_NOT_FOUND, dd);
46 std::unique_ptr<Object> obj(
new Object);
47 obj->setFilePath(sFileName);
48 obj->createWorkingDir();
54 bool isArchive = isArchiveFormat(sFileName);
58 dd <<
"Recognized Old Pencil2D File Format (*.pcl) !";
60 strMainXMLFile = sFileName;
61 strDataFolder = strMainXMLFile +
"." + PFF_OLD_DATA_DIR;
65 dd <<
"Recognized New zipped Pencil2D File Format (*.pclx) !";
67 Status sanityCheck = MiniZ::sanityCheck(sFileName);
70 if (!sanityCheck.ok()) {
71 dd.collect(sanityCheck.details());
73 Status unzipStatus = unzip(sFileName, obj->workingDir());
74 dd.collect(unzipStatus.details());
77 strMainXMLFile =
QDir(obj->workingDir()).
filePath(PFF_XML_FILE_NAME);
78 strDataFolder =
QDir(obj->workingDir()).
filePath(PFF_DATA_DIR);
85 obj->setDataDir(strDataFolder);
86 obj->setMainXMLFile(strMainXMLFile);
89 mMaxProgressValue = totalFileCount;
90 emit progressRangeChanged(mMaxProgressValue);
92 QFile file(strMainXMLFile);
95 dd <<
"Main XML file does not exist";
96 handleOpenProjectError(Status::ERROR_INVALID_XML_FILE, dd);
101 handleOpenProjectError(Status::ERROR_FILE_CANNOT_OPEN, dd);
108 FILEMANAGER_LOG(
"Couldn't open the main XML file");
109 dd <<
"Error parsing or opening the main XML file";
110 handleOpenProjectError(Status::ERROR_INVALID_XML_FILE, dd);
115 if (!(type.
name() ==
"PencilDocument" || type.
name() ==
"MyObject"))
117 FILEMANAGER_LOG(
"Invalid main XML doctype");
119 handleOpenProjectError(Status::ERROR_INVALID_PENCIL_FILE, dd);
126 dd <<
"Main XML root node is null";
127 handleOpenProjectError(Status::ERROR_INVALID_PENCIL_FILE, dd);
131 loadPalette(obj.get());
135 if (root.
tagName() ==
"document")
137 ok = loadObject(obj.get(), root);
139 else if (root.
tagName() ==
"object" || root.
tagName() ==
"MyOject")
141 ok = loadObjectOldWay(obj.get(), root);
147 dd <<
"Issue occurred during object loading";
148 handleOpenProjectError(Status::ERROR_INVALID_PENCIL_FILE, dd);
152 verifyObject(obj.get());
154 return obj.release();
172 if (element.
tagName() ==
"object")
174 ok =
object->loadXML(element, [
this]{ progressForward(); });
175 if (!ok) FILEMANAGER_LOG(
"Failed to Load object");
178 else if (element.
tagName() ==
"editor" || element.
tagName() ==
"projectdata")
180 object->setData(loadProjectData(element));
182 else if (element.
tagName() ==
"version")
187 if (!fileVersion.
isNull())
189 if (appVersion < fileVersion)
191 qWarning() <<
"You are opening a newer project file in an older version of Pencil2D!";
205 return object->loadXML(root, [
this] { progressForward(); });
208bool FileManager::isArchiveFormat(
const QString& fileName)
const
220 dd << (
"sFileName = " + sFileName);
222 if (
object ==
nullptr)
224 dd <<
"Object parameter is null";
225 return Status(Status::INVALID_ARGUMENT, dd);
228 dd <<
"File name is empty";
229 return Status(Status::INVALID_ARGUMENT, dd,
230 tr(
"Invalid Save Path"),
231 tr(
"The path is empty."));
234 const int totalCount =
object->totalKeyFrameCount();
235 mMaxProgressValue = totalCount + 5;
236 emit progressRangeChanged(mMaxProgressValue);
241 if (fileInfo.isDir())
243 dd <<
"FileName points to a directory";
244 return Status(Status::INVALID_ARGUMENT, dd,
245 tr(
"Invalid Save Path"),
246 tr(
"The path (\"%1\") points to a directory.").arg(fileInfo.absoluteFilePath()));
248 QFileInfo parentDirInfo(fileInfo.dir().absolutePath());
249 if (!parentDirInfo.exists())
251 dd <<
"The parent directory of sFileName does not exist";
252 return Status(Status::INVALID_ARGUMENT, dd,
253 tr(
"Invalid Save Path"),
254 tr(
"The directory (\"%1\") does not exist.").arg(parentDirInfo.absoluteFilePath()));
256 if ((fileInfo.exists() && !fileInfo.isWritable()) || !parentDirInfo.isWritable())
258 dd <<
"Filename points to a location that is not writable";
259 return Status(Status::INVALID_ARGUMENT, dd,
260 tr(
"Invalid Save Path"),
261 tr(
"The path (\"%1\") is not writable.").arg(fileInfo.absoluteFilePath()));
268 bool isArchive = isArchiveFormat(sFileName);
271 dd <<
"Old Pencil2D File Format (*.pcl) !";
273 sMainXMLFile = sFileName;
274 sDataFolder = sMainXMLFile +
"." + PFF_OLD_DATA_DIR;
278 dd <<
"New zipped Pencil2D File Format (*.pclx) !";
279 dd.collect(MiniZ::sanityCheck(sFileName).details());
281 sTempWorkingFolder =
object->workingDir();
282 Q_ASSERT(
QDir(sTempWorkingFolder).exists());
283 dd <<
QString(
"TempWorkingFolder = ").
append(sTempWorkingFolder);
285 sMainXMLFile =
QDir(sTempWorkingFolder).
filePath(PFF_XML_FILE_NAME);
286 sDataFolder =
QDir(sTempWorkingFolder).
filePath(PFF_OLD_DATA_DIR);
290 if (!dataInfo.exists())
292 QDir dir(sDataFolder);
294 if (!dir.mkpath(sDataFolder))
296 dd <<
QString(
"dir.absolutePath() = %1").
arg(dir.absolutePath());
297 return Status(Status::FAIL, dd,
298 tr(
"Cannot Create Data Directory"),
299 tr(
"Failed to create directory \"%1\". Please make sure you have sufficient permissions.").arg(sDataFolder));
302 if (!dataInfo.isDir())
304 dd <<
QString(
"dataInfo.absoluteFilePath() = ").
append(dataInfo.absoluteFilePath());
305 return Status(Status::FAIL,
307 tr(
"Cannot Create Data Directory"),
308 tr(
"\"%1\" is a file. Please delete the file and try again.").arg(dataInfo.absoluteFilePath()));
312 Status stKeyFrames = writeKeyFrameFiles(
object, sDataFolder, filesToZip);
313 dd.collect(stKeyFrames.details());
315 Status stMainXml = writeMainXml(
object, sMainXMLFile, filesToZip);
316 dd.collect(stMainXml.details());
318 Status stPalette = writePalette(
object, sDataFolder, filesToZip);
319 dd.collect(stPalette.details());
321 const bool saveOk = stKeyFrames.ok() && stMainXml.ok() && stPalette.ok();
327 QString sBackupFile = backupPreviousFile(sFileName);
330 return Status(Status::FAIL, dd,
331 tr(
"Internal Error"),
332 tr(
"An internal error occurred. Your file may not be saved successfully."));
336 Status stMiniz = MiniZ::compressFolder(sFileName, sTempWorkingFolder, filesToZip,
"application/x-pencil2d-pclx");
339 dd.collect(stMiniz.details());
340 return Status(Status::ERROR_MINIZ_FAIL, dd,
342 tr(
"An internal error occurred. Your file may not be saved successfully."));
344 dd <<
"Zip file saved successfully";
345 Q_ASSERT(stMiniz.ok());
348 deleteBackupFile(sBackupFile);
355 return Status(Status::FAIL, dd,
356 tr(
"Internal Error"),
357 tr(
"An internal error occurred. Your file may not be saved successfully."));
363Status FileManager::writeToWorkingFolder(
const Object*
object)
369 const QString dataFolder =
object->dataDir();
370 const QString mainXml =
object->mainXMLFile();
372 Status stKeyFrames = writeKeyFrameFiles(
object, dataFolder, filesWritten);
373 dd.collect(stKeyFrames.details());
375 Status stMainXml = writeMainXml(
object, mainXml, filesWritten);
376 dd.collect(stMainXml.details());
378 Status stPalette = writePalette(
object, dataFolder, filesWritten);
379 dd.collect(stPalette.details());
381 const bool saveOk = stKeyFrames.ok() && stMainXml.ok() && stPalette.ok();
382 const auto errorCode = (saveOk) ? Status::OK : Status::FAIL;
383 return Status(errorCode, dd);
404 extractProjectData(element, data);
417 currentFrameTag.
setAttribute(
"value", data->getCurrentFrame());
422 QColor color = data->getCurrentColor();
431 currentLayerTag.
setAttribute(
"value", data->getCurrentLayer());
452 tagIsLoop.
setAttribute(
"value", data->isLooping() ?
"true" :
"false");
456 tagRangedPlayback.
setAttribute(
"value", data->isRangedPlayback() ?
"true" :
"false");
460 tagMarkInFrame.
setAttribute(
"value", data->getMarkInFrameNumber());
464 tagMarkOutFrame.
setAttribute(
"value", data->getMarkOutFrameNumber());
473 if (strName ==
"currentFrame")
477 else if (strName ==
"currentColor")
484 data.setCurrentColor(
QColor(r, g, b, a));
486 else if (strName ==
"currentLayer")
490 else if (strName ==
"currentView")
499 data.setCurrentView(
QTransform(m11, m12, m21, m22, dx, dy));
501 else if (strName ==
"fps" || strName ==
"currentFps")
505 else if (strName ==
"isLoop")
507 data.setLooping(element.
attribute(
"value",
"false") ==
"true");
509 else if (strName ==
"isRangedPlayback")
511 data.setRangedPlayback((element.
attribute(
"value",
"false") ==
"true"));
513 else if (strName ==
"markInFrame")
515 data.setMarkInFrameNumber(element.
attribute(
"value",
"0").
toInt());
517 else if (strName ==
"markOutFrame")
519 data.setMarkOutFrameNumber(element.
attribute(
"value",
"15").
toInt());
523void FileManager::handleOpenProjectError(Status::ErrorCode error,
const DebugDetails& dd)
525 QString title =
tr(
"Could not open file");
528 "<li><a href=\"https://discuss.pencil2d.org/c/bugs\">Pencil2D Forum</a></li>"
529 "<li><a href=\"https://github.com/pencil2d/pencil/issues/new\">Github</a></li>"
530 "<li><a href=\"https://discord.gg/8FxdV2g\">Discord<\a></li>"
533 if (error == Status::FILE_NOT_FOUND)
535 errorDesc =
tr(
"The file does not exist, so we are unable to open it."
536 "Please check to make sure the path is correct and try again.");
538 else if (error == Status::ERROR_FILE_CANNOT_OPEN)
540 errorDesc =
tr(
"No permission to read the file. "
541 "Please check you have read permissions for this file and try again.");
546 errorDesc =
tr(
"There was an error processing your file. "
547 "This usually means that your project has been at least partially corrupted. "
548 "Try again with a newer version of Pencil2D, "
549 "or try to use a backup file if you have one. "
550 "If you contact us through one of our official channels we may be able to help you."
551 "For reporting issues, the best places to reach us are:");
554 mError =
Status(error, dd, title, errorDesc + contactLinks);
555 removePFFTmpDirectory(mstrLastTempFolder);
558int FileManager::countExistingBackups(
const QString& fileName)
const
561 QDir directory(fileInfo.absoluteDir());
562 const QString& baseName = fileInfo.completeBaseName();
565 for (
const QFileInfo &dirFileInfo : directory.entryInfoList(QDir::Filter::Files)) {
566 QString searchFileBaseName = dirFileInfo.completeBaseName();
567 if (baseName.
compare(searchFileBaseName) == 0 && searchFileBaseName.
contains(PFF_BACKUP_IDENTIFIER)) {
581 QString baseName = fileInfo.completeBaseName();
583 int backupCount = countExistingBackups(fileName) + 1;
586 QString sBackupFile = baseName +
"." + PFF_BACKUP_IDENTIFIER + countStr +
"." + fileInfo.suffix();
589 bool ok =
QFile::copy(fileInfo.absoluteFilePath(), sBackupFileFullPath);
592 FILEMANAGER_LOG(
"Cannot backup the previous file");
595 return sBackupFileFullPath;
598void FileManager::deleteBackupFile(
const QString& fileName)
606void FileManager::progressForward()
609 emit progressChanged(mCurrentProgress);
612bool FileManager::loadPalette(
Object* obj)
614 FILEMANAGER_LOG(
"Load Palette..");
616 QString paletteFilePath = validateDataPath(PFF_PALETTE_FILE, obj->dataDir());
617 if (paletteFilePath.
isEmpty() || !obj->importPalette(paletteFilePath))
619 obj->loadDefaultPalette();
628 const int numLayers =
object->getLayerCount();
629 dd <<
QString(
"Total %1 layers").
arg(numLayers);
631 for (
int i = 0; i < numLayers; ++i)
633 Layer* layer =
object->getLayer(i);
634 layer->presave(dataFolder);
637 bool saveLayersOK =
true;
638 for (
int i = 0; i < numLayers; ++i)
640 Layer* layer =
object->getLayer(i);
642 dd <<
QString(
"Layer[%1] = [id=%2, type=%3, name=%4]").
arg(i).
arg(layer->id()).
arg(layer->type()).
arg(layer->name());
644 Status st = layer->save(dataFolder, filesFlushed, [
this] { progressForward(); });
647 saveLayersOK =
false;
648 dd.collect(st.details());
649 dd <<
QString(
" !! Failed to save Layer[%1] %2").
arg(i).
arg(layer->name());
652 dd <<
"All Layers saved";
656 auto errorCode = (saveLayersOK) ? Status::OK : Status::FAIL;
657 return Status(errorCode, dd);
664 QFile file(mainXmlPath);
667 dd <<
"Failed to open Main XML" << mainXmlPath;
668 return Status(Status::ERROR_FILE_CANNOT_OPEN, dd);
680 QDomElement projDataXml = saveProjectData(object->data(), xmlDoc);
684 QDomElement objectElement =
object->saveXML(xmlDoc);
692 dd <<
"Writing main xml file...";
694 const int indentSize = 2;
697 xmlDoc.
save(out, indentSize);
701 dd <<
"Done writing main xml file: " << mainXmlPath;
703 filesWritten.
append(mainXmlPath);
704 return Status(Status::OK, dd);
709 const QString paletteFile =
object->savePalette(dataFolder);
713 dd <<
"Failed to save palette";
714 return Status(Status::FAIL, dd);
716 filesWritten.
append(paletteFile);
723 removePFFTmpDirectory(strUnzipTarget);
725 Status s = MiniZ::uncompressFolder(strZipFile, strUnzipTarget);
728 mstrLastTempFolder = strUnzipTarget;
735 if (!fileInfo.exists())
747 int curLayer = obj->data()->getCurrentLayer();
748 int maxLayer = obj->getLayerCount();
749 if (curLayer >= maxLayer)
751 obj->data()->setCurrentLayer(maxLayer - 1);
755 std::vector<LayerCamera*> camLayers = obj->getLayersByType<
LayerCamera>();
756 if (camLayers.empty())
758 obj->addNewCameraLayer();
766 bool folderExists = pencil2DTempDir.
cd(
"Pencil2D");
772 const QStringList nameFilter(
"*_" PFF_TMP_DECOMPRESS_EXT
"_*");
776 for (
const QString& path : entries)
779 if (isProjectRecoverable(fullPath))
781 qDebug() <<
"Found debris at" << fullPath;
782 recoverables.
append(fullPath);
788bool FileManager::isProjectRecoverable(
const QString& projectFolder)
790 QDir dir(projectFolder);
791 if (!dir.exists()) {
return false; }
794 if (!dir.exists(
"data")) {
return false; }
796 bool ok = dir.cd(
"data");
800 nameFiler <<
"*.png" <<
"*.vec" <<
"*.xml";
803 return (entries.
size() > 0);
806Object* FileManager::recoverUnsavedProject(
QString intermeidatePath)
808 qDebug() <<
"TODO: recover project" << intermeidatePath;
810 QDir projectDir(intermeidatePath);
811 const QString mainXMLPath = projectDir.filePath(PFF_XML_FILE_NAME);
812 const QString dataFolder = projectDir.filePath(PFF_DATA_DIR);
814 std::unique_ptr<Object> object(
new Object);
815 object->setWorkingDir(intermeidatePath);
816 object->setMainXMLFile(mainXMLPath);
817 object->setDataDir(dataFolder);
819 Status st = recoverObject(
object.get());
826 return object.release();
832 bool mainXmlOK =
true;
834 QFile file(object->mainXMLFile());
835 mainXmlOK &= file.exists();
843 mainXmlOK &= (type.
name() ==
"PencilDocument" || type.
name() ==
"MyObject");
846 mainXmlOK &= (!root.
isNull());
849 mainXmlOK &= (!objectTag.
isNull());
851 if (mainXmlOK ==
false)
857 QFile file(object->mainXMLFile());
865 bool ok = loadObject(
object, root);
866 verifyObject(
object);
868 return ok ? Status::OK : Status::FAIL;
874 QDir dataDir(object->dataDir());
877 nameFiler <<
"*.png" <<
"*.vec";
883 for (
const QString& s : entries)
885 int layerIndex = layerIndexFromFilename(s);
888 keyFrameGroups[layerIndex].append(s);
893 const QString mainXMLPath =
object->mainXMLFile();
894 QFile file(mainXMLPath);
897 return Status::ERROR_FILE_CANNOT_OPEN;
907 QDomElement projDataXml = saveProjectData(object->data(), xmlDoc);
914 for (
const int layerIndex : keyFrameGroups.
keys())
921 xmlDoc.
save(fout, 2);
937 const int layerIndex,
940 Q_ASSERT(frames.
length() > 0);
942 Layer::LAYER_TYPE type = frames[0].
endsWith(
".png") ? Layer::BITMAP : Layer::VECTOR;
946 elemLayer.
setAttribute(
"name", recoverLayerName(type, layerIndex));
951 for (
const QString& s : frames)
953 const int framePos = framePosFromFilename(s);
954 if (framePos < 0) {
continue; }
960 if (type == Layer::BITMAP)
972QString FileManager::recoverLayerName(Layer::LAYER_TYPE type,
int index)
977 return tr(
"Bitmap Layer %1").
arg(index);
979 return tr(
"Vector Layer %1").
arg(index);
981 return tr(
"Sound Layer %1").
arg(index);
988int FileManager::layerIndexFromFilename(
const QString& filename)
993 return tokens[0].toInt();
998int FileManager::framePosFromFilename(
const QString& filename)
1001 if (tokens.
length() >= 3)
1003 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
virtual void close() 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