]> cloud.milkyroute.net Git - dolphin.git/blob - src/views/viewproperties.cpp
Modernize: Use nullptr everywhere
[dolphin.git] / src / views / viewproperties.cpp
1 /***************************************************************************
2 * Copyright (C) 2006-2010 by Peter Penz <peter.penz19@gmail.com> *
3 * Copyright (C) 2006 by Aaron J. Seigo <aseigo@kde.org> *
4 * *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation; either version 2 of the License, or *
8 * (at your option) any later version. *
9 * *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
14 * *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the *
17 * Free Software Foundation, Inc., *
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
19 ***************************************************************************/
20
21 #include "viewproperties.h"
22
23 #include "dolphin_directoryviewpropertysettings.h"
24 #include "dolphin_generalsettings.h"
25
26 #include <QUrl>
27 #include "dolphindebug.h"
28
29 #include <QCryptographicHash>
30 #include <QDate>
31 #include <QFile>
32 #include <QFileInfo>
33 #include <QStandardPaths>
34
35 namespace {
36 const int AdditionalInfoViewPropertiesVersion = 1;
37 const int NameRolePropertiesVersion = 2;
38 const int DateRolePropertiesVersion = 4;
39 const int CurrentViewPropertiesVersion = 4;
40
41 // String representation to mark the additional properties of
42 // the details view as customized by the user. See
43 // ViewProperties::visibleRoles() for more information.
44 const char CustomizedDetailsString[] = "CustomizedDetails";
45
46 // Filename that is used for storing the properties
47 const char ViewPropertiesFileName[] = ".directory";
48 }
49
50 ViewProperties::ViewProperties(const QUrl& url) :
51 m_changedProps(false),
52 m_autoSave(true),
53 m_node(nullptr)
54 {
55 GeneralSettings* settings = GeneralSettings::self();
56 const bool useGlobalViewProps = settings->globalViewProps() || url.isEmpty();
57 bool useDetailsViewWithPath = false;
58
59 // We try and save it to the file .directory in the directory being viewed.
60 // If the directory is not writable by the user or the directory is not local,
61 // we store the properties information in a local file.
62 if (useGlobalViewProps) {
63 m_filePath = destinationDir(QStringLiteral("global"));
64 } else if (url.scheme().contains(QStringLiteral("search"))) {
65 m_filePath = destinationDir(QStringLiteral("search/")) + directoryHashForUrl(url);
66 useDetailsViewWithPath = true;
67 } else if (url.scheme() == QLatin1String("trash")) {
68 m_filePath = destinationDir(QStringLiteral("trash"));
69 useDetailsViewWithPath = true;
70 } else if (url.isLocalFile()) {
71 m_filePath = url.toLocalFile();
72 const QFileInfo dirInfo(m_filePath);
73 const QFileInfo fileInfo(m_filePath + QDir::separator() + ViewPropertiesFileName);
74 // Check if the directory is writable and check if the ".directory" file exists and
75 // is read- and writable.
76 if (!dirInfo.isWritable()
77 || (fileInfo.exists() && !(fileInfo.isReadable() && fileInfo.isWritable()))
78 || !isPartOfHome(m_filePath)) {
79 #ifdef Q_OS_WIN
80 // m_filePath probably begins with C:/ - the colon is not a valid character for paths though
81 m_filePath = QDir::separator() + m_filePath.remove(QLatin1Char(':'));
82 #endif
83 m_filePath = destinationDir(QStringLiteral("local")) + m_filePath;
84 }
85 } else {
86 m_filePath = destinationDir(QStringLiteral("remote")) + m_filePath;
87 }
88
89 const QString file = m_filePath + QDir::separator() + ViewPropertiesFileName;
90 m_node = new ViewPropertySettings(KSharedConfig::openConfig(file));
91
92 // If the .directory file does not exist or the timestamp is too old,
93 // use default values instead.
94 const bool useDefaultProps = (!useGlobalViewProps || useDetailsViewWithPath) &&
95 (!QFile::exists(file) ||
96 (m_node->timestamp() < settings->viewPropsTimestamp()));
97 if (useDefaultProps) {
98 if (useDetailsViewWithPath) {
99 setViewMode(DolphinView::DetailsView);
100 setVisibleRoles({"path"});
101 } else {
102 // The global view-properties act as default for directories without
103 // any view-property configuration. Constructing a ViewProperties
104 // instance for an empty QUrl ensures that the global view-properties
105 // are loaded.
106 QUrl emptyUrl;
107 ViewProperties defaultProps(emptyUrl);
108 setDirProperties(defaultProps);
109
110 m_changedProps = false;
111 }
112 }
113
114 if (m_node->version() < CurrentViewPropertiesVersion) {
115 // The view-properties have an outdated version. Convert the properties
116 // to the changes of the current version.
117 if (m_node->version() < AdditionalInfoViewPropertiesVersion) {
118 convertAdditionalInfo();
119 Q_ASSERT(m_node->version() == AdditionalInfoViewPropertiesVersion);
120 }
121
122 if (m_node->version() < NameRolePropertiesVersion) {
123 convertNameRoleToTextRole();
124 Q_ASSERT(m_node->version() == NameRolePropertiesVersion);
125 }
126
127 if (m_node->version() < DateRolePropertiesVersion) {
128 convertDateRoleToModificationTimeRole();
129 Q_ASSERT(m_node->version() == DateRolePropertiesVersion);
130 }
131
132 m_node->setVersion(CurrentViewPropertiesVersion);
133 }
134 }
135
136 ViewProperties::~ViewProperties()
137 {
138 if (m_changedProps && m_autoSave) {
139 save();
140 }
141
142 delete m_node;
143 m_node = nullptr;
144 }
145
146 void ViewProperties::setViewMode(DolphinView::Mode mode)
147 {
148 if (m_node->viewMode() != mode) {
149 m_node->setViewMode(mode);
150 update();
151 }
152 }
153
154 DolphinView::Mode ViewProperties::viewMode() const
155 {
156 const int mode = qBound(0, m_node->viewMode(), 2);
157 return static_cast<DolphinView::Mode>(mode);
158 }
159
160 void ViewProperties::setPreviewsShown(bool show)
161 {
162 if (m_node->previewsShown() != show) {
163 m_node->setPreviewsShown(show);
164 update();
165 }
166 }
167
168 bool ViewProperties::previewsShown() const
169 {
170 return m_node->previewsShown();
171 }
172
173 void ViewProperties::setHiddenFilesShown(bool show)
174 {
175 if (m_node->hiddenFilesShown() != show) {
176 m_node->setHiddenFilesShown(show);
177 update();
178 }
179 }
180
181 void ViewProperties::setGroupedSorting(bool grouped)
182 {
183 if (m_node->groupedSorting() != grouped) {
184 m_node->setGroupedSorting(grouped);
185 update();
186 }
187 }
188
189 bool ViewProperties::groupedSorting() const
190 {
191 return m_node->groupedSorting();
192 }
193
194 bool ViewProperties::hiddenFilesShown() const
195 {
196 return m_node->hiddenFilesShown();
197 }
198
199 void ViewProperties::setSortRole(const QByteArray& role)
200 {
201 if (m_node->sortRole() != role) {
202 m_node->setSortRole(role);
203 update();
204 }
205 }
206
207 QByteArray ViewProperties::sortRole() const
208 {
209 return m_node->sortRole().toLatin1();
210 }
211
212 void ViewProperties::setSortOrder(Qt::SortOrder sortOrder)
213 {
214 if (m_node->sortOrder() != sortOrder) {
215 m_node->setSortOrder(sortOrder);
216 update();
217 }
218 }
219
220 Qt::SortOrder ViewProperties::sortOrder() const
221 {
222 return static_cast<Qt::SortOrder>(m_node->sortOrder());
223 }
224
225 void ViewProperties::setSortFoldersFirst(bool foldersFirst)
226 {
227 if (m_node->sortFoldersFirst() != foldersFirst) {
228 m_node->setSortFoldersFirst(foldersFirst);
229 update();
230 }
231 }
232
233 bool ViewProperties::sortFoldersFirst() const
234 {
235 return m_node->sortFoldersFirst();
236 }
237
238 void ViewProperties::setVisibleRoles(const QList<QByteArray>& roles)
239 {
240 if (roles == visibleRoles()) {
241 return;
242 }
243
244 // See ViewProperties::visibleRoles() for the storage format
245 // of the additional information.
246
247 // Remove the old values stored for the current view-mode
248 const QStringList oldVisibleRoles = m_node->visibleRoles();
249 const QString prefix = viewModePrefix();
250 QStringList newVisibleRoles = oldVisibleRoles;
251 for (int i = newVisibleRoles.count() - 1; i >= 0; --i) {
252 if (newVisibleRoles[i].startsWith(prefix)) {
253 newVisibleRoles.removeAt(i);
254 }
255 }
256
257 // Add the updated values for the current view-mode
258 newVisibleRoles.reserve(roles.count());
259 foreach (const QByteArray& role, roles) {
260 newVisibleRoles.append(prefix + role);
261 }
262
263 if (oldVisibleRoles != newVisibleRoles) {
264 const bool markCustomizedDetails = (m_node->viewMode() == DolphinView::DetailsView)
265 && !newVisibleRoles.contains(CustomizedDetailsString);
266 if (markCustomizedDetails) {
267 // The additional information of the details-view has been modified. Set a marker,
268 // so that it is allowed to also show no additional information without doing the
269 // fallback to show the size and date per default.
270 newVisibleRoles.append(CustomizedDetailsString);
271 }
272
273 m_node->setVisibleRoles(newVisibleRoles);
274 update();
275 }
276 }
277
278 QList<QByteArray> ViewProperties::visibleRoles() const
279 {
280 // The shown additional information is stored for each view-mode separately as
281 // string with the view-mode as prefix. Example:
282 //
283 // AdditionalInfo=Details_size,Details_date,Details_owner,Icons_size
284 //
285 // To get the representation as QList<QByteArray>, the current
286 // view-mode must be checked and the values of this mode added to the list.
287 //
288 // For the details-view a special case must be respected: Per default the size
289 // and date should be shown without creating a .directory file. Only if
290 // the user explictly has modified the properties of the details view (marked
291 // by "CustomizedDetails"), also a details-view with no additional information
292 // is accepted.
293
294 QList<QByteArray> roles{"text"};
295
296 // Iterate through all stored keys and append all roles that match to
297 // the current view mode.
298 const QString prefix = viewModePrefix();
299 const int prefixLength = prefix.length();
300
301 const QStringList visibleRoles = m_node->visibleRoles();
302 foreach (const QString& visibleRole, visibleRoles) {
303 if (visibleRole.startsWith(prefix)) {
304 const QByteArray role = visibleRole.right(visibleRole.length() - prefixLength).toLatin1();
305 if (role != "text") {
306 roles.append(role);
307 }
308 }
309 }
310
311 // For the details view the size and date should be shown per default
312 // until the additional information has been explicitly changed by the user
313 const bool useDefaultValues = roles.count() == 1 // "text"
314 && (m_node->viewMode() == DolphinView::DetailsView)
315 && !visibleRoles.contains(CustomizedDetailsString);
316 if (useDefaultValues) {
317 roles.append("size");
318 roles.append("modificationtime");
319 }
320
321 return roles;
322 }
323
324 void ViewProperties::setHeaderColumnWidths(const QList<int>& widths)
325 {
326 if (m_node->headerColumnWidths() != widths) {
327 m_node->setHeaderColumnWidths(widths);
328 update();
329 }
330 }
331
332 QList<int> ViewProperties::headerColumnWidths() const
333 {
334 return m_node->headerColumnWidths();
335 }
336
337 void ViewProperties::setDirProperties(const ViewProperties& props)
338 {
339 setViewMode(props.viewMode());
340 setPreviewsShown(props.previewsShown());
341 setHiddenFilesShown(props.hiddenFilesShown());
342 setGroupedSorting(props.groupedSorting());
343 setSortRole(props.sortRole());
344 setSortOrder(props.sortOrder());
345 setSortFoldersFirst(props.sortFoldersFirst());
346 setVisibleRoles(props.visibleRoles());
347 setHeaderColumnWidths(props.headerColumnWidths());
348 m_node->setVersion(props.m_node->version());
349 }
350
351 void ViewProperties::setAutoSaveEnabled(bool autoSave)
352 {
353 m_autoSave = autoSave;
354 }
355
356 bool ViewProperties::isAutoSaveEnabled() const
357 {
358 return m_autoSave;
359 }
360
361 void ViewProperties::update()
362 {
363 m_changedProps = true;
364 m_node->setTimestamp(QDateTime::currentDateTime());
365 }
366
367 void ViewProperties::save()
368 {
369 qCDebug(DolphinDebug) << "Saving view-properties to" << m_filePath;
370 QDir dir;
371 dir.mkpath(m_filePath);
372 m_node->setVersion(CurrentViewPropertiesVersion);
373 m_node->save();
374 m_changedProps = false;
375 }
376
377 bool ViewProperties::exist() const
378 {
379 const QString file = m_filePath + QDir::separator() + ViewPropertiesFileName;
380 return QFile::exists(file);
381 }
382
383 QString ViewProperties::destinationDir(const QString& subDir) const
384 {
385 QString path = QStandardPaths::writableLocation(QStandardPaths::DataLocation);
386 path.append("/view_properties/").append(subDir);
387 return path;
388 }
389
390 QString ViewProperties::viewModePrefix() const
391 {
392 QString prefix;
393
394 switch (m_node->viewMode()) {
395 case DolphinView::IconsView: prefix = QStringLiteral("Icons_"); break;
396 case DolphinView::CompactView: prefix = QStringLiteral("Compact_"); break;
397 case DolphinView::DetailsView: prefix = QStringLiteral("Details_"); break;
398 default: qCWarning(DolphinDebug) << "Unknown view-mode of the view properties";
399 }
400
401 return prefix;
402 }
403
404 void ViewProperties::convertAdditionalInfo()
405 {
406 QStringList visibleRoles;
407
408 const QStringList additionalInfo = m_node->additionalInfo();
409 if (!additionalInfo.isEmpty()) {
410 // Convert the obsolete values like Icons_Size, Details_Date, ...
411 // to Icons_size, Details_date, ... where the suffix just represents
412 // the internal role. One special-case must be handled: "LinkDestination"
413 // has been used for "destination".
414 visibleRoles.reserve(additionalInfo.count());
415 foreach (const QString& info, additionalInfo) {
416 QString visibleRole = info;
417 int index = visibleRole.indexOf('_');
418 if (index >= 0 && index + 1 < visibleRole.length()) {
419 ++index;
420 if (visibleRole[index] == QLatin1Char('L')) {
421 visibleRole.replace(QLatin1String("LinkDestination"), QLatin1String("destination"));
422 } else {
423 visibleRole[index] = visibleRole[index].toLower();
424 }
425 }
426 visibleRoles.append(visibleRole);
427 }
428 }
429
430 m_node->setAdditionalInfo(QStringList());
431 m_node->setVisibleRoles(visibleRoles);
432 m_node->setVersion(AdditionalInfoViewPropertiesVersion);
433 update();
434 }
435
436 void ViewProperties::convertNameRoleToTextRole()
437 {
438 QStringList visibleRoles = m_node->visibleRoles();
439 for (int i = 0; i < visibleRoles.count(); ++i) {
440 if (visibleRoles[i].endsWith(QLatin1String("_name"))) {
441 const int leftLength = visibleRoles[i].length() - 5;
442 visibleRoles[i] = visibleRoles[i].left(leftLength) + "_text";
443 }
444 }
445
446 QString sortRole = m_node->sortRole();
447 if (sortRole == QLatin1String("name")) {
448 sortRole = QStringLiteral("text");
449 }
450
451 m_node->setVisibleRoles(visibleRoles);
452 m_node->setSortRole(sortRole);
453 m_node->setVersion(NameRolePropertiesVersion);
454 update();
455 }
456
457 void ViewProperties::convertDateRoleToModificationTimeRole()
458 {
459 QStringList visibleRoles = m_node->visibleRoles();
460 for (int i = 0; i < visibleRoles.count(); ++i) {
461 if (visibleRoles[i].endsWith(QLatin1String("_date"))) {
462 const int leftLength = visibleRoles[i].length() - 5;
463 visibleRoles[i] = visibleRoles[i].left(leftLength) + "_modificationtime";
464 }
465 }
466
467 QString sortRole = m_node->sortRole();
468 if (sortRole == QLatin1String("date")) {
469 sortRole = QStringLiteral("modificationtime");
470 }
471
472 m_node->setVisibleRoles(visibleRoles);
473 m_node->setSortRole(sortRole);
474 m_node->setVersion(DateRolePropertiesVersion);
475 update();
476 }
477
478 bool ViewProperties::isPartOfHome(const QString& filePath)
479 {
480 // For performance reasons cache the path in a static QString
481 // (see QDir::homePath() for more details)
482 static QString homePath;
483 if (homePath.isEmpty()) {
484 homePath = QDir::homePath();
485 Q_ASSERT(!homePath.isEmpty());
486 }
487
488 return filePath.startsWith(homePath);
489 }
490
491 QString ViewProperties::directoryHashForUrl(const QUrl& url)
492 {
493 const QByteArray hashValue = QCryptographicHash::hash(url.toEncoded(), QCryptographicHash::Sha1);
494 QString hashString = hashValue.toBase64();
495 hashString.replace('/', '-');
496 return hashString;
497 }