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