dolphinsortfilterproxymodel.cpp 20.2 KB
Newer Older
1
/***************************************************************************
2
3
4
 *   Copyright (C) 2006 by Peter Penz <peter.penz@gmx.at>                  *
 *   Copyright (C) 2006 by Dominic Battre <dominic@battre.de>              *
 *   Copyright (C) 2006 by Martin Pool <mbp@canonical.com>                 *
5
 *   Copyright (C) 2007 by Rafael Fernández López <ereslibre@gmail.com>    *
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA            *
 ***************************************************************************/
22
23
24

#include "dolphinsortfilterproxymodel.h"

25
26
27
28
#ifdef HAVE_NEPOMUK
#include <config-nepomuk.h>
#include <nepomuk/global.h>
#include <nepomuk/resource.h>
29
#include <nepomuk/tag.h>
30
31
#endif

32
33
#include <kdirmodel.h>
#include <kfileitem.h>
34
#include <kdatetime.h>
35
#include <klocale.h>
36

37
static DolphinView::Sorting sortingTypeTable[] =
Peter Penz's avatar
Peter Penz committed
38
39
40
41
42
43
44
45
{
    DolphinView::SortByName,        // KDirModel::Name
    DolphinView::SortBySize,        // KDirModel::Size
    DolphinView::SortByDate,        // KDirModel::ModifiedTime
    DolphinView::SortByPermissions, // KDirModel::Permissions
    DolphinView::SortByOwner,       // KDirModel::Owner
    DolphinView::SortByGroup,       // KDirModel::Group
    DolphinView::SortByType         // KDirModel::Type
46
47
48
49
#ifdef HAVE_NEPOMUK
    , DolphinView::SortByRating
    , DolphinView::SortByTags
#endif
Peter Penz's avatar
Peter Penz committed
50
};
51

52
DolphinSortFilterProxyModel::DolphinSortFilterProxyModel(QObject* parent) :
53
    KSortFilterProxyModel(parent),
54
55
    m_sorting(DolphinView::SortByName),
    m_sortOrder(Qt::AscendingOrder)
56
{
57
58
    setDynamicSortFilter(true);

59
    // sort by the user visible string for now
60
    setSortRole(DolphinView::SortByName);
61
    setSortCaseSensitivity(Qt::CaseInsensitive);
62
    sort(KDirModel::Name, Qt::AscendingOrder);
63
64
65
}

DolphinSortFilterProxyModel::~DolphinSortFilterProxyModel()
66
67
{
}
68
69
70

void DolphinSortFilterProxyModel::setSorting(DolphinView::Sorting sorting)
{
71
72
    // change the sorting column by keeping the current sort order
    sort(sorting, m_sortOrder);
73
74
}

75
76
77
void DolphinSortFilterProxyModel::setSortOrder(Qt::SortOrder sortOrder)
{
    // change the sort order by keeping the current column
78
    sort(m_sorting, sortOrder);
79
80
}

81
82
void DolphinSortFilterProxyModel::sort(int column, Qt::SortOrder sortOrder)
{
83
    m_sorting = sortingForColumn(column);
84
    m_sortOrder = sortOrder;
85
    setSortRole(m_sorting);
86
    KSortFilterProxyModel::sort(column, sortOrder);
87
88
}

89
90
91
92
93
94
95
96
97
98
99
100
bool DolphinSortFilterProxyModel::hasChildren(const QModelIndex& parent) const
{
    const QModelIndex sourceParent = mapToSource(parent);
    return sourceModel()->hasChildren(sourceParent);
}

bool DolphinSortFilterProxyModel::canFetchMore(const QModelIndex& parent) const
{
    const QModelIndex sourceParent = mapToSource(parent);
    return sourceModel()->canFetchMore(sourceParent);
}

101
102
DolphinView::Sorting DolphinSortFilterProxyModel::sortingForColumn(int column)
{
103
104
105
    Q_ASSERT(column >= 0);
    Q_ASSERT(column < static_cast<int>(sizeof(sortingTypeTable) / sizeof(DolphinView::Sorting)));
    return sortingTypeTable[column];
106
107
}

108
109
110
111
112
bool DolphinSortFilterProxyModel::lessThanGeneralPurpose(const QModelIndex &left,
                                                         const QModelIndex &right) const
{
    KDirModel* dirModel = static_cast<KDirModel*>(sourceModel());

113
114
    const KFileItem* leftFileItem  = dirModel->itemForIndex(left);
    const KFileItem* rightFileItem = dirModel->itemForIndex(right);
115

116
    switch (sortRole()) {
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
    case DolphinView::SortByName: {
        QString leftFileName(leftFileItem->name());
        if (leftFileName.at(0) == '.') {
            leftFileName = leftFileName.mid(1);
        }

        QString rightFileName(rightFileItem->name());
        if (rightFileName.at(0) == '.') {
            rightFileName = rightFileName.mid(1);
        }

        // We don't care about case for building categories. We also don't
        // want here to compare by a natural comparison.
        return naturalCompare(leftFileName, rightFileName) < 0;
    }
132

133
134
135
136
    case DolphinView::SortBySize:
        // If we are sorting by size, show folders first. We will sort them
        // correctly later.
        return leftFileItem->isDir() && !rightFileItem->isDir();
137

138
139
140
141
142
143
    case DolphinView::SortByDate: {
        KDateTime leftTime, rightTime;
        leftTime.setTime_t(leftFileItem->time(KIO::UDS_MODIFICATION_TIME));
        rightTime.setTime_t(rightFileItem->time(KIO::UDS_MODIFICATION_TIME));
        return leftTime > rightTime;
    }
144

145
146
147
148
    case DolphinView::SortByPermissions: {
        return naturalCompare(leftFileItem->permissionsString(),
                            rightFileItem->permissionsString()) < 0;
    }
149

150
151
152
153
    case DolphinView::SortByOwner: {
        return naturalCompare(leftFileItem->user().toLower(),
                              rightFileItem->user().toLower()) < 0;
    }
154

155
156
157
158
    case DolphinView::SortByGroup: {
        return naturalCompare(leftFileItem->group().toLower(),
                              rightFileItem->group().toLower()) < 0;
    }
159

160
161
    case DolphinView::SortByType: {
        // If we are sorting by size, show folders first. We will sort them
162
        // correctly later.
163
164
165
166
167
        if (leftFileItem->isDir() && !rightFileItem->isDir()) {
            return true;
        } else if (!leftFileItem->isDir() && rightFileItem->isDir()) {
            return false;
        }
168

169
170
171
        return naturalCompare(leftFileItem->mimeComment().toLower(),
                              rightFileItem->mimeComment().toLower()) < 0;
    }
172
173
174
175
176
177
#ifdef HAVE_NEPOMUK
    case DolphinView::SortByRating: {
        const quint32 leftRating = ratingForIndex(left);
        const quint32 rightRating = ratingForIndex(right);
        return leftRating > rightRating;
    }
178
    case DolphinView::SortByTags: {
179
180
181
182
183
184
185
186
        const QString leftTags = tagsForIndex(left);
        const QString rightTags = tagsForIndex(right);

        if (leftTags.isEmpty() && !rightTags.isEmpty())
            return false;
        else if (!leftTags.isEmpty() && rightTags.isEmpty())
            return true;

187
188
        return naturalCompare(tagsForIndex(left), tagsForIndex(right)) < 0;
    }
189
190
191
#endif
    default:
        break;
192
    }
Dirk Mueller's avatar
Dirk Mueller committed
193
    return false;
194
195
}

196
bool DolphinSortFilterProxyModel::lessThan(const QModelIndex& left,
197
                                           const QModelIndex& right) const
198
{
199
200
    KDirModel* dirModel = static_cast<KDirModel*>(sourceModel());

201
202
    const KFileItem* leftFileItem  = dirModel->itemForIndex(left);
    const KFileItem* rightFileItem = dirModel->itemForIndex(right);
203

204
    // If we are sorting by rating, folders and files are citizens of the same
205
    // class. Same if we are sorting by tags.
206
#ifdef HAVE_NEPOMUK
207
208
    if ((sortRole() != DolphinView::SortByRating) &&
        (sortRole() != DolphinView::SortByTags))
209
    {
210
#endif
211
212
213
214
215
216
        // On our priority, folders go above regular files.
        if (leftFileItem->isDir() && !rightFileItem->isDir()) {
            return true;
        } else if (!leftFileItem->isDir() && rightFileItem->isDir()) {
            return false;
        }
217
#ifdef HAVE_NEPOMUK
218
    }
219
#endif
220

221
    // Hidden elements go before visible ones, if they both are
222
    // folders or files.
223
224
    if (leftFileItem->isHidden() && !rightFileItem->isHidden()) {
        return true;
225
    } else if (!leftFileItem->isHidden() && rightFileItem->isHidden()) {
226
227
        return false;
    }
228

229
    switch (sortRole()) {
230
    case DolphinView::SortByName: {
231
232
233
234
235
236
237
238
239
        // So we are in the same priority, what counts now is their names.
        const QVariant leftData  = dirModel->data(left, KDirModel::Name);
        const QVariant rightData = dirModel->data(right, KDirModel::Name);
        const QString leftValueString(leftData.toString());
        const QString rightValueString(rightData.toString());

        return sortCaseSensitivity() ?
               (naturalCompare(leftValueString, rightValueString) < 0) :
               (naturalCompare(leftValueString.toLower(), rightValueString.toLower()) < 0);
240
    }
241

242
243
244
245
246
247
    case DolphinView::SortBySize: {
        // If we have two folders, what we have to measure is the number of
        // items that contains each other
        if (leftFileItem->isDir() && rightFileItem->isDir()) {
            QVariant leftValue = dirModel->data(left, KDirModel::ChildCountRole);
            int leftCount = leftValue.type() == QVariant::Int ? leftValue.toInt() : KDirModel::ChildCountUnknown;
248

249
250
            QVariant rightValue = dirModel->data(right, KDirModel::ChildCountRole);
            int rightCount = rightValue.type() == QVariant::Int ? rightValue.toInt() : KDirModel::ChildCountUnknown;
251

252
253
            // In the case they two have the same child items, we sort them by
            // their names. So we have always everything ordered. We also check
254
            // if we are taking in count their cases.
255
            if (leftCount == rightCount) {
256
                return sortCaseSensitivity() ? (naturalCompare(leftFileItem->name(), rightFileItem->name()) < 0) :
257
                        (naturalCompare(leftFileItem->name().toLower(), rightFileItem->name().toLower()) < 0);
258
            }
259

260
            // If they had different number of items, we sort them depending
261
            // on how many items had each other.
262
263
            return leftCount < rightCount;
        }
264

265
        // If what we are measuring is two files and they have the same size,
266
        // sort them by their file names.
267
268
269
270
        if (leftFileItem->size() == rightFileItem->size()) {
            return sortCaseSensitivity() ? (naturalCompare(leftFileItem->name(), rightFileItem->name()) < 0) :
                    (naturalCompare(leftFileItem->name().toLower(), rightFileItem->name().toLower()) < 0);
        }
271

272
        // If their sizes are different, sort them by their sizes, as expected.
273
274
        return leftFileItem->size() < rightFileItem->size();
    }
275

276
277
278
279
    case DolphinView::SortByDate: {
        KDateTime leftTime, rightTime;
        leftTime.setTime_t(leftFileItem->time(KIO::UDS_MODIFICATION_TIME));
        rightTime.setTime_t(rightFileItem->time(KIO::UDS_MODIFICATION_TIME));
280

281
282
283
284
285
        if (leftTime == rightTime) {
            return sortCaseSensitivity() ?
                   (naturalCompare(leftFileItem->name(), rightFileItem->name()) < 0) :
                   (naturalCompare(leftFileItem->name().toLower(), rightFileItem->name().toLower()) < 0);
        }
286

287
288
        return leftTime > rightTime;
    }
289

290
291
292
293
294
295
    case DolphinView::SortByPermissions: {
        if (leftFileItem->permissionsString() == rightFileItem->permissionsString()) {
            return sortCaseSensitivity() ?
                   (naturalCompare(leftFileItem->name(), rightFileItem->name()) < 0) :
                   (naturalCompare(leftFileItem->name().toLower(), rightFileItem->name().toLower()) < 0);
        }
296

297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
        return naturalCompare(leftFileItem->permissionsString(),
                              rightFileItem->permissionsString()) < 0;
    }

    case DolphinView::SortByOwner: {
        if (leftFileItem->user() == rightFileItem->user()) {
            return sortCaseSensitivity() ?
                   (naturalCompare(leftFileItem->name(), rightFileItem->name()) < 0) :
                   (naturalCompare(leftFileItem->name().toLower(), rightFileItem->name().toLower()) < 0);
        }

        return naturalCompare(leftFileItem->user(), rightFileItem->user()) < 0;
    }

    case DolphinView::SortByGroup: {
        if (leftFileItem->group() == rightFileItem->group()) {
            return sortCaseSensitivity() ? (naturalCompare(leftFileItem->name(), rightFileItem->name()) < 0) :
                    (naturalCompare(leftFileItem->name().toLower(), rightFileItem->name().toLower()) < 0);
        }
316

317
318
319
320
321
322
323
324
325
326
327
328
329
330
        return naturalCompare(leftFileItem->group(),
                              rightFileItem->group()) < 0;
    }

    case DolphinView::SortByType: {
        if (leftFileItem->mimetype() == rightFileItem->mimetype()) {
            return sortCaseSensitivity() ?
                   (naturalCompare(leftFileItem->name(), rightFileItem->name()) < 0) :
                   (naturalCompare(leftFileItem->name().toLower(), rightFileItem->name().toLower()) < 0);
        }

        return naturalCompare(leftFileItem->mimeComment(),
                              rightFileItem->mimeComment()) < 0;
    }
331
332
333
334
335
336
337

#ifdef HAVE_NEPOMUK
    case DolphinView::SortByRating: {
        const quint32 leftRating  = ratingForIndex(left);
        const quint32 rightRating = ratingForIndex(right);

        if (leftRating == rightRating) {
338
            // On our priority, folders go above regular files.
339
340
341
342
343
            // This checks are needed (don't think it's the same doing it here
            // than above). Here we make dirs citizens of first class because
            // we know we are on the same category. On the check we do on the
            // top of the method we don't know, so we remove that check when we
            // are sorting by rating. (ereslibre)
344
345
346
347
348
349
            if (leftFileItem->isDir() && !rightFileItem->isDir()) {
                return true;
            } else if (!leftFileItem->isDir() && rightFileItem->isDir()) {
                return false;
            }

350
351
352
353
354
355
356
            return sortCaseSensitivity() ?
                   (naturalCompare(leftFileItem->name(), rightFileItem->name()) < 0) :
                   (naturalCompare(leftFileItem->name().toLower(), rightFileItem->name().toLower()) < 0);
        }

        return leftRating > rightRating;
    }
357
358

    case DolphinView::SortByTags: {
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
        const QString leftTags = tagsForIndex(left);
        const QString rightTags = tagsForIndex(right);

        if (leftTags == rightTags) {
            // On our priority, folders go above regular files.
            // This checks are needed (don't think it's the same doing it here
            // than above). Here we make dirs citizens of first class because
            // we know we are on the same category. On the check we do on the
            // top of the method we don't know, so we remove that check when we
            // are sorting by tags. (ereslibre)
            if (leftFileItem->isDir() && !rightFileItem->isDir()) {
                return true;
            } else if (!leftFileItem->isDir() && rightFileItem->isDir()) {
                return false;
            }

            return sortCaseSensitivity() ?
                   (naturalCompare(leftFileItem->name(), rightFileItem->name()) < 0) :
                   (naturalCompare(leftFileItem->name().toLower(), rightFileItem->name().toLower()) < 0);
        }

        return naturalCompare(leftTags, rightTags) < 0;
381
    }
382
#endif
383
    }
384
385
386
387

    // We have set a SortRole and trust the ProxyModel to do
    // the right thing for now.
    return QSortFilterProxyModel::lessThan(left, right);
388
389
}

390
quint32 DolphinSortFilterProxyModel::ratingForIndex(const QModelIndex& index)
391
392
393
394
{
#ifdef HAVE_NEPOMUK
    quint32 rating = 0;

395
    const KDirModel* dirModel = static_cast<const KDirModel*>(index.model());
396
397
398
399
400
401
402
403
404
405
406
407
    KFileItem* item = dirModel->itemForIndex(index);
    if (item != 0) {
        const Nepomuk::Resource resource(item->url().url(), Nepomuk::NFO::File());
        rating = resource.rating();
    }
    return rating;
#else
    Q_UNUSED(index);
    return 0;
#endif
}

408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
QString DolphinSortFilterProxyModel::tagsForIndex(const QModelIndex& index)
{
#ifdef HAVE_NEPOMUK
    QString tagsString;

    const KDirModel* dirModel = static_cast<const KDirModel*>(index.model());
    KFileItem* item = dirModel->itemForIndex(index);
    if (item != 0) {
        const Nepomuk::Resource resource(item->url().url(), Nepomuk::NFO::File());
        const QList<Nepomuk::Tag> tags = resource.tags();
        QStringList stringList;
        foreach (const Nepomuk::Tag& tag, tags) {
            stringList.append(tag.label());
        }
        stringList.sort();

        foreach (const QString& str, stringList) {
            tagsString += str;
426
            tagsString += ", ";
427
428
        }

429
430
        if (!tagsString.isEmpty())
            tagsString.resize(tagsString.size() - 2);
431
432
433
434
435
436
437
438
    }

    return tagsString;
#else
    return QString();
#endif
}

439
int DolphinSortFilterProxyModel::naturalCompare(const QString& a,
440
                                                const QString& b)
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
{
    // This method chops the input a and b into pieces of
    // digits and non-digits (a1.05 becomes a | 1 | . | 05)
    // and compares these pieces of a and b to each other
    // (first with first, second with second, ...).
    //
    // This is based on the natural sort order code code by Martin Pool
    // http://sourcefrog.net/projects/natsort/
    // Martin Pool agreed to license this under LGPL or GPL.

    const QChar* currA = a.unicode(); // iterator over a
    const QChar* currB = b.unicode(); // iterator over b

    if (currA == currB) {
        return 0;
    }

    const QChar* begSeqA = currA; // beginning of a new character sequence of a
    const QChar* begSeqB = currB;

    while (!currA->isNull() && !currB->isNull()) {
        // find sequence of characters ending at the first non-character
        while (!currA->isNull() && !currA->isDigit()) {
            ++currA;
        }

        while (!currB->isNull() && !currB->isDigit()) {
            ++currB;
        }

        // compare these sequences
472
473
474
        const QString subA(begSeqA, currA - begSeqA);
        const QString subB(begSeqB, currB - begSeqB);
        const int cmp = QString::localeAwareCompare(subA, subB);
475
476
477
478
479
480
481
482
483
484
485
        if (cmp != 0) {
            return cmp;
        }

        if (currA->isNull() || currB->isNull()) {
            break;
        }

        // now some digits follow...
        if ((*currA == '0') || (*currB == '0')) {
            // one digit-sequence starts with 0 -> assume we are in a fraction part
486
            // do left aligned comparison (numbers are considered left aligned)
487
            while (1) {
488
489
                if (!currA->isDigit() && !currB->isDigit()) {
                    break;
490
                } else if (!currA->isDigit()) {
491
                    return -1;
492
493
494
                } else if (!currB->isDigit()) {
                    return + 1;
                } else if (*currA < *currB) {
495
                    return -1;
496
497
                } else if (*currA > *currB) {
                    return + 1;
498
499
500
501
                }
                ++currA;
                ++currB;
            }
502
        } else {
503
504
505
506
            // No digit-sequence starts with 0 -> assume we are looking at some integer
            // do right aligned comparison.
            //
            // The longest run of digits wins. That aside, the greatest
507
            // value wins, but we can't know that it will until we've scanned
508
            // both numbers to know that they have the same magnitude.
509

510
            int weight = 0;
511
512
            while (1) {
                if (!currA->isDigit() && !currB->isDigit()) {
513
514
                    if (weight != 0) {
                        return weight;
515
516
                    }
                    break;
517
                } else if (!currA->isDigit()) {
518
                    return -1;
519
520
521
                } else if (!currB->isDigit()) {
                    return + 1;
                } else if ((*currA < *currB) && (weight == 0)) {
522
                    weight = -1;
523
524
                } else if ((*currA > *currB) && (weight == 0)) {
                    weight = + 1;
525
526
527
528
529
530
531
532
533
534
535
536
537
538
                }
                ++currA;
                ++currB;
            }
        }

        begSeqA = currA;
        begSeqB = currB;
    }

    if (currA->isNull() && currB->isNull()) {
        return 0;
    }

539
    return currA->isNull() ? -1 : + 1;
540
541
}

542
#include "dolphinsortfilterproxymodel.moc"