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