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