Debian Codegraph @

src/Gui/DocumentRecovery.cpp

raw
1 /***************************************************************************
2 * Copyright (c) 2015 Werner Mayer <wmayer[at]users.sourceforge.net> *
3 * *
4 * This file is part of the FreeCAD CAx development system. *
5 * *
6 * This library is free software; you can redistribute it and/or *
7 * modify it under the terms of the GNU Library General Public *
8 * License as published by the Free Software Foundation; either *
9 * version 2 of the License, or (at your option) any later version. *
10 * *
11 * This library is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU Library General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU Library General Public *
17 * License along with this library; see the file COPYING.LIB. If not, *
18 * write to the Free Software Foundation, Inc., 59 Temple Place, *
19 * Suite 330, Boston, MA 02111-1307, USA *
20 * *
21 ***************************************************************************/
22
23 // Implement FileWriter which puts files into a directory
24 // write a property to file only when it has been modified
25 // implement xml meta file
26
27
28 #include <boost/interprocess/sync/file_lock.hpp>
29 #include <QApplication>
30 #include <QCloseEvent>
31 #include <QDateTime>
32 #include <QDebug>
33 #include <QDir>
34 #include <QDomDocument>
35 #include <QFileInfo>
36 #include <QHeaderView>
37 #include <QList>
38 #include <QMap>
39 #include <QMenu>
40 #include <QMessageBox>
41 #include <QSet>
42 #include <QTextStream>
43 #include <QTreeWidgetItem>
44 #include <QXmlStreamReader>
45 #include <QVector>
46 #include <sstream>
47
48 #include <FCConfig.h>
49
50 #include <App/Application.h>
51 #include <App/Document.h>
52 #include <App/ProjectFile.h>
53 #include <Base/Exception.h>
54 #include <Gui/Application.h>
55 #include <Gui/Command.h>
56 #include <Gui/Dialogs/DlgCheckableMessageBox.h>
57 #include <Gui/Document.h>
58 #include <Gui/MainWindow.h>
59
60 #include "DocumentRecovery.h"
61 #include "ui_DocumentRecovery.h"
62 #include "WaitCursor.h"
63
64
65 FC_LOG_LEVEL_INIT("Gui", true, true)
66
67 using namespace Gui;
68 using namespace Gui::Dialog;
69 namespace sp = std::placeholders;
70
71 // taken from the script doctools.py
72 std::string DocumentRecovery::doctools
73 = "import os,sys,string\n"
74 "from defusedxml import sax as defused_sax\n"
75 "from xml.sax.handler import ContentHandler\n"
76 "import zipfile\n"
77 "\n"
78 "# SAX handler to parse the Document.xml\n"
79 "class DocumentHandler(ContentHandler):\n"
80 " def __init__(self, dirname):\n"
81 " self.files = []\n"
82 " self.dirname = dirname\n"
83 "\n"
84 " def startElement(self, name, attributes):\n"
85 " if name == 'XLink':\n"
86 " return\n"
87 " item=attributes.get(\"file\")\n"
88 " if item:\n"
89 " self.files.append(os.path.join(self.dirname,str(item)))\n"
90 "\n"
91 " def characters(self, data):\n"
92 " return\n"
93 "\n"
94 " def endElement(self, name):\n"
95 " return\n"
96 "\n"
97 "def extractDocument(filename, outpath):\n"
98 " zfile=zipfile.ZipFile(filename)\n"
99 " files=zfile.namelist()\n"
100 "\n"
101 " for i in files:\n"
102 " data=zfile.read(i)\n"
103 " dirs=i.split(\"/\")\n"
104 " if len(dirs) > 1:\n"
105 " dirs.pop()\n"
106 " curpath=outpath\n"
107 " for j in dirs:\n"
108 " curpath=curpath+\"/\"+j\n"
109 " os.mkdir(curpath)\n"
110 " output=open(outpath+\"/\"+i,'wb')\n"
111 " output.write(data)\n"
112 " output.close()\n"
113 "\n"
114 "def createDocument(filename, outpath):\n"
115 " files=getFilesList(filename)\n"
116 " dirname=os.path.dirname(filename)\n"
117 " guixml=os.path.join(dirname,\"GuiDocument.xml\")\n"
118 " if os.path.exists(guixml):\n"
119 " files.extend(getFilesList(guixml))\n"
120 " compress=zipfile.ZipFile(outpath,'w',zipfile.ZIP_DEFLATED)\n"
121 " for i in files:\n"
122 " dirs=os.path.split(i)\n"
123 " #print i, dirs[-1]\n"
124 " compress.write(i,dirs[-1],zipfile.ZIP_DEFLATED)\n"
125 " compress.close()\n"
126 "\n"
127 "def getFilesList(filename):\n"
128 " dirname=os.path.dirname(filename)\n"
129 " handler=DocumentHandler(dirname)\n"
130 " parser=defused_sax.make_parser()\n"
131 " parser.setContentHandler(handler)\n"
132 " parser.parse(filename)\n"
133 "\n"
134 " files=[]\n"
135 " files.append(filename)\n"
136 " files.extend(iter(handler.files))\n"
137 " return files\n";
138
139
140 namespace Gui
141 {
142 namespace Dialog
143 {
144 class DocumentRecoveryPrivate
145 {
146 public:
147 using XmlConfig = QMap<QString, QString>;
148
149 enum Status
150 {
151 Unknown = 0, /*!< The file is not available */
152 Created = 1, /*!< The file was created but not processed so far*/
153 Overage = 2, /*!< The recovery file is older than the actual project file */
154 Corrupted = 3, /*!< The original file is corrupted */
155 Success = 4, /*!< The file could be recovered */
156 Failure = 5 /*!< The file could not be recovered */
157 };
158 struct Info
159 {
160 QString projectFile;
161 QString xmlFile;
162 QString label;
163 QString fileName;
164 QString tooltip;
165 Status status = Unknown;
166 };
167 Ui_DocumentRecovery ui;
168 bool recovered;
169 QList<Info> recoveryInfo;
170
171 Info getRecoveryInfo(const QFileInfo&) const;
172 bool isValidProject(const QFileInfo&) const;
173 void writeRecoveryInfo(const Info&) const;
174 XmlConfig readXmlFile(const QString& fn) const;
175 };
176
177 } // namespace Dialog
178 } // namespace Gui
179
180 DocumentRecovery::DocumentRecovery(const QList<QFileInfo>& dirs, QWidget* parent)
181 : QDialog(parent)
182 , d_ptr(new DocumentRecoveryPrivate())
183 {
184 d_ptr->ui.setupUi(this);
185 connect(d_ptr->ui.buttonCleanup, &QPushButton::clicked, this, &DocumentRecovery::onButtonCleanupClicked);
186 d_ptr->ui.buttonBox->button(QDialogButtonBox::Ok)->setText(tr("Start Recovery"));
187 d_ptr->ui.treeWidget->header()->setSectionResizeMode(QHeaderView::Stretch);
188
189 d_ptr->recovered = false;
190
191 for (QList<QFileInfo>::const_iterator it = dirs.begin(); it != dirs.end(); ++it) {
192 DocumentRecoveryPrivate::Info info = d_ptr->getRecoveryInfo(*it);
193
194 if (info.status == DocumentRecoveryPrivate::Created
195 || info.status == DocumentRecoveryPrivate::Corrupted) {
196 d_ptr->recoveryInfo << info;
197
198 auto item = new QTreeWidgetItem(d_ptr->ui.treeWidget);
199 item->setText(0, info.label);
200 item->setToolTip(0, info.tooltip);
201 if (info.status == DocumentRecoveryPrivate::Corrupted) {
202 item->setText(1, tr("Original file corrupted"));
203 item->setForeground(1, QColor(170, 0, 0)); // TODO: Don't hardcode colors
204 }
205 else {
206 item->setText(1, tr("Not yet recovered"));
207 }
208 item->setToolTip(1, info.projectFile);
209 d_ptr->ui.treeWidget->addTopLevelItem(item);
210 }
211 }
212
213 this->adjustSize();
214 }
215
216 DocumentRecovery::~DocumentRecovery() = default;
217
218 bool DocumentRecovery::foundDocuments() const
219 {
220 Q_D(const DocumentRecovery);
221 return (!d->recoveryInfo.isEmpty());
222 }
223
224 QString DocumentRecovery::createProjectFile(const QString& documentXml)
225 {
226 QString source = documentXml;
227 QFileInfo fi(source);
228 QString dest = fi.dir().absoluteFilePath(QStringLiteral("fc_recovery_file.fcstd"));
229
230 std::stringstream str;
231 str << doctools << "\n";
232 str << "createDocument(\"" << (const char*)source.toUtf8() << "\", \""
233 << (const char*)dest.toUtf8() << "\")";
234 Gui::Command::runCommand(Gui::Command::App, str.str().c_str());
235
236 return dest;
237 }
238
239 void DocumentRecovery::closeEvent(QCloseEvent* e)
240 {
241 // Do not disable the X button in the title bar
242 // #0004281: Close Document Recovery
243 e->accept();
244 }
245
246 void DocumentRecovery::accept()
247 {
248 Q_D(DocumentRecovery);
249
250 if (!d->recovered) {
251
252 WaitCursor wc;
253 int index = 0;
254 std::vector<int> indices;
255 std::vector<std::string> filenames, paths, labels, errs;
256 for (auto& info : d->recoveryInfo) {
257 QString errorInfo;
258 QTreeWidgetItem* item = d_ptr->ui.treeWidget->topLevelItem(index);
259
260 try {
261 QString file = info.projectFile;
262 QFileInfo fi(file);
263 if (fi.fileName() == QLatin1String("Document.xml")) {
264 file = createProjectFile(info.projectFile);
265 }
266
267 paths.emplace_back(file.toUtf8().constData());
268 filenames.emplace_back(info.fileName.toUtf8().constData());
269 labels.emplace_back(info.label.toUtf8().constData());
270 indices.push_back(index);
271 ++index;
272 }
273 catch (const std::exception& e) {
274 errorInfo = QString::fromLatin1(e.what());
275 }
276 catch (const Base::Exception& e) {
277 errorInfo = QString::fromLatin1(e.what());
278 }
279 catch (...) {
280 errorInfo = tr("Unknown problem occurred");
281 }
282
283 if (!errorInfo.isEmpty()) {
284 info.status = DocumentRecoveryPrivate::Failure;
285 if (item) {
286 item->setText(1, tr("Failed to recover"));
287 item->setToolTip(1, errorInfo);
288 item->setForeground(1, QColor(170, 0, 0));
289 }
290 d->writeRecoveryInfo(info);
291 }
292 }
293
294 auto docs = App::GetApplication().openDocuments(filenames, &paths, &labels, &errs);
295
296 for (size_t i = 0; i < docs.size(); ++i) {
297 auto& info = d->recoveryInfo[indices[i]];
298 QTreeWidgetItem* item = d_ptr->ui.treeWidget->topLevelItem(indices[i]);
299 if (!docs[i] || !errs[i].empty()) {
300 if (docs[i]) {
301 App::GetApplication().closeDocument(docs[i]->getName());
302 }
303 info.status = DocumentRecoveryPrivate::Failure;
304
305 if (item) {
306 item->setText(1, tr("Failed to recover"));
307 item->setToolTip(1, QString::fromUtf8(errs[i].c_str()));
308 item->setForeground(1, QColor(170, 0, 0));
309 }
310 // write back current status
311 d->writeRecoveryInfo(info);
312 }
313 else {
314 auto gdoc = Application::Instance->getDocument(docs[i]);
315 if (gdoc) {
316 gdoc->setModified(true);
317 }
318
319 info.status = DocumentRecoveryPrivate::Success;
320 if (item) {
321 item->setText(1, tr("Successfully recovered"));
322 item->setForeground(1, QColor(0, 170, 0));
323 }
324
325 QDir transDir(QString::fromUtf8(docs[i]->TransientDir.getValue()));
326
327 QFileInfo xfi(info.xmlFile);
328 QFileInfo fi(info.projectFile);
329 bool res = false;
330
331 if (fi.fileName() == QLatin1String("fc_recovery_file.fcstd")) {
332 transDir.remove(fi.fileName());
333 res = transDir.rename(fi.absoluteFilePath(), fi.fileName());
334 }
335 else {
336 transDir.rmdir(fi.dir().dirName());
337 res = transDir.rename(fi.absolutePath(), fi.dir().dirName());
338 }
339
340 if (res) {
341 transDir.remove(xfi.fileName());
342 res = transDir.rename(xfi.absoluteFilePath(), xfi.fileName());
343 }
344
345 if (!res) {
346 FC_WARN(
347 "Failed to move recovery file of document '" << docs[i]->Label.getValue() << "'"
348 );
349 }
350 else {
351 DocumentRecoveryCleaner().clearDirectory(QFileInfo(xfi.absolutePath()));
352 QDir().rmdir(xfi.absolutePath());
353 }
354
355 // DO NOT write success into recovery info, in case the program
356 // crash again before the user save the just recovered file.
357 }
358 }
359
360 d->ui.buttonBox->button(QDialogButtonBox::Ok)->setText(tr("&Finish"));
361 d->ui.buttonBox->button(QDialogButtonBox::Cancel)->setEnabled(false);
362 d->recovered = true;
363 }
364 else {
365 QDialog::accept();
366 }
367 }
368
369 void DocumentRecoveryPrivate::writeRecoveryInfo(const DocumentRecoveryPrivate::Info& info) const
370 {
371 // Write recovery meta file
372 QFile file(info.xmlFile);
373 if (file.open(QFile::WriteOnly)) {
374 QTextStream str(&file);
375 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
376 str.setCodec("UTF-8");
377 #endif
378 str << "<?xml version='1.0' encoding='utf-8'?>\n"
379 << "<AutoRecovery SchemaVersion=\"1\">\n";
380 switch (info.status) {
381 case Created:
382 str << " <Status>Created</Status>\n";
383 break;
384 case Overage:
385 str << " <Status>Deprecated</Status>\n";
386 break;
387 case Corrupted:
388 str << " <Status>Corrupted</Status>\n";
389 break;
390 case Success:
391 str << " <Status>Success</Status>\n";
392 break;
393 case Failure:
394 str << " <Status>Failure</Status>\n";
395 break;
396 default:
397 str << " <Status>Unknown</Status>\n";
398 break;
399 }
400 str << " <Label>" << info.label << "</Label>\n";
401 str << " <FileName>" << info.fileName << "</FileName>\n";
402 str << "</AutoRecovery>\n";
403 file.close();
404 }
405 }
406
407
408 DocumentRecoveryPrivate::Info DocumentRecoveryPrivate::getRecoveryInfo(const QFileInfo& fi) const
409 {
410 DocumentRecoveryPrivate::Info info;
411 info.status = DocumentRecoveryPrivate::Unknown;
412 info.label = qApp->translate("StdCmdNew", "Unnamed");
413
414 QString file;
415 QDir doc_dir(fi.absoluteFilePath());
416 QDir rec_dir(doc_dir.absoluteFilePath(QLatin1String("fc_recovery_files")));
417
418 // compressed recovery file
419 if (doc_dir.exists(QLatin1String("fc_recovery_file.fcstd"))) {
420 file = doc_dir.absoluteFilePath(QLatin1String("fc_recovery_file.fcstd"));
421 }
422 // separate files for recovery
423 else if (rec_dir.exists(QLatin1String("Document.xml"))) {
424 file = rec_dir.absoluteFilePath(QLatin1String("Document.xml"));
425 }
426
427 info.status = DocumentRecoveryPrivate::Created;
428 info.projectFile = file;
429 info.tooltip = fi.fileName();
430
431 // when the Xml meta exists get some relevant information
432 info.xmlFile = doc_dir.absoluteFilePath(QLatin1String("fc_recovery_file.xml"));
433 if (doc_dir.exists(QLatin1String("fc_recovery_file.xml"))) {
434 XmlConfig cfg = readXmlFile(info.xmlFile);
435
436 if (cfg.contains(QStringLiteral("Label"))) {
437 info.label = cfg[QStringLiteral("Label")];
438 }
439
440 if (cfg.contains(QStringLiteral("FileName"))) {
441 info.fileName = cfg[QStringLiteral("FileName")];
442 }
443
444 if (cfg.contains(QStringLiteral("Status"))) {
445 QString status = cfg[QStringLiteral("Status")];
446 if (status == QLatin1String("Deprecated")) {
447 info.status = DocumentRecoveryPrivate::Overage;
448 }
449 if (status == QLatin1String("Corrupted")) {
450 info.status = DocumentRecoveryPrivate::Corrupted;
451 }
452 else if (status == QLatin1String("Success")) {
453 info.status = DocumentRecoveryPrivate::Success;
454 }
455 else if (status == QLatin1String("Failure")) {
456 info.status = DocumentRecoveryPrivate::Failure;
457 }
458 }
459
460 if (info.status == DocumentRecoveryPrivate::Created) {
461 // compare the modification dates
462 QFileInfo fileInfo(info.fileName);
463 if (!info.fileName.isEmpty()) {
464 if (isValidProject(fileInfo)) {
465 QDateTime dateRecv = QFileInfo(file).lastModified();
466 QDateTime dateProj = fileInfo.lastModified();
467 if (dateRecv < dateProj) {
468 info.status = DocumentRecoveryPrivate::Overage;
469 writeRecoveryInfo(info);
470 qWarning() << "Ignore recovery file " << file.toUtf8()
471 << " because it is older than the project file"
472 << info.fileName.toUtf8() << "\n";
473 }
474 }
475 else {
476 info.status = DocumentRecoveryPrivate::Corrupted;
477 writeRecoveryInfo(info);
478 qWarning() << "Original project file is corrupted: " << info.fileName << "\n";
479 }
480 }
481 }
482 }
483
484 return info;
485 }
486
487
488 /// Rough check to see if the ZIP data is valid. No CRC calculation, just a fast iteration over the
489 /// contents to see if it seems basically OK.
490 bool zipDataIsValid(const QString& zipData)
491 {
492 try {
493 zipios::ZipFile zf(zipData.toStdString());
494 auto entries = zf.entries();
495 int n = 0;
496 for (auto it = entries.begin(); it != entries.end(); ++it) {
497 auto s = zf.getInputStream(*it);
498 if (!s || !(*s)) {
499 return false;
500 }
501 ++n;
502 }
503 if (n == 0) {
504 return false;
505 }
506 return true;
507 }
508 catch (...) {
509 return false;
510 }
511 }
512
513 static zipios::ConstEntryPointer findEntry(zipios::ZipFile& zf, const std::string& name)
514 {
515 auto entries = zf.entries();
516 for (auto it = entries.begin(); it != entries.end(); ++it) {
517 if ((*it)->getName() == name) {
518 return *it;
519 }
520 }
521 return {};
522 }
523
524 bool xmlFilesAreValid(const QString& fcstdFile)
525 {
526 try {
527 zipios::ZipFile zf(fcstdFile.toStdString());
528 auto doc = findEntry(zf, "Document.xml");
529 if (!doc) {
530 return false;
531 }
532 {
533 auto s = zf.getInputStream(doc);
534 QByteArray bytes;
535 bytes.resize(0);
536 std::string tmp((std::istreambuf_iterator<char>(*s)), std::istreambuf_iterator<char>());
537 QXmlStreamReader xr(QByteArray(tmp.data(), int(tmp.size())));
538 while (!xr.atEnd()) {
539 xr.readNext();
540 }
541 if (xr.hasError()) {
542 return false;
543 }
544 }
545
546 // GuiDocument.xml is optional, but if it's present it must be well-formed
547 if (auto gui = findEntry(zf, "GuiDocument.xml")) {
548 auto s = zf.getInputStream(gui);
549 std::string tmp((std::istreambuf_iterator<char>(*s)), std::istreambuf_iterator<char>());
550 QXmlStreamReader xr(QByteArray(tmp.data(), int(tmp.size())));
551 while (!xr.atEnd()) {
552 xr.readNext();
553 }
554 if (xr.hasError()) {
555 return false;
556 }
557 }
558
559 return true;
560 }
561 catch (...) {
562 return false;
563 }
564 }
565
566 bool DocumentRecoveryPrivate::isValidProject(const QFileInfo& fi) const
567 {
568 if (!fi.exists()) {
569 return false;
570 }
571
572 if (!zipDataIsValid(fi.fileName())) {
573 return false;
574 }
575
576 if (!xmlFilesAreValid(fi.fileName())) {
577 return false;
578 }
579
580 App::ProjectFile project(fi.absoluteFilePath().toStdString());
581 return project.loadDocument();
582 }
583
584 DocumentRecoveryPrivate::XmlConfig DocumentRecoveryPrivate::readXmlFile(const QString& fn) const
585 {
586 DocumentRecoveryPrivate::XmlConfig cfg;
587 QDomDocument domDocument;
588 QFile file(fn);
589 if (!file.open(QFile::ReadOnly)) {
590 return cfg;
591 }
592
593 #if QT_VERSION >= QT_VERSION_CHECK(6, 5, 0)
594 if (!domDocument.setContent(&file, QDomDocument::ParseOption::UseNamespaceProcessing)) {
595 return cfg;
596 }
597 #else
598 QString errorStr;
599 int errorLine;
600 int errorColumn;
601
602 if (!domDocument.setContent(&file, true, &errorStr, &errorLine, &errorColumn)) {
603 return cfg;
604 }
605 #endif
606
607 QDomElement root = domDocument.documentElement();
608 if (root.tagName() != QLatin1String("AutoRecovery")) {
609 return cfg;
610 }
611
612 file.close();
613
614 QVector<QString> filter;
615 filter << QStringLiteral("Label");
616 filter << QStringLiteral("FileName");
617 filter << QStringLiteral("Status");
618
619 QDomElement child;
620 if (!root.isNull()) {
621 child = root.firstChildElement();
622 while (!child.isNull()) {
623 QString name = child.localName();
624 const QString value = child.text();
625 if (filter.contains(name)) {
626 cfg[name] = value;
627 }
628 child = child.nextSiblingElement();
629 }
630 }
631
632 return cfg;
633 }
634
635 void DocumentRecovery::contextMenuEvent(QContextMenuEvent* ev)
636 {
637 QList<QTreeWidgetItem*> items = d_ptr->ui.treeWidget->selectedItems();
638 if (!items.isEmpty()) {
639 QMenu menu;
640 menu.addAction(tr("Delete"), this, &DocumentRecovery::onDeleteSection);
641 menu.exec(ev->globalPos());
642 }
643 }
644
645 void DocumentRecovery::onDeleteSection()
646 {
647 QMessageBox msgBox(this);
648 msgBox.setIcon(QMessageBox::Warning);
649 msgBox.setWindowTitle(tr("Cleanup"));
650 msgBox.setText(tr("Delete the selected transient directories?"));
651 msgBox.setInformativeText(
652 tr("When deleting the selected transient directory it is not possible to recover any files "
653 "afterwards.")
654 );
655 msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
656 msgBox.setDefaultButton(QMessageBox::No);
657 int ret = msgBox.exec();
658 if (ret == QMessageBox::No) {
659 return;
660 }
661
662 QList<QTreeWidgetItem*> items = d_ptr->ui.treeWidget->selectedItems();
663 QDir tmp = QString::fromUtf8(App::Application::getUserCachePath().c_str());
664 for (QList<QTreeWidgetItem*>::iterator it = items.begin(); it != items.end(); ++it) {
665 int index = d_ptr->ui.treeWidget->indexOfTopLevelItem(*it);
666 QTreeWidgetItem* item = d_ptr->ui.treeWidget->takeTopLevelItem(index);
667
668 QString projectFile = item->toolTip(0);
669 DocumentRecoveryCleaner().clearDirectory(QFileInfo(tmp.filePath(projectFile)));
670 tmp.rmdir(projectFile);
671 delete item;
672 }
673
674 int numItems = d_ptr->ui.treeWidget->topLevelItemCount();
675 if (numItems == 0) {
676 d_ptr->ui.buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
677 d_ptr->ui.buttonBox->button(QDialogButtonBox::Cancel)->setEnabled(true);
678 }
679 }
680
681 void DocumentRecovery::onButtonCleanupClicked()
682 {
683 QMessageBox msgBox(this);
684 msgBox.setIcon(QMessageBox::Warning);
685 msgBox.setWindowTitle(tr("Cleanup"));
686 msgBox.setText(tr("Delete all transient directories?"));
687 msgBox.setInformativeText(tr("When deleting all transient directories it is not possible to recover any files afterwards."));
688 msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
689 msgBox.setDefaultButton(QMessageBox::No);
690 int ret = msgBox.exec();
691 if (ret == QMessageBox::No) {
692 return;
693 }
694
695 d_ptr->ui.treeWidget->clear();
696 d_ptr->ui.buttonCleanup->setEnabled(false);
697 d_ptr->ui.buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
698 d_ptr->ui.buttonBox->button(QDialogButtonBox::Cancel)->setEnabled(true);
699
700 DocumentRecoveryHandler handler;
701 handler.checkForPreviousCrashes(
702 std::bind(&DocumentRecovery::cleanup, this, sp::_1, sp::_2, sp::_3)
703 );
704 DlgCheckableMessageBox::showMessage(tr("Delete"), tr("Transient directories deleted."));
705 reject();
706 }
707
708 void DocumentRecovery::cleanup(QDir& tmp, const QList<QFileInfo>& dirs, const QString& lockFile)
709 {
710 if (!dirs.isEmpty()) {
711 for (QList<QFileInfo>::const_iterator jt = dirs.cbegin(); jt != dirs.cend(); ++jt) {
712 DocumentRecoveryCleaner().clearDirectory(*jt);
713 tmp.rmdir(jt->fileName());
714 }
715 }
716 tmp.remove(lockFile);
717 }
718
719 // ----------------------------------------------------------------------------
720
721 bool DocumentRecoveryFinder::checkForPreviousCrashes()
722 {
723 // NOLINTBEGIN
724 DocumentRecoveryHandler handler;
725 handler.checkForPreviousCrashes(
726 std::bind(&DocumentRecoveryFinder::checkDocumentDirs, this, sp::_1, sp::_2, sp::_3)
727 );
728 // NOLINTEND
729
730 return showRecoveryDialogIfNeeded();
731 }
732
733 void DocumentRecoveryFinder::checkDocumentDirs(QDir& tmp, const QList<QFileInfo>& dirs, const QString& fn)
734 {
735 if (dirs.isEmpty()) {
736 // delete the lock file immediately if no transient directories are related
737 tmp.remove(fn);
738 }
739 else {
740 int countDeletedDocs = 0;
741 QString recovery_files = QStringLiteral("fc_recovery_files");
742 for (QList<QFileInfo>::const_iterator it = dirs.cbegin(); it != dirs.cend(); ++it) {
743 QDir doc_dir(it->absoluteFilePath());
744 doc_dir.setFilter(QDir::NoDotAndDotDot | QDir::AllEntries);
745 uint entries = doc_dir.entryList().count();
746 if (entries == 0) {
747 // in this case we can delete the transient directory because
748 // we cannot do anything
749 if (tmp.rmdir(it->filePath())) {
750 countDeletedDocs++;
751 }
752 }
753 // search for the existence of a recovery file
754 else if (doc_dir.exists(QLatin1String("fc_recovery_file.xml"))) {
755 // store the transient directory in case it's not empty
756 restoreDocFiles << *it;
757 }
758 // search for the 'fc_recovery_files' sub-directory and check that it's the only entry
759 else if (entries == 1 && doc_dir.exists(recovery_files)) {
760 // if the sub-directory is empty delete the transient directory
761 QDir rec_dir(doc_dir.absoluteFilePath(recovery_files));
762 rec_dir.setFilter(QDir::NoDotAndDotDot | QDir::AllEntries);
763 if (rec_dir.entryList().isEmpty()) {
764 doc_dir.rmdir(recovery_files);
765 if (tmp.rmdir(it->filePath())) {
766 countDeletedDocs++;
767 }
768 }
769 }
770 }
771
772 // all directories corresponding to the lock file have been deleted
773 // so delete the lock file, too
774 if (countDeletedDocs == dirs.size()) {
775 tmp.remove(fn);
776 }
777 }
778 }
779
780 bool DocumentRecoveryFinder::showRecoveryDialogIfNeeded()
781 {
782 bool foundRecoveryFiles = false;
783 if (!restoreDocFiles.isEmpty()) {
784 Gui::Dialog::DocumentRecovery dlg(restoreDocFiles, Gui::getMainWindow());
785 if (dlg.foundDocuments()) {
786 foundRecoveryFiles = true;
787 dlg.exec();
788 }
789 }
790
791 return foundRecoveryFiles;
792 }
793
794 // ----------------------------------------------------------------------------
795
796 void DocumentRecoveryHandler::checkForPreviousCrashes(
797 const std::function<void(QDir&, const QList<QFileInfo>&, const QString&)>& callableFunc
798 ) const
799 {
800 QDir tmp = QString::fromUtf8(App::Application::getUserCachePath().c_str());
801 tmp.setNameFilters(QStringList() << QStringLiteral("*.lock"));
802 tmp.setFilter(QDir::Files);
803
804 QString exeName = QString::fromStdString(App::Application::getExecutableName());
805 QList<QFileInfo> locks = tmp.entryInfoList();
806 for (const QFileInfo& it : locks) {
807 QString bn = it.baseName();
808 // ignore the lock file for this instance
809 QString pid = QString::number(App::Application::applicationPid());
810 if (bn.startsWith(exeName) && bn.indexOf(pid) < 0) {
811 QString fn = it.absoluteFilePath();
812
813 #if !defined(FC_OS_WIN32) || (BOOST_VERSION < 107600)
814 boost::interprocess::file_lock flock(fn.toUtf8());
815 #else
816 boost::interprocess::file_lock flock(fn.toStdWString().c_str());
817 #endif
818 if (flock.try_lock()) {
819 // OK, this file is a leftover from a previous crash
820 QString crashed_pid = bn.mid(exeName.length() + 1);
821 // search for transient directories with this PID
822 QString filter;
823 QTextStream str(&filter);
824 str << exeName << "_Doc_*_" << crashed_pid;
825 tmp.setNameFilters(QStringList() << filter);
826 tmp.setFilter(QDir::Dirs);
827 QList<QFileInfo> dirs = tmp.entryInfoList();
828
829 callableFunc(tmp, dirs, it.fileName());
830 }
831 else {
832 Base::Console().log("Failed to lock file %s\n", fn.toUtf8().constData());
833 }
834 }
835 }
836 }
837
838 // ----------------------------------------------------------------------------
839
840 void DocumentRecoveryCleaner::clearDirectory(const QFileInfo& dir)
841 {
842 QDir qThisDir(dir.absoluteFilePath());
843 if (!qThisDir.exists()) {
844 return;
845 }
846
847 // Remove all files in this directory
848 qThisDir.setFilter(QDir::Files);
849 QStringList files = qThisDir.entryList();
850 subtractFiles(files);
851 for (QStringList::iterator it = files.begin(); it != files.end(); ++it) {
852 QString file = *it;
853 qThisDir.remove(file);
854 }
855
856 // Clear this directory of any sub-directories
857 qThisDir.setFilter(QDir::Dirs | QDir::NoDotAndDotDot);
858 QFileInfoList subdirs = qThisDir.entryInfoList();
859 subtractDirs(subdirs);
860 for (QFileInfoList::iterator it = subdirs.begin(); it != subdirs.end(); ++it) {
861 clearDirectory(*it);
862 qThisDir.rmdir(it->fileName());
863 }
864 }
865
866 void DocumentRecoveryCleaner::subtractFiles(QStringList& files)
867 {
868 if (!ignoreFiles.isEmpty() && !files.isEmpty()) {
869 auto set1 = QSet<QString>(files.begin(), files.end());
870 auto set2 = QSet<QString>(ignoreFiles.begin(), ignoreFiles.end());
871 set1.subtract(set2);
872 files = QList<QString>(set1.begin(), set1.end());
873 }
874 }
875
876 void DocumentRecoveryCleaner::subtractDirs(QFileInfoList& dirs)
877 {
878 if (!ignoreDirs.isEmpty() && !dirs.isEmpty()) {
879 for (const auto& it : std::as_const(ignoreDirs)) {
880 dirs.removeOne(it);
881 }
882 }
883 }
884
885 void DocumentRecoveryCleaner::setIgnoreFiles(const QStringList& list)
886 {
887 ignoreFiles = list;
888 }
889
890 void DocumentRecoveryCleaner::setIgnoreDirectories(const QFileInfoList& list)
891 {
892 ignoreDirs = list;
893 }
894
895 #include "moc_DocumentRecovery.cpp"