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