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