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