Debian Codegraph @

src/Gui/PreferencePages/DlgSettingsCacheDirectory.cpp

raw
1 /***************************************************************************
2 * Copyright (c) 2021 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 <cmath>
24 #include <limits>
25 #include <vector>
26 #include <QCoreApplication>
27 #include <QDate>
28 #include <QDesktopServices>
29 #include <QDir>
30 #include <QLocale>
31 #include <QMessageBox>
32 #include <QSettings>
33 #include <QUrl>
34
35 #include <App/Application.h>
36 #include <App/Document.h>
37 #include <Gui/DocumentRecovery.h>
38 #include <Gui/MainWindow.h>
39
40 #include "DlgSettingsCacheDirectory.h"
41 #include "ui_DlgSettingsCacheDirectory.h"
42
43
44 using namespace Gui::Dialog;
45
46 /* TRANSLATOR Gui::Dialog::DlgSettingsCacheDirectory */
47
48 QString DlgSettingsCacheDirectory::currentSize;
49
50 DlgSettingsCacheDirectory::DlgSettingsCacheDirectory(QWidget* parent)
51 : PreferencePage(parent)
52 , ui(new Ui_DlgSettingsCacheDirectory)
53 {
54 ui->setupUi(this);
55 ui->labelCache->setToolTip(tr("Notify the user if the cache size exceeds the specified limit"));
56 if (currentSize.isEmpty()) {
57 currentSize = tr("Unknown");
58 }
59 setCurrentCacheSize(currentSize);
60
61 QString path = QString::fromStdString(App::Application::getUserCachePath());
62 ui->cacheLocation->setText(path);
63
64 ui->comboBoxLimit->addItem(QStringLiteral("100 MB"), 100);
65 ui->comboBoxLimit->addItem(QStringLiteral("300 MB"), 300);
66 ui->comboBoxLimit->addItem(QStringLiteral("500 MB"), 500);
67 ui->comboBoxLimit->addItem(QStringLiteral("1 GB"), 1024);
68 ui->comboBoxLimit->addItem(QStringLiteral("2 GB"), 2048);
69 ui->comboBoxLimit->addItem(QStringLiteral("3 GB"), 3072);
70
71 connect(ui->pushButtonCheck, &QPushButton::clicked, this, &DlgSettingsCacheDirectory::runCheck);
72 connect(ui->openButton, &QPushButton::clicked, this, &DlgSettingsCacheDirectory::openDirectory);
73 }
74
75 DlgSettingsCacheDirectory::~DlgSettingsCacheDirectory() = default;
76
77 void DlgSettingsCacheDirectory::saveSettings()
78 {
79 ApplicationCacheSettings::setCheckPeriod(ui->comboBoxPeriod->currentIndex());
80 ApplicationCacheSettings::setCacheSizeLimit(ui->comboBoxLimit->currentData().toUInt());
81 }
82
83 void DlgSettingsCacheDirectory::loadSettings()
84 {
85 int period = ApplicationCacheSettings::getCheckPeriod();
86 if (period >= 0 && period < ui->comboBoxPeriod->count()) {
87 ui->comboBoxPeriod->setCurrentIndex(period);
88 }
89 unsigned int limit = ApplicationCacheSettings::getCacheSizeLimit();
90 int index = ui->comboBoxLimit->findData(limit);
91
92 // if not found then add a new item with this value
93 if (index < 0) {
94 ui->comboBoxLimit->addItem(QStringLiteral("%1 MB").arg(limit), limit);
95 index = ui->comboBoxLimit->count() - 1;
96 }
97 ui->comboBoxLimit->setCurrentIndex(index);
98 }
99
100 void DlgSettingsCacheDirectory::resetSettingsToDefaults()
101 {
102 ParameterGrp::handle hGrp;
103 hGrp = WindowParameter::getDefaultParameter()->GetGroup("CacheDirectory");
104 // reset "Limit" parameter
105 hGrp->RemoveUnsigned("Limit");
106 // reset "Period" parameter
107 hGrp->RemoveInt("Period");
108
109 // finally reset all the parameters associated to Gui::Pref* widgets
110 PreferencePage::resetSettingsToDefaults();
111 }
112
113 void DlgSettingsCacheDirectory::changeEvent(QEvent* e)
114 {
115 if (e->type() == QEvent::LanguageChange) {
116 int period = ui->comboBoxPeriod->currentIndex();
117 ui->retranslateUi(this);
118 ui->comboBoxPeriod->setCurrentIndex(period);
119 setCurrentCacheSize(currentSize);
120 }
121 QWidget::changeEvent(e);
122 }
123
124 void DlgSettingsCacheDirectory::setCurrentCacheSize(const QString& str)
125 {
126 currentSize = str;
127 ui->labelCurrentCache->setText(tr("Current cache size: %1").arg(str));
128 }
129
130 void DlgSettingsCacheDirectory::runCheck()
131 {
132 Gui::Dialog::ApplicationCache cache;
133 unsigned int sizeInMB = ui->comboBoxLimit->currentData().toUInt();
134 cache.setLimit(ApplicationCache::toBytes(sizeInMB));
135 qint64 total = cache.size();
136 setCurrentCacheSize(ApplicationCache::toString(total));
137
138 // When performing the clean-up then recompute the new cache size
139 if (cache.performAction(total)) {
140 total = cache.size();
141 setCurrentCacheSize(ApplicationCache::toString(total));
142 }
143 }
144
145 void DlgSettingsCacheDirectory::openDirectory()
146 {
147 QString path = QString::fromStdString(App::Application::getUserCachePath());
148 QUrl url = QUrl::fromLocalFile(path);
149 QDesktopServices::openUrl(url);
150 }
151
152 // ----------------------------------------------------------------------------
153
154 ApplicationCache::ApplicationCache()
155 {
156 limit = std::pow(1024, 3);
157 setPeriod(Period::Weekly);
158 }
159
160 /*!
161 * \brief ApplicationCache::setPeriod
162 * Set the period to check for the cache size
163 * \param period
164 */
165 void ApplicationCache::setPeriod(ApplicationCache::Period period)
166 {
167 switch (period) {
168 case Period::Always:
169 numDays = -1;
170 break;
171 case Period::Daily:
172 numDays = 1;
173 break;
174 case Period::Weekly:
175 numDays = 7;
176 break;
177 case Period::Monthly:
178 numDays = 31;
179 break;
180 case Period::Yearly:
181 numDays = 365;
182 break;
183 case Period::Never:
184 numDays = std::numeric_limits<int>::max();
185 break;
186 }
187 }
188
189 /*!
190 * \brief ApplicationCache::setLimit
191 * Set the limit in bytes to perform a check
192 * \param value
193 */
194 void ApplicationCache::setLimit(qint64 value)
195 {
196 limit = value;
197 }
198
199 /*!
200 * \brief ApplicationCache::periodicCheckOfSize
201 * Checks if the periodic check should be performed now
202 * \return
203 */
204 bool ApplicationCache::periodicCheckOfSize() const
205 {
206 QString vendor = QString::fromLatin1(App::Application::Config()["ExeVendor"].c_str());
207 QString application = QString::fromStdString(App::Application::getExecutableName());
208
209 QSettings settings(vendor, application);
210 QString key = QStringLiteral("LastCacheCheck");
211 QDate date = settings.value(key).toDate();
212 QDate now = QDate::currentDate();
213
214 // get the days since the last check
215 int days = date.daysTo(now);
216 if (date.isNull()) {
217 days = 1000;
218 }
219
220 if (days >= numDays) {
221 settings.setValue(key, now);
222 return true;
223 }
224
225 return false;
226 }
227
228 /*!
229 * \brief ApplicationCache::performAction
230 * If the cache size \a total is higher than the limit then show a dialog to the user
231 * \param total
232 */
233 bool ApplicationCache::performAction(qint64 total)
234 {
235 bool performed = false;
236 if (total > limit) {
237 QString path = QString::fromStdString(App::Application::getUserCachePath());
238 QMessageBox msgBox(Gui::getMainWindow());
239 msgBox.setIcon(QMessageBox::Warning);
240 msgBox.setWindowTitle(tr("Cache Directory"));
241
242 QString hint = tr("The cache directory %1 exceeds the size of %2.")
243 .arg(path, ApplicationCache::toString(limit));
244 QString ask = tr("Clear it now?");
245 QString warn = tr("Warning: Make sure that this is the only running %1 instance "
246 "and that no documents are opened as this may result into data loss!")
247 .arg(QCoreApplication::applicationName());
248
249 msgBox.setText(QStringLiteral("%1 %2\n\n\n%3").arg(hint, ask, warn));
250 msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No | QMessageBox::Open);
251 msgBox.setDefaultButton(QMessageBox::No);
252
253 while (true) {
254 int ret = msgBox.exec();
255 if (ret == QMessageBox::Open) {
256 QUrl url = QUrl::fromLocalFile(path);
257 QDesktopServices::openUrl(url);
258 }
259 else {
260 if (ret == QMessageBox::Yes) {
261 clearDirectory(path);
262 performed = true;
263 }
264 break;
265 }
266 }
267 }
268
269 return performed;
270 }
271
272 /*!
273 * \brief ApplicationCache::size
274 * Determines the size of the cache.
275 * \return
276 */
277 qint64 ApplicationCache::size() const
278 {
279 qint64 total = dirSize(QString::fromStdString(App::Application::getUserCachePath()));
280 return total;
281 }
282
283 /*!
284 * \internal
285 */
286 void ApplicationCache::clearDirectory(const QString& path)
287 {
288 // Add the transient directories and the lock files to the ignore list
289 QDir tmp = QString::fromUtf8(App::Application::getUserCachePath().c_str());
290 tmp.setNameFilters(QStringList() << QStringLiteral("*.lock"));
291 tmp.setFilter(QDir::Files);
292
293 QList<QFileInfo> dirs;
294 std::vector<App::Document*> docs = App::GetApplication().getDocuments();
295 for (auto it : docs) {
296 QDir dir(QString::fromStdString(it->TransientDir.getStrValue()));
297 QFileInfo fi(dir.absolutePath());
298 dirs.append(fi);
299 }
300
301 DocumentRecoveryCleaner cleaner;
302 cleaner.setIgnoreFiles(tmp.entryList());
303 cleaner.setIgnoreDirectories(dirs);
304 cleaner.clearDirectory(QFileInfo(path));
305 }
306
307 /*!
308 * \internal
309 */
310 qint64 ApplicationCache::dirSize(QString dirPath) const
311 {
312 qint64 total = 0;
313 QDir dir(dirPath);
314
315 QDir::Filters fileFilters = QDir::Files;
316 const auto& files = dir.entryList(fileFilters);
317 for (const QString& filePath : files) {
318 QFileInfo fi(dir, filePath);
319 total += fi.size();
320 }
321
322 // traverse sub-directories recursively
323 QDir::Filters dirFilters = QDir::Dirs | QDir::NoDotAndDotDot;
324 const auto& dirs = dir.entryList(dirFilters);
325 for (const QString& subDirPath : dirs) {
326 total += dirSize(dirPath + QDir::separator() + subDirPath);
327 }
328 return total;
329 }
330
331 /*!
332 * \brief ApplicationCache::applyUserSettings
333 * Set period and limit according to user settings
334 */
335 void ApplicationCache::applyUserSettings()
336 {
337 int period = ApplicationCacheSettings::getCheckPeriod();
338 setPeriod(static_cast<Period>(period));
339
340 unsigned int sizeInMB = ApplicationCacheSettings::getCacheSizeLimit();
341 setLimit(ApplicationCache::toBytes(sizeInMB));
342 }
343
344 qint64 ApplicationCache::toBytes(unsigned int sizeInMB)
345 {
346 qint64 value = static_cast<qint64>(sizeInMB) * 1024 * 1024;
347 return value;
348 }
349
350 QString ApplicationCache::toString(qint64 size)
351 {
352 QStringList units
353 = {QStringLiteral("Bytes"), QStringLiteral("KB"), QStringLiteral("MB"), QStringLiteral("GB")};
354 int i;
355 double outputSize = size;
356 for (i = 0; i < units.size() - 1; i++) {
357 if (outputSize < 1024) {
358 break;
359 }
360 outputSize /= 1024;
361 }
362
363 return QStringLiteral("%1 %2").arg(QLocale().toString(outputSize, 'f', 2), units[i]);
364 }
365
366 // ----------------------------------------------------------------------------
367
368 unsigned int ApplicationCacheSettings::getCacheSizeLimit()
369 {
370 ParameterGrp::handle hGrp = WindowParameter::getDefaultParameter()->GetGroup("CacheDirectory");
371 return hGrp->GetUnsigned("Limit", 500);
372 }
373
374 void ApplicationCacheSettings::setCacheSizeLimit(unsigned int limit)
375 {
376 ParameterGrp::handle hGrp = WindowParameter::getDefaultParameter()->GetGroup("CacheDirectory");
377 hGrp->SetUnsigned("Limit", limit);
378 }
379
380 int ApplicationCacheSettings::getCheckPeriod()
381 {
382 ParameterGrp::handle hGrp = WindowParameter::getDefaultParameter()->GetGroup("CacheDirectory");
383 return hGrp->GetInt("Period", static_cast<int>(ApplicationCache::Period::Weekly));
384 }
385
386 void ApplicationCacheSettings::setCheckPeriod(int period)
387 {
388 ParameterGrp::handle hGrp = WindowParameter::getDefaultParameter()->GetGroup("CacheDirectory");
389 hGrp->SetInt("Period", period);
390 }
391
392
393 #include "moc_DlgSettingsCacheDirectory.cpp"