]> cloud.milkyroute.net Git - dolphin.git/blob - src/views/viewproperties.cpp
Merge branch 'release/21.08'
[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::setVisibleRoles(const QList<QByteArray>& roles)
249 {
250 if (roles == visibleRoles()) {
251 return;
252 }
253
254 // See ViewProperties::visibleRoles() for the storage format
255 // of the additional information.
256
257 // Remove the old values stored for the current view-mode
258 const QStringList oldVisibleRoles = m_node->visibleRoles();
259 const QString prefix = viewModePrefix();
260 QStringList newVisibleRoles = oldVisibleRoles;
261 for (int i = newVisibleRoles.count() - 1; i >= 0; --i) {
262 if (newVisibleRoles[i].startsWith(prefix)) {
263 newVisibleRoles.removeAt(i);
264 }
265 }
266
267 // Add the updated values for the current view-mode
268 newVisibleRoles.reserve(roles.count());
269 for (const QByteArray& role : roles) {
270 newVisibleRoles.append(prefix + role);
271 }
272
273 if (oldVisibleRoles != newVisibleRoles) {
274 const bool markCustomizedDetails = (m_node->viewMode() == DolphinView::DetailsView)
275 && !newVisibleRoles.contains(CustomizedDetailsString);
276 if (markCustomizedDetails) {
277 // The additional information of the details-view has been modified. Set a marker,
278 // so that it is allowed to also show no additional information without doing the
279 // fallback to show the size and date per default.
280 newVisibleRoles.append(CustomizedDetailsString);
281 }
282
283 m_node->setVisibleRoles(newVisibleRoles);
284 update();
285 }
286 }
287
288 QList<QByteArray> ViewProperties::visibleRoles() const
289 {
290 // The shown additional information is stored for each view-mode separately as
291 // string with the view-mode as prefix. Example:
292 //
293 // AdditionalInfo=Details_size,Details_date,Details_owner,Icons_size
294 //
295 // To get the representation as QList<QByteArray>, the current
296 // view-mode must be checked and the values of this mode added to the list.
297 //
298 // For the details-view a special case must be respected: Per default the size
299 // and date should be shown without creating a .directory file. Only if
300 // the user explicitly has modified the properties of the details view (marked
301 // by "CustomizedDetails"), also a details-view with no additional information
302 // is accepted.
303
304 QList<QByteArray> roles{"text"};
305
306 // Iterate through all stored keys and append all roles that match to
307 // the current view mode.
308 const QString prefix = viewModePrefix();
309 const int prefixLength = prefix.length();
310
311 const QStringList visibleRoles = m_node->visibleRoles();
312 for (const QString& visibleRole : visibleRoles) {
313 if (visibleRole.startsWith(prefix)) {
314 const QByteArray role = visibleRole.right(visibleRole.length() - prefixLength).toLatin1();
315 if (role != "text") {
316 roles.append(role);
317 }
318 }
319 }
320
321 // For the details view the size and date should be shown per default
322 // until the additional information has been explicitly changed by the user
323 const bool useDefaultValues = roles.count() == 1 // "text"
324 && (m_node->viewMode() == DolphinView::DetailsView)
325 && !visibleRoles.contains(CustomizedDetailsString);
326 if (useDefaultValues) {
327 roles.append("size");
328 roles.append("modificationtime");
329 }
330
331 return roles;
332 }
333
334 void ViewProperties::setHeaderColumnWidths(const QList<int>& widths)
335 {
336 if (m_node->headerColumnWidths() != widths) {
337 m_node->setHeaderColumnWidths(widths);
338 update();
339 }
340 }
341
342 QList<int> ViewProperties::headerColumnWidths() const
343 {
344 return m_node->headerColumnWidths();
345 }
346
347 void ViewProperties::setDirProperties(const ViewProperties& props)
348 {
349 setViewMode(props.viewMode());
350 setPreviewsShown(props.previewsShown());
351 setHiddenFilesShown(props.hiddenFilesShown());
352 setGroupedSorting(props.groupedSorting());
353 setSortRole(props.sortRole());
354 setSortOrder(props.sortOrder());
355 setSortFoldersFirst(props.sortFoldersFirst());
356 setVisibleRoles(props.visibleRoles());
357 setHeaderColumnWidths(props.headerColumnWidths());
358 m_node->setVersion(props.m_node->version());
359 }
360
361 void ViewProperties::setAutoSaveEnabled(bool autoSave)
362 {
363 m_autoSave = autoSave;
364 }
365
366 bool ViewProperties::isAutoSaveEnabled() const
367 {
368 return m_autoSave;
369 }
370
371 void ViewProperties::update()
372 {
373 m_changedProps = true;
374 m_node->setTimestamp(QDateTime::currentDateTime());
375 }
376
377 void ViewProperties::save()
378 {
379 qCDebug(DolphinDebug) << "Saving view-properties to" << m_filePath;
380 QDir dir;
381 dir.mkpath(m_filePath);
382 m_node->setVersion(CurrentViewPropertiesVersion);
383 m_node->save();
384 m_changedProps = false;
385 }
386
387 bool ViewProperties::exist() const
388 {
389 const QString file = m_filePath + QDir::separator() + ViewPropertiesFileName;
390 return QFile::exists(file);
391 }
392
393 QString ViewProperties::destinationDir(const QString& subDir) const
394 {
395 QString path = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
396 path.append("/view_properties/").append(subDir);
397 return path;
398 }
399
400 QString ViewProperties::viewModePrefix() const
401 {
402 QString prefix;
403
404 switch (m_node->viewMode()) {
405 case DolphinView::IconsView: prefix = QStringLiteral("Icons_"); break;
406 case DolphinView::CompactView: prefix = QStringLiteral("Compact_"); break;
407 case DolphinView::DetailsView: prefix = QStringLiteral("Details_"); break;
408 default: qCWarning(DolphinDebug) << "Unknown view-mode of the view properties";
409 }
410
411 return prefix;
412 }
413
414 void ViewProperties::convertAdditionalInfo()
415 {
416 QStringList visibleRoles;
417
418 const QStringList additionalInfo = m_node->additionalInfo();
419 if (!additionalInfo.isEmpty()) {
420 // Convert the obsolete values like Icons_Size, Details_Date, ...
421 // to Icons_size, Details_date, ... where the suffix just represents
422 // the internal role. One special-case must be handled: "LinkDestination"
423 // has been used for "destination".
424 visibleRoles.reserve(additionalInfo.count());
425 for (const QString& info : additionalInfo) {
426 QString visibleRole = info;
427 int index = visibleRole.indexOf('_');
428 if (index >= 0 && index + 1 < visibleRole.length()) {
429 ++index;
430 if (visibleRole[index] == QLatin1Char('L')) {
431 visibleRole.replace(QLatin1String("LinkDestination"), QLatin1String("destination"));
432 } else {
433 visibleRole[index] = visibleRole[index].toLower();
434 }
435 }
436 visibleRoles.append(visibleRole);
437 }
438 }
439
440 m_node->setAdditionalInfo(QStringList());
441 m_node->setVisibleRoles(visibleRoles);
442 m_node->setVersion(AdditionalInfoViewPropertiesVersion);
443 update();
444 }
445
446 void ViewProperties::convertNameRoleToTextRole()
447 {
448 QStringList visibleRoles = m_node->visibleRoles();
449 for (int i = 0; i < visibleRoles.count(); ++i) {
450 if (visibleRoles[i].endsWith(QLatin1String("_name"))) {
451 const int leftLength = visibleRoles[i].length() - 5;
452 visibleRoles[i] = visibleRoles[i].left(leftLength) + "_text";
453 }
454 }
455
456 QString sortRole = m_node->sortRole();
457 if (sortRole == QLatin1String("name")) {
458 sortRole = QStringLiteral("text");
459 }
460
461 m_node->setVisibleRoles(visibleRoles);
462 m_node->setSortRole(sortRole);
463 m_node->setVersion(NameRolePropertiesVersion);
464 update();
465 }
466
467 void ViewProperties::convertDateRoleToModificationTimeRole()
468 {
469 QStringList visibleRoles = m_node->visibleRoles();
470 for (int i = 0; i < visibleRoles.count(); ++i) {
471 if (visibleRoles[i].endsWith(QLatin1String("_date"))) {
472 const int leftLength = visibleRoles[i].length() - 5;
473 visibleRoles[i] = visibleRoles[i].left(leftLength) + "_modificationtime";
474 }
475 }
476
477 QString sortRole = m_node->sortRole();
478 if (sortRole == QLatin1String("date")) {
479 sortRole = QStringLiteral("modificationtime");
480 }
481
482 m_node->setVisibleRoles(visibleRoles);
483 m_node->setSortRole(sortRole);
484 m_node->setVersion(DateRolePropertiesVersion);
485 update();
486 }
487
488 bool ViewProperties::isPartOfHome(const QString& filePath)
489 {
490 // For performance reasons cache the path in a static QString
491 // (see QDir::homePath() for more details)
492 static QString homePath;
493 if (homePath.isEmpty()) {
494 homePath = QDir::homePath();
495 Q_ASSERT(!homePath.isEmpty());
496 }
497
498 return filePath.startsWith(homePath);
499 }
500
501 QString ViewProperties::directoryHashForUrl(const QUrl& url)
502 {
503 const QByteArray hashValue = QCryptographicHash::hash(url.toEncoded(), QCryptographicHash::Sha1);
504 QString hashString = hashValue.toBase64();
505 hashString.replace('/', '-');
506 return hashString;
507 }