]> cloud.milkyroute.net Git - dolphin.git/blob - src/views/viewproperties.cpp
Merge branch 'Applications/19.08'
[dolphin.git] / src / views / viewproperties.cpp
1 /***************************************************************************
2 * Copyright (C) 2006-2010 by Peter Penz <peter.penz19@gmail.com> *
3 * Copyright (C) 2006 by Aaron J. Seigo <aseigo@kde.org> *
4 * *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation; either version 2 of the License, or *
8 * (at your option) any later version. *
9 * *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
14 * *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the *
17 * Free Software Foundation, Inc., *
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
19 ***************************************************************************/
20
21 #include "viewproperties.h"
22
23 #include "dolphin_directoryviewpropertysettings.h"
24 #include "dolphin_generalsettings.h"
25 #include "dolphindebug.h"
26
27 #include <QCryptographicHash>
28
29 #include <KFileItem>
30
31 namespace {
32 const int AdditionalInfoViewPropertiesVersion = 1;
33 const int NameRolePropertiesVersion = 2;
34 const int DateRolePropertiesVersion = 4;
35 const int CurrentViewPropertiesVersion = 4;
36
37 // String representation to mark the additional properties of
38 // the details view as customized by the user. See
39 // ViewProperties::visibleRoles() for more information.
40 const char CustomizedDetailsString[] = "CustomizedDetails";
41
42 // Filename that is used for storing the properties
43 const char ViewPropertiesFileName[] = ".directory";
44 }
45
46 ViewProperties::ViewProperties(const QUrl& url) :
47 m_changedProps(false),
48 m_autoSave(true),
49 m_node(nullptr)
50 {
51 GeneralSettings* settings = GeneralSettings::self();
52 const bool useGlobalViewProps = settings->globalViewProps() || url.isEmpty();
53 bool useDetailsViewWithPath = false;
54 bool useRecentDocumentsView = false;
55 bool useDownloadsView = false;
56
57 // We try and save it to the file .directory in the directory being viewed.
58 // If the directory is not writable by the user or the directory is not local,
59 // we store the properties information in a local file.
60 if (useGlobalViewProps) {
61 m_filePath = destinationDir(QStringLiteral("global"));
62 } else if (url.scheme().contains(QLatin1String("search"))) {
63 m_filePath = destinationDir(QStringLiteral("search/")) + directoryHashForUrl(url);
64 useDetailsViewWithPath = true;
65 } else if (url.scheme() == QLatin1String("trash")) {
66 m_filePath = destinationDir(QStringLiteral("trash"));
67 useDetailsViewWithPath = true;
68 } else if (url.scheme() == QLatin1String("recentdocuments")) {
69 m_filePath = destinationDir(QStringLiteral("recentdocuments"));
70 useRecentDocumentsView = true;
71 } else if (url.isLocalFile()) {
72 m_filePath = url.toLocalFile();
73
74 bool useDestinationDir = !isPartOfHome(m_filePath);
75 if (!useDestinationDir) {
76 const KFileItem fileItem(url);
77 useDestinationDir = fileItem.isSlow();
78 }
79
80 if (!useDestinationDir) {
81 const QFileInfo dirInfo(m_filePath);
82 const QFileInfo fileInfo(m_filePath + QDir::separator() + ViewPropertiesFileName);
83 useDestinationDir = !dirInfo.isWritable() || (dirInfo.size() > 0 && fileInfo.exists() && !(fileInfo.isReadable() && fileInfo.isWritable()));
84 }
85
86 if (useDestinationDir) {
87 #ifdef Q_OS_WIN
88 // m_filePath probably begins with C:/ - the colon is not a valid character for paths though
89 m_filePath = QDir::separator() + m_filePath.remove(QLatin1Char(':'));
90 #endif
91 m_filePath = destinationDir(QStringLiteral("local")) + m_filePath;
92 }
93
94 if (m_filePath == QStandardPaths::writableLocation(QStandardPaths::DownloadLocation)) {
95 useDownloadsView = true;
96 }
97 } else {
98 m_filePath = destinationDir(QStringLiteral("remote")) + m_filePath;
99 }
100
101 const QString file = m_filePath + QDir::separator() + ViewPropertiesFileName;
102 m_node = new ViewPropertySettings(KSharedConfig::openConfig(file));
103
104 // If the .directory file does not exist or the timestamp is too old,
105 // use default values instead.
106 const bool useDefaultProps = (!useGlobalViewProps || useDetailsViewWithPath) &&
107 (!QFile::exists(file) ||
108 (m_node->timestamp() < settings->viewPropsTimestamp()));
109 if (useDefaultProps) {
110 if (useDetailsViewWithPath) {
111 setViewMode(DolphinView::DetailsView);
112 setVisibleRoles({"path"});
113 } else if (useRecentDocumentsView || useDownloadsView) {
114 setSortRole(QByteArrayLiteral("modificationtime"));
115 setSortOrder(Qt::DescendingOrder);
116
117 if (useRecentDocumentsView) {
118 setViewMode(DolphinView::DetailsView);
119 setVisibleRoles({QByteArrayLiteral("path")});
120 } else if (useDownloadsView) {
121 setSortFoldersFirst(false);
122 setGroupedSorting(true);
123 }
124 } else {
125 // The global view-properties act as default for directories without
126 // any view-property configuration. Constructing a ViewProperties
127 // instance for an empty QUrl ensures that the global view-properties
128 // are loaded.
129 QUrl emptyUrl;
130 ViewProperties defaultProps(emptyUrl);
131 setDirProperties(defaultProps);
132
133 m_changedProps = false;
134 }
135 }
136
137 if (m_node->version() < CurrentViewPropertiesVersion) {
138 // The view-properties have an outdated version. Convert the properties
139 // to the changes of the current version.
140 if (m_node->version() < AdditionalInfoViewPropertiesVersion) {
141 convertAdditionalInfo();
142 Q_ASSERT(m_node->version() == AdditionalInfoViewPropertiesVersion);
143 }
144
145 if (m_node->version() < NameRolePropertiesVersion) {
146 convertNameRoleToTextRole();
147 Q_ASSERT(m_node->version() == NameRolePropertiesVersion);
148 }
149
150 if (m_node->version() < DateRolePropertiesVersion) {
151 convertDateRoleToModificationTimeRole();
152 Q_ASSERT(m_node->version() == DateRolePropertiesVersion);
153 }
154
155 m_node->setVersion(CurrentViewPropertiesVersion);
156 }
157 }
158
159 ViewProperties::~ViewProperties()
160 {
161 if (m_changedProps && m_autoSave) {
162 save();
163 }
164
165 delete m_node;
166 m_node = nullptr;
167 }
168
169 void ViewProperties::setViewMode(DolphinView::Mode mode)
170 {
171 if (m_node->viewMode() != mode) {
172 m_node->setViewMode(mode);
173 update();
174 }
175 }
176
177 DolphinView::Mode ViewProperties::viewMode() const
178 {
179 const int mode = qBound(0, m_node->viewMode(), 2);
180 return static_cast<DolphinView::Mode>(mode);
181 }
182
183 void ViewProperties::setPreviewsShown(bool show)
184 {
185 if (m_node->previewsShown() != show) {
186 m_node->setPreviewsShown(show);
187 update();
188 }
189 }
190
191 bool ViewProperties::previewsShown() const
192 {
193 return m_node->previewsShown();
194 }
195
196 void ViewProperties::setHiddenFilesShown(bool show)
197 {
198 if (m_node->hiddenFilesShown() != show) {
199 m_node->setHiddenFilesShown(show);
200 update();
201 }
202 }
203
204 void ViewProperties::setGroupedSorting(bool grouped)
205 {
206 if (m_node->groupedSorting() != grouped) {
207 m_node->setGroupedSorting(grouped);
208 update();
209 }
210 }
211
212 bool ViewProperties::groupedSorting() const
213 {
214 return m_node->groupedSorting();
215 }
216
217 bool ViewProperties::hiddenFilesShown() const
218 {
219 return m_node->hiddenFilesShown();
220 }
221
222 void ViewProperties::setSortRole(const QByteArray& role)
223 {
224 if (m_node->sortRole() != role) {
225 m_node->setSortRole(role);
226 update();
227 }
228 }
229
230 QByteArray ViewProperties::sortRole() const
231 {
232 return m_node->sortRole().toLatin1();
233 }
234
235 void ViewProperties::setSortOrder(Qt::SortOrder sortOrder)
236 {
237 if (m_node->sortOrder() != sortOrder) {
238 m_node->setSortOrder(sortOrder);
239 update();
240 }
241 }
242
243 Qt::SortOrder ViewProperties::sortOrder() const
244 {
245 return static_cast<Qt::SortOrder>(m_node->sortOrder());
246 }
247
248 void ViewProperties::setSortFoldersFirst(bool foldersFirst)
249 {
250 if (m_node->sortFoldersFirst() != foldersFirst) {
251 m_node->setSortFoldersFirst(foldersFirst);
252 update();
253 }
254 }
255
256 bool ViewProperties::sortFoldersFirst() const
257 {
258 return m_node->sortFoldersFirst();
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 foreach (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 foreach (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 setVisibleRoles(props.visibleRoles());
370 setHeaderColumnWidths(props.headerColumnWidths());
371 m_node->setVersion(props.m_node->version());
372 }
373
374 void ViewProperties::setAutoSaveEnabled(bool autoSave)
375 {
376 m_autoSave = autoSave;
377 }
378
379 bool ViewProperties::isAutoSaveEnabled() const
380 {
381 return m_autoSave;
382 }
383
384 void ViewProperties::update()
385 {
386 m_changedProps = true;
387 m_node->setTimestamp(QDateTime::currentDateTime());
388 }
389
390 void ViewProperties::save()
391 {
392 qCDebug(DolphinDebug) << "Saving view-properties to" << m_filePath;
393 QDir dir;
394 dir.mkpath(m_filePath);
395 m_node->setVersion(CurrentViewPropertiesVersion);
396 m_node->save();
397 m_changedProps = false;
398 }
399
400 bool ViewProperties::exist() const
401 {
402 const QString file = m_filePath + QDir::separator() + ViewPropertiesFileName;
403 return QFile::exists(file);
404 }
405
406 QString ViewProperties::destinationDir(const QString& subDir) const
407 {
408 QString path = QStandardPaths::writableLocation(QStandardPaths::DataLocation);
409 path.append("/view_properties/").append(subDir);
410 return path;
411 }
412
413 QString ViewProperties::viewModePrefix() const
414 {
415 QString prefix;
416
417 switch (m_node->viewMode()) {
418 case DolphinView::IconsView: prefix = QStringLiteral("Icons_"); break;
419 case DolphinView::CompactView: prefix = QStringLiteral("Compact_"); break;
420 case DolphinView::DetailsView: prefix = QStringLiteral("Details_"); break;
421 default: qCWarning(DolphinDebug) << "Unknown view-mode of the view properties";
422 }
423
424 return prefix;
425 }
426
427 void ViewProperties::convertAdditionalInfo()
428 {
429 QStringList visibleRoles;
430
431 const QStringList additionalInfo = m_node->additionalInfo();
432 if (!additionalInfo.isEmpty()) {
433 // Convert the obsolete values like Icons_Size, Details_Date, ...
434 // to Icons_size, Details_date, ... where the suffix just represents
435 // the internal role. One special-case must be handled: "LinkDestination"
436 // has been used for "destination".
437 visibleRoles.reserve(additionalInfo.count());
438 foreach (const QString& info, additionalInfo) {
439 QString visibleRole = info;
440 int index = visibleRole.indexOf('_');
441 if (index >= 0 && index + 1 < visibleRole.length()) {
442 ++index;
443 if (visibleRole[index] == QLatin1Char('L')) {
444 visibleRole.replace(QLatin1String("LinkDestination"), QLatin1String("destination"));
445 } else {
446 visibleRole[index] = visibleRole[index].toLower();
447 }
448 }
449 visibleRoles.append(visibleRole);
450 }
451 }
452
453 m_node->setAdditionalInfo(QStringList());
454 m_node->setVisibleRoles(visibleRoles);
455 m_node->setVersion(AdditionalInfoViewPropertiesVersion);
456 update();
457 }
458
459 void ViewProperties::convertNameRoleToTextRole()
460 {
461 QStringList visibleRoles = m_node->visibleRoles();
462 for (int i = 0; i < visibleRoles.count(); ++i) {
463 if (visibleRoles[i].endsWith(QLatin1String("_name"))) {
464 const int leftLength = visibleRoles[i].length() - 5;
465 visibleRoles[i] = visibleRoles[i].left(leftLength) + "_text";
466 }
467 }
468
469 QString sortRole = m_node->sortRole();
470 if (sortRole == QLatin1String("name")) {
471 sortRole = QStringLiteral("text");
472 }
473
474 m_node->setVisibleRoles(visibleRoles);
475 m_node->setSortRole(sortRole);
476 m_node->setVersion(NameRolePropertiesVersion);
477 update();
478 }
479
480 void ViewProperties::convertDateRoleToModificationTimeRole()
481 {
482 QStringList visibleRoles = m_node->visibleRoles();
483 for (int i = 0; i < visibleRoles.count(); ++i) {
484 if (visibleRoles[i].endsWith(QLatin1String("_date"))) {
485 const int leftLength = visibleRoles[i].length() - 5;
486 visibleRoles[i] = visibleRoles[i].left(leftLength) + "_modificationtime";
487 }
488 }
489
490 QString sortRole = m_node->sortRole();
491 if (sortRole == QLatin1String("date")) {
492 sortRole = QStringLiteral("modificationtime");
493 }
494
495 m_node->setVisibleRoles(visibleRoles);
496 m_node->setSortRole(sortRole);
497 m_node->setVersion(DateRolePropertiesVersion);
498 update();
499 }
500
501 bool ViewProperties::isPartOfHome(const QString& filePath)
502 {
503 // For performance reasons cache the path in a static QString
504 // (see QDir::homePath() for more details)
505 static QString homePath;
506 if (homePath.isEmpty()) {
507 homePath = QDir::homePath();
508 Q_ASSERT(!homePath.isEmpty());
509 }
510
511 return filePath.startsWith(homePath);
512 }
513
514 QString ViewProperties::directoryHashForUrl(const QUrl& url)
515 {
516 const QByteArray hashValue = QCryptographicHash::hash(url.toEncoded(), QCryptographicHash::Sha1);
517 QString hashString = hashValue.toBase64();
518 hashString.replace('/', '-');
519 return hashString;
520 }