]> cloud.milkyroute.net Git - dolphin.git/blob - src/views/viewproperties.cpp
Assure backward compatibility for the sort-role
[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
26 #include <KComponentData>
27 #include <KLocale>
28 #include <KStandardDirs>
29 #include <KUrl>
30
31 #include <QCryptographicHash>
32 #include <QDate>
33 #include <QFile>
34 #include <QFileInfo>
35
36 namespace {
37 const int AdditionalInfoViewPropertiesVersion = 1;
38 const int NameRolePropertiesVersion = 2;
39 const int CurrentViewPropertiesVersion = 3;
40
41 // String representation to mark the additional properties of
42 // the details view as customized by the user. See
43 // ViewProperties::visibleRoles() for more information.
44 const char* CustomizedDetailsString = "CustomizedDetails";
45 }
46
47 ViewProperties::ViewProperties(const KUrl& url) :
48 m_changedProps(false),
49 m_autoSave(true),
50 m_node(0)
51 {
52 GeneralSettings* settings = GeneralSettings::self();
53 const bool useGlobalViewProps = settings->globalViewProps();
54 bool useDetailsViewWithPath = false;
55
56 // We try and save it to the file .directory in the directory being viewed.
57 // If the directory is not writable by the user or the directory is not local,
58 // we store the properties information in a local file.
59 if (useGlobalViewProps) {
60 m_filePath = destinationDir("global");
61 } else if (url.protocol().contains("search")) {
62 m_filePath = destinationDir("search/") + directoryHashForUrl(url);
63 useDetailsViewWithPath = true;
64 } else if (url.protocol() == QLatin1String("trash")) {
65 m_filePath = destinationDir("trash");
66 useDetailsViewWithPath = true;
67 } else if (url.isLocalFile()) {
68 m_filePath = url.toLocalFile();
69 const QFileInfo info(m_filePath);
70 if (!info.isWritable() || !isPartOfHome(m_filePath)) {
71 #ifdef Q_OS_WIN
72 // m_filePath probably begins with C:/ - the colon is not a valid character for paths though
73 m_filePath = QDir::separator() + m_filePath.remove(QLatin1Char(':'));
74 #endif
75 m_filePath = destinationDir("local") + m_filePath;
76 }
77 } else {
78 m_filePath = destinationDir("remote") + m_filePath;
79 }
80
81 const QString file = m_filePath + QDir::separator() + QLatin1String(".directory");
82 m_node = new ViewPropertySettings(KSharedConfig::openConfig(file));
83
84 // If the .directory file does not exist or the timestamp is too old,
85 // use default values instead.
86 const bool useDefaultProps = (!useGlobalViewProps || useDetailsViewWithPath) &&
87 (!QFileInfo(file).exists() ||
88 (m_node->timestamp() < settings->viewPropsTimestamp()));
89 if (useDefaultProps) {
90 if (useDetailsViewWithPath) {
91 setViewMode(DolphinView::DetailsView);
92 setVisibleRoles(QList<QByteArray>() << "path");
93 } else {
94 // The global view-properties act as default for directories without
95 // any view-property configuration
96 settings->setGlobalViewProps(true);
97
98 ViewProperties defaultProps(url);
99 setDirProperties(defaultProps);
100
101 settings->setGlobalViewProps(false);
102 m_changedProps = false;
103 }
104 }
105 }
106
107 ViewProperties::~ViewProperties()
108 {
109 if (m_changedProps && m_autoSave) {
110 save();
111 }
112
113 delete m_node;
114 m_node = 0;
115 }
116
117 void ViewProperties::setViewMode(DolphinView::Mode mode)
118 {
119 if (m_node->viewMode() != mode) {
120 m_node->setViewMode(mode);
121 update();
122 }
123 }
124
125 DolphinView::Mode ViewProperties::viewMode() const
126 {
127 const int mode = qBound(0, m_node->viewMode(), 2);
128 return static_cast<DolphinView::Mode>(mode);
129 }
130
131 void ViewProperties::setPreviewsShown(bool show)
132 {
133 if (m_node->previewsShown() != show) {
134 m_node->setPreviewsShown(show);
135 update();
136 }
137 }
138
139 bool ViewProperties::previewsShown() const
140 {
141 return m_node->previewsShown();
142 }
143
144 void ViewProperties::setHiddenFilesShown(bool show)
145 {
146 if (m_node->hiddenFilesShown() != show) {
147 m_node->setHiddenFilesShown(show);
148 update();
149 }
150 }
151
152 void ViewProperties::setGroupedSorting(bool grouped)
153 {
154 if (m_node->groupedSorting() != grouped) {
155 m_node->setGroupedSorting(grouped);
156 update();
157 }
158 }
159
160 bool ViewProperties::groupedSorting() const
161 {
162 return m_node->groupedSorting();
163 }
164
165 bool ViewProperties::hiddenFilesShown() const
166 {
167 return m_node->hiddenFilesShown();
168 }
169
170 void ViewProperties::setSortRole(const QByteArray& role)
171 {
172 if (m_node->sortRole() != role) {
173 m_node->setSortRole(role);
174 update();
175 }
176 }
177
178 QByteArray ViewProperties::sortRole() const
179 {
180 if (m_node->version() <= NameRolePropertiesVersion) {
181 const_cast<ViewProperties*>(this)->convertNameRoleToTextRole();
182 }
183
184 return m_node->sortRole().toLatin1();
185 }
186
187 void ViewProperties::setSortOrder(Qt::SortOrder sortOrder)
188 {
189 if (m_node->sortOrder() != sortOrder) {
190 m_node->setSortOrder(sortOrder);
191 update();
192 }
193 }
194
195 Qt::SortOrder ViewProperties::sortOrder() const
196 {
197 return static_cast<Qt::SortOrder>(m_node->sortOrder());
198 }
199
200 void ViewProperties::setSortFoldersFirst(bool foldersFirst)
201 {
202 if (m_node->sortFoldersFirst() != foldersFirst) {
203 m_node->setSortFoldersFirst(foldersFirst);
204 update();
205 }
206 }
207
208 bool ViewProperties::sortFoldersFirst() const
209 {
210 return m_node->sortFoldersFirst();
211 }
212
213 void ViewProperties::setVisibleRoles(const QList<QByteArray>& roles)
214 {
215 // See ViewProperties::visibleRoles() for the storage format
216 // of the additional information.
217
218 // Remove the old values stored for the current view-mode
219 const QStringList oldVisibleRoles = m_node->visibleRoles();
220 const QString prefix = viewModePrefix();
221 QStringList newVisibleRoles = oldVisibleRoles;
222 for (int i = newVisibleRoles.count() - 1; i >= 0; --i) {
223 if (newVisibleRoles[i].startsWith(prefix)) {
224 newVisibleRoles.removeAt(i);
225 }
226 }
227
228 // Add the updated values for the current view-mode
229 foreach (const QByteArray& role, roles) {
230 newVisibleRoles.append(prefix + role);
231 }
232
233 if (oldVisibleRoles != newVisibleRoles) {
234 const bool markCustomizedDetails = (m_node->viewMode() == DolphinView::DetailsView)
235 && !newVisibleRoles.contains(CustomizedDetailsString);
236 if (markCustomizedDetails) {
237 // The additional information of the details-view has been modified. Set a marker,
238 // so that it is allowed to also show no additional information without doing the
239 // fallback to show the size and date per default.
240 newVisibleRoles.append(CustomizedDetailsString);
241 }
242
243 m_node->setVisibleRoles(newVisibleRoles);
244 update();
245 }
246 }
247
248 QList<QByteArray> ViewProperties::visibleRoles() const
249 {
250 // The shown additional information is stored for each view-mode separately as
251 // string with the view-mode as prefix. Example:
252 //
253 // AdditionalInfo=Details_size,Details_date,Details_owner,Icons_size
254 //
255 // To get the representation as QList<QByteArray>, the current
256 // view-mode must be checked and the values of this mode added to the list.
257 //
258 // For the details-view a special case must be respected: Per default the size
259 // and date should be shown without creating a .directory file. Only if
260 // the user explictly has modified the properties of the details view (marked
261 // by "CustomizedDetails"), also a details-view with no additional information
262 // is accepted.
263
264 QList<QByteArray> roles;
265 roles.append("text");
266
267 // Iterate through all stored keys and append all roles that match to
268 // the curren view mode.
269 const QString prefix = viewModePrefix();
270 const int prefixLength = prefix.length();
271
272 QStringList visibleRoles = m_node->visibleRoles();
273 const int version = m_node->version();
274 if (visibleRoles.isEmpty() && version <= AdditionalInfoViewPropertiesVersion) {
275 // Convert the obsolete additionalInfo-property from older versions into the
276 // visibleRoles-property
277 const_cast<ViewProperties*>(this)->convertAdditionalInfo();
278 visibleRoles = m_node->visibleRoles();
279 } else if (version <= NameRolePropertiesVersion) {
280 const_cast<ViewProperties*>(this)->convertNameRoleToTextRole();
281 visibleRoles = m_node->visibleRoles();
282 }
283
284 foreach (const QString& visibleRole, visibleRoles) {
285 if (visibleRole.startsWith(prefix)) {
286 const QByteArray role = visibleRole.right(visibleRole.length() - prefixLength).toLatin1();
287 if (role != "text") {
288 roles.append(role);
289 }
290 }
291 }
292
293 // For the details view the size and date should be shown per default
294 // until the additional information has been explicitly changed by the user
295 const bool useDefaultValues = roles.count() == 1 // "text"
296 && (m_node->viewMode() == DolphinView::DetailsView)
297 && !visibleRoles.contains(CustomizedDetailsString);
298 if (useDefaultValues) {
299 roles.append("size");
300 roles.append("date");
301 }
302
303 return roles;
304 }
305
306 void ViewProperties::setHeaderColumnWidths(const QList<int>& widths)
307 {
308 if (m_node->headerColumnWidths() != widths) {
309 m_node->setHeaderColumnWidths(widths);
310 update();
311 }
312 }
313
314 QList<int> ViewProperties::headerColumnWidths() const
315 {
316 return m_node->headerColumnWidths();
317 }
318
319 void ViewProperties::setDirProperties(const ViewProperties& props)
320 {
321 setViewMode(props.viewMode());
322 setPreviewsShown(props.previewsShown());
323 setHiddenFilesShown(props.hiddenFilesShown());
324 setGroupedSorting(props.groupedSorting());
325 setSortRole(props.sortRole());
326 setSortOrder(props.sortOrder());
327 setSortFoldersFirst(props.sortFoldersFirst());
328 setVisibleRoles(props.visibleRoles());
329 setHeaderColumnWidths(props.headerColumnWidths());
330 }
331
332 void ViewProperties::setAutoSaveEnabled(bool autoSave)
333 {
334 m_autoSave = autoSave;
335 }
336
337 bool ViewProperties::isAutoSaveEnabled() const
338 {
339 return m_autoSave;
340 }
341
342 void ViewProperties::update()
343 {
344 m_changedProps = true;
345 m_node->setTimestamp(QDateTime::currentDateTime());
346 }
347
348 void ViewProperties::save()
349 {
350 KStandardDirs::makeDir(m_filePath);
351 m_node->setVersion(CurrentViewPropertiesVersion);
352 m_node->writeConfig();
353 m_changedProps = false;
354 }
355
356 KUrl ViewProperties::mirroredDirectory()
357 {
358 QString basePath = KGlobal::mainComponent().componentName();
359 basePath.append("/view_properties/");
360 return KUrl(KStandardDirs::locateLocal("data", basePath));
361 }
362
363 QString ViewProperties::destinationDir(const QString& subDir) const
364 {
365 QString basePath = KGlobal::mainComponent().componentName();
366 basePath.append("/view_properties/").append(subDir);
367 return KStandardDirs::locateLocal("data", basePath);
368 }
369
370 QString ViewProperties::viewModePrefix() const
371 {
372 QString prefix;
373
374 switch (m_node->viewMode()) {
375 case DolphinView::IconsView: prefix = "Icons_"; break;
376 case DolphinView::CompactView: prefix = "Compact_"; break;
377 case DolphinView::DetailsView: prefix = "Details_"; break;
378 default: kWarning() << "Unknown view-mode of the view properties";
379 }
380
381 return prefix;
382 }
383
384 void ViewProperties::convertAdditionalInfo()
385 {
386 QStringList visibleRoles;
387
388 const QStringList additionalInfo = m_node->additionalInfo();
389 if (!additionalInfo.isEmpty()) {
390 // Convert the obsolete values like Icons_Size, Details_Date, ...
391 // to Icons_size, Details_date, ... where the suffix just represents
392 // the internal role. One special-case must be handled: "LinkDestination"
393 // has been used for "destination".
394 visibleRoles.reserve(additionalInfo.count());
395 foreach (const QString& info, additionalInfo) {
396 QString visibleRole = info;
397 int index = visibleRole.indexOf('_');
398 if (index >= 0 && index + 1 < visibleRole.length()) {
399 ++index;
400 if (visibleRole[index] == QLatin1Char('L')) {
401 visibleRole.replace("LinkDestination", "destination");
402 } else {
403 visibleRole[index] = visibleRole[index].toLower();
404 }
405 }
406 visibleRoles.append(visibleRole);
407 }
408 }
409
410 m_node->setAdditionalInfo(QStringList());
411 m_node->setVisibleRoles(visibleRoles);
412 update();
413 }
414
415 void ViewProperties::convertNameRoleToTextRole()
416 {
417 QStringList visibleRoles = m_node->visibleRoles();
418 for (int i = 0; i < visibleRoles.count(); ++i) {
419 if (visibleRoles[i].endsWith("_name")) {
420 const int leftLength = visibleRoles[i].length() - 5;
421 visibleRoles[i] = visibleRoles[i].left(leftLength) + "_text";
422 }
423 }
424
425 QString sortRole = m_node->sortRole();
426 if (sortRole == QLatin1String("name")) {
427 sortRole = QLatin1String("text");
428 }
429
430 m_node->setVisibleRoles(visibleRoles);
431 m_node->setSortRole(sortRole);
432 update();
433 }
434
435 bool ViewProperties::isPartOfHome(const QString& filePath)
436 {
437 // For performance reasons cache the path in a static QString
438 // (see QDir::homePath() for more details)
439 static QString homePath;
440 if (homePath.isEmpty()) {
441 homePath = QDir::homePath();
442 Q_ASSERT(!homePath.isEmpty());
443 }
444
445 return filePath.startsWith(homePath);
446 }
447
448 QString ViewProperties::directoryHashForUrl(const KUrl& url)
449 {
450 const QByteArray hashValue = QCryptographicHash::hash(url.prettyUrl().toLatin1(),
451 QCryptographicHash::Sha1);
452 QString hashString = hashValue.toBase64();
453 hashString.replace('/', '-');
454 return hashString;
455 }