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