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