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