Debian Codegraph @

src/Gui/AutoSaver.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 #include <QApplication>
24 #include <QFile>
25 #include <QDir>
26 #include <QRunnable>
27 #include <QTextStream>
28 #include <QThreadPool>
29
30 #include <App/Application.h>
31 #include <App/Document.h>
32 #include <App/DocumentObject.h>
33 #include <Base/Console.h>
34 #include <Base/FileInfo.h>
35 #include <Base/Stream.h>
36 #include <Base/TimeInfo.h>
37 #include <Base/Tools.h>
38 #include <Base/Writer.h>
39
40 #include "AutoSaver.h"
41 #include "Document.h"
42 #include "MainWindow.h"
43 #include "ViewProvider.h"
44 #include "WaitCursor.h"
45
46 FC_LOG_LEVEL_INIT("App", true, true)
47
48 using namespace Gui;
49 namespace sp = std::placeholders;
50
51 AutoSaver* AutoSaver::self = nullptr;
52 const int AutoSaveTimeout = 900000;
53
54 AutoSaver::AutoSaver(QObject* parent)
55 : QObject(parent)
56 , timeout(AutoSaveTimeout)
57 , compressed(true)
58 {
59 // NOLINTBEGIN
60 App::GetApplication().signalNewDocument.connect(
61 std::bind(&AutoSaver::slotCreateDocument, this, sp::_1)
62 );
63 App::GetApplication().signalDeleteDocument.connect(
64 std::bind(&AutoSaver::slotDeleteDocument, this, sp::_1)
65 );
66 // NOLINTEND
67 }
68
69 AutoSaver::~AutoSaver() = default;
70
71 AutoSaver* AutoSaver::instance()
72 {
73 if (!self) {
74 self = new AutoSaver(QApplication::instance());
75 }
76 return self;
77 }
78
79 void AutoSaver::renameFile(QString dirName, QString file, QString tmpFile)
80 {
81 FC_LOG("auto saver rename " << tmpFile.toUtf8().constData() << " -> " << file.toUtf8().constData());
82 QDir dir(dirName);
83 dir.remove(file);
84 if (!dir.rename(tmpFile, file)) {
85 FC_ERR(
86 "Failed to rename autosave file " << tmpFile.toStdString() << " to "
87 << file.toStdString() << "\n"
88 );
89 }
90 }
91
92 void AutoSaver::setTimeout(int ms)
93 {
94 timeout = Base::clamp<int>(ms, 0, 3600000); // between 0 and 60 min
95
96 // go through the attached documents and apply the new timeout
97 for (auto& it : saverMap) {
98 if (it.second->timerId > 0) {
99 killTimer(it.second->timerId);
100 }
101 int id = timeout > 0 ? startTimer(timeout) : 0;
102 it.second->timerId = id;
103 }
104 }
105
106 void AutoSaver::setCompressed(bool on)
107 {
108 this->compressed = on;
109 }
110
111 void AutoSaver::slotCreateDocument(const App::Document& Doc)
112 {
113 std::string name = Doc.getName();
114 int id = timeout > 0 ? startTimer(timeout) : 0;
115 AutoSaveProperty* as = new AutoSaveProperty(&Doc);
116 as->timerId = id;
117
118 if (!this->compressed) {
119 std::string dirName = Doc.TransientDir.getValue();
120 dirName += "/fc_recovery_files";
121 Base::FileInfo fi(dirName);
122 fi.createDirectory();
123 as->dirName = dirName;
124 }
125 saverMap.insert(std::make_pair(name, as));
126 }
127
128 void AutoSaver::slotDeleteDocument(const App::Document& Doc)
129 {
130 std::string name = Doc.getName();
131 std::map<std::string, AutoSaveProperty*>::iterator it = saverMap.find(name);
132 if (it != saverMap.end()) {
133 if (it->second->timerId > 0) {
134 killTimer(it->second->timerId);
135 }
136 delete it->second;
137 saverMap.erase(it);
138 }
139 }
140
141 void AutoSaver::saveDocument(const std::string& name, AutoSaveProperty& saver)
142 {
143 Gui::WaitCursor wc;
144 App::Document* doc = App::GetApplication().getDocument(name.c_str());
145 if (doc && !doc->testStatus(App::Document::PartialDoc)
146 && !doc->testStatus(App::Document::TempDoc)) {
147 // Set the document's current transient directory
148 std::string dirName = doc->TransientDir.getValue();
149 dirName += "/fc_recovery_files";
150 saver.dirName = dirName;
151
152 // Write recovery meta file
153 QFile file(QStringLiteral("%1/fc_recovery_file.xml")
154 .arg(QString::fromUtf8(doc->TransientDir.getValue())));
155 if (file.open(QFile::WriteOnly)) {
156 QTextStream str(&file);
157 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
158 str.setCodec("UTF-8");
159 #endif
160 str << "<?xml version='1.0' encoding='utf-8'?>\n"
161 << "<AutoRecovery SchemaVersion=\"1\">\n";
162 str << " <Status>Created</Status>\n";
163 str << " <Label>" << QString::fromUtf8(doc->Label.getValue())
164 << "</Label>\n"; // store the document's current label
165 str << " <FileName>" << QString::fromUtf8(doc->FileName.getValue())
166 << "</FileName>\n"; // store the document's current filename
167 str << "</AutoRecovery>\n";
168 file.close();
169 }
170
171 // make sure to tmp. disable saving thumbnails because this causes trouble if the
172 // associated 3d view is not active
173 Base::Reference<ParameterGrp> hGrp = App::GetApplication().GetParameterGroupByPath(
174 "User parameter:BaseApp/Preferences/Document"
175 );
176 bool save = hGrp->GetBool("SaveThumbnail", true);
177 hGrp->SetBool("SaveThumbnail", false);
178
179 getMainWindow()->showMessage(tr("Wait until the auto-recovery file has been saved…"), 5000);
180 // qApp->processEvents();
181
182 Base::TimeElapsed startTime;
183 // open extra scope to close ZipWriter properly
184 {
185 if (!this->compressed) {
186 RecoveryWriter writer(saver);
187
188 // We will be using thread pool if not compressed.
189 // So, always force binary format because ASCII
190 // is not reentrant. See PropertyPartShape::SaveDocFile
191 writer.setMode("BinaryBrep");
192
193 writer.putNextEntry("Document.xml");
194
195 doc->Save(writer);
196
197 // Special handling for Gui document.
198 doc->signalSaveDocument(writer);
199
200 // write additional files
201 writer.writeFiles();
202 }
203 // only create the file if something has changed
204 else if (!saver.touched.empty()) {
205 std::string fn = doc->TransientDir.getValue();
206 fn += "/fc_recovery_file.fcstd";
207 Base::FileInfo tmp(fn);
208 Base::ofstream file(tmp, std::ios::out | std::ios::binary);
209 if (file.is_open()) {
210 Base::ZipWriter writer(file);
211 if (hGrp->GetBool("SaveBinaryBrep", true)) {
212 writer.setMode("BinaryBrep");
213 }
214
215 writer.setComment("AutoRecovery file");
216 writer.setLevel(1); // apparently the fastest compression
217 writer.putNextEntry("Document.xml");
218
219 doc->Save(writer);
220
221 // Special handling for Gui document.
222 doc->signalSaveDocument(writer);
223
224 // write additional files
225 writer.writeFiles();
226 }
227 }
228 }
229
230 Base::Console().log(
231 "Save auto-recovery file in %fs\n",
232 Base::TimeElapsed::diffTimeF(startTime, Base::TimeElapsed())
233 );
234 hGrp->SetBool("SaveThumbnail", save);
235 }
236 }
237
238 void AutoSaver::timerEvent(QTimerEvent* event)
239 {
240 int id = event->timerId();
241 for (auto& it : saverMap) {
242 if (it.second->timerId == id) {
243 try {
244 saveDocument(it.first, *it.second);
245 it.second->touched.clear();
246 break;
247 }
248 catch (...) {
249 Base::Console().error("Failed to auto-save document '%s'\n", it.first.c_str());
250 }
251 }
252 }
253 }
254
255 // ----------------------------------------------------------------------------
256
257 AutoSaveProperty::AutoSaveProperty(const App::Document* doc)
258 : timerId(-1)
259 {
260 // NOLINTBEGIN
261 documentNew = const_cast<App::Document*>(doc)->signalNewObject.connect(
262 std::bind(&AutoSaveProperty::slotNewObject, this, sp::_1)
263 );
264 documentMod = const_cast<App::Document*>(doc)->signalChangedObject.connect(
265 std::bind(&AutoSaveProperty::slotChangePropertyData, this, sp::_2)
266 );
267 // NOLINTEND
268 }
269
270 AutoSaveProperty::~AutoSaveProperty()
271 {
272 documentNew.disconnect();
273 documentMod.disconnect();
274 }
275
276 void AutoSaveProperty::slotNewObject(const App::DocumentObject& obj)
277 {
278 std::vector<App::Property*> props;
279 obj.getPropertyList(props);
280
281 // if an object was deleted and then restored by an undo then add all properties
282 // because this might be the data files which we may want to re-write
283 for (const auto& prop : props) {
284 slotChangePropertyData(*prop);
285 }
286 }
287
288 void AutoSaveProperty::slotChangePropertyData(const App::Property& prop)
289 {
290 std::stringstream str;
291 str << static_cast<const void*>(&prop) << std::ends;
292 std::string address = str.str();
293 this->touched.insert(address);
294 }
295
296 // ----------------------------------------------------------------------------
297
298 RecoveryWriter::RecoveryWriter(AutoSaveProperty& saver)
299 : Base::FileWriter(saver.dirName.c_str())
300 , saver(saver)
301 {}
302
303 RecoveryWriter::~RecoveryWriter() = default;
304
305 bool RecoveryWriter::shouldWrite(const std::string& name, const Base::Persistence* object) const
306 {
307 // Property files of a view provider can always be written because
308 // these are rather small files.
309 if (object->isDerivedFrom<App::Property>()) {
310 const auto* prop = static_cast<const App::Property*>(object);
311 const App::PropertyContainer* parent = prop->getContainer();
312 if (parent && parent->isDerivedFrom<Gui::ViewProvider>()) {
313 return true;
314 }
315 }
316 else if (object->isDerivedFrom<Gui::Document>()) {
317 return true;
318 }
319
320 // These are the addresses of touched properties of a document object.
321 std::stringstream str;
322 str << static_cast<const void*>(object) << std::ends;
323 std::string address = str.str();
324
325 // Check if the property will be exported to the same file. If the file has changed or if the
326 // property hasn't been yet exported then (re-)write the file.
327 std::map<std::string, std::string>::iterator it = saver.fileMap.find(address);
328 if (it == saver.fileMap.end() || it->second != name) {
329 saver.fileMap[address] = name;
330 return true;
331 }
332
333 std::set<std::string>::const_iterator jt = saver.touched.find(address);
334 return (jt != saver.touched.end());
335 }
336
337 namespace Gui
338 {
339
340 class RecoveryRunnable: public QRunnable
341 {
342 public:
343 RecoveryRunnable(
344 const std::set<std::string>& modes,
345 const char* dir,
346 const char* file,
347 const App::Property* p
348 )
349 : prop(p->Copy())
350 , writer(dir)
351 {
352 writer.setModes(modes);
353
354 dirName = QString::fromUtf8(dir);
355 fileName = QString::fromUtf8(file);
356 tmpName = QStringLiteral("%1.tmp%2").arg(fileName).arg(rand());
357 writer.putNextEntry(tmpName.toUtf8().constData());
358 }
359 ~RecoveryRunnable() override
360 {
361 delete prop;
362 }
363 void run() override
364 {
365 try {
366 prop->SaveDocFile(writer);
367 writer.close();
368
369 // We could have renamed the file in this thread. However, there is
370 // still chance of crash when we deleted the original and before rename
371 // the new file. So we ask the main thread to do it. There is still
372 // possibility of crash caused by thread other than the main, but
373 // that's the best we can do for now.
374 QMetaObject::invokeMethod(
375 AutoSaver::instance(),
376 "renameFile",
377 Qt::QueuedConnection,
378 Q_ARG(QString, dirName),
379 Q_ARG(QString, fileName),
380 Q_ARG(QString, tmpName)
381 );
382 }
383 catch (const Base::Exception& e) {
384 Base::Console().warning("Exception in auto-saving: %s\n", e.what());
385 }
386 catch (const std::exception& e) {
387 Base::Console().warning("C++ exception in auto-saving: %s\n", e.what());
388 }
389 catch (...) {
390 Base::Console().warning("Unknown exception in auto-saving\n");
391 }
392 }
393
394 private:
395 App::Property* prop;
396 Base::FileWriter writer;
397 QString dirName;
398 QString fileName;
399 QString tmpName;
400 };
401
402 } // namespace Gui
403
404 void RecoveryWriter::writeFiles()
405 {
406 // use a while loop because it is possible that while
407 // processing the files new ones can be added
408 size_t index = 0;
409 this->FileStream.close();
410 while (index < FileList.size()) {
411 FileEntry entry = FileList.begin()[index];
412
413 if (shouldWrite(entry.FileName, entry.Object)) {
414 std::string filePath = entry.FileName;
415 std::string::size_type pos = 0;
416 while ((pos = filePath.find('/', pos)) != std::string::npos) {
417 std::string dirName = DirName + "/" + filePath.substr(0, pos);
418 pos++;
419 Base::FileInfo fi(dirName);
420 fi.createDirectory();
421 }
422
423 // For properties a copy can be created and then this can be written to disk in a thread
424 if (entry.Object->isDerivedFrom<App::Property>()) {
425 const auto* prop = static_cast<const App::Property*>(entry.Object);
426 QThreadPool::globalInstance()->start(
427 new RecoveryRunnable(getModes(), DirName.c_str(), entry.FileName.c_str(), prop)
428 );
429 }
430 else {
431 std::string fileName = DirName + "/" + entry.FileName;
432 this->FileStream.open(fileName.c_str(), std::ios::out | std::ios::binary);
433 entry.Object->SaveDocFile(*this);
434 this->FileStream.close();
435 }
436 }
437
438 index++;
439 }
440 }
441
442
443 #include "moc_AutoSaver.cpp"