File: TreeModel.h

package info (click to toggle)
qtop 2.3.4-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,976 kB
  • sloc: cpp: 40,477; makefile: 7
file content (505 lines) | stat: -rw-r--r-- 12,797 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
#ifndef TreeModel_h
#define TreeModel_h

/******************************************************************************
*
* Copyright (C) 2002 Hugo PEREIRA <mailto: hugo.pereira@free.fr>
*
* This 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 software 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, see <http://www.gnu.org/licenses/>.
*
*******************************************************************************/

#include "Debug.h"
#include "ItemModel.h"
#include "TreeItem.h"

#include <QList>

//* generic class to store structure in a model
template<class T> class TreeModel : public ItemModel
{

    public:

    //* value type
    using ValueType = T;

    //* reference
    using Reference = T&;

    //* reference
    using ConstReference = const T&;

    //* pointer
    using Pointer = T*;

    //* list of values
    using List = QList<ValueType>;

    //* iterator
    using ListIterator = QListIterator<ValueType>;

    //* item
    using Item = TreeItem<T>;

    //* constructor
    TreeModel(QObject *parent = nullptr):
        ItemModel( parent ),
        root_( map_ )
    {}

    //*@name accessors
    //@{

    //* flags
    Qt::ItemFlags flags(const QModelIndex &index) const override
    {
        if (!index.isValid()) return 0;
        return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
    }

    //* unique index for given row, column and parent index
    QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override
    {

        // check if index is valid
        if( !hasIndex( row, column, parent ) ) return QModelIndex();

        // fid parent item
        const Item& parentItem = parent.isValid() ? _find( parent.internalId() ) : root_;

        // return new index if matching child is found, or invalid index
        return (row < (int)parentItem.childCount()) ?
            createIndex( row, column, parentItem.child(row).id() ):
            QModelIndex();

    }

    //* index of parent
    QModelIndex parent(const QModelIndex &index) const override
    {

        // check index validity
        if (!index.isValid()) return QModelIndex();

        // retrieve associated job item
        const Item& childItem( _find(index.internalId() ) );

        // if no parent return invalid index
        if( !( childItem.hasParent() && childItem.parent().hasParent() ) ) return QModelIndex();

        // if parent is root return invalid index
        const Item& parentItem( childItem.parent() );
        const Item& grandParentItem( parentItem.parent() );

        // find parent position in list of grand parent
        int row(0);
        for( ; row < grandParentItem.childCount(); row++ )
        { if( &parentItem == &grandParentItem.child(row) ) return createIndex( row, 0, parentItem.id() ); }

        // not found
        return QModelIndex();

    }

    //* number of rows below given index
    int rowCount(const QModelIndex &parent = QModelIndex()) const override
    {

        // check column
        if (parent.column() > 0) return 0;

        // store parent Job
        const Item& parentItem = parent.isValid() ? _find( parent.internalId() ) : root_;
        return parentItem.childCount();

    }

    //* return index associated to a given value, starting from parent [recursive]
    QModelIndex index( ConstReference value, const QModelIndex& parent = QModelIndex() ) const
    {

        // return parent index if job match
        if( parent.isValid() && _find( parent.internalId() ).get() == value ) return parent;

        // get rows associated to parent and loop over rows
        for( int row=0; row<rowCount( parent ); row++ )
        {
            // get child index
            QModelIndex found( index( value, index( row, 0, parent ) ) );
            if( found.isValid() ) return found;
        }

        // value not found. return invalid index
        return QModelIndex();

    }

    //* return all values [recursive]
    List children( const QModelIndex& parent = QModelIndex() ) const
    {

        // retrieve parent item
        const Item& parentItem = parent.isValid() ? _find( parent.internalId() ) : root_;
        return parentItem.childValues();

    }

    //* return all values [recursive]
    List children( ConstReference value ) const
    {

        const QModelIndex& index( this->index( value ) );
        return index.isValid() ? children( index ):List();
    }

    //* return value associated to given model index
    ValueType get( const QModelIndex& index ) const
    {
        if( !index.isValid() ) return ValueType();
        else return _find( index.internalId() ).get();
    }

    //* return all values matching index list
    List get( const QModelIndexList& indexes ) const
    {
        List out;
        for( const auto& index:indexes )
        { if( index.isValid() ) out << get( index ); }
        return out;
    }

    //* get list of internal selected items
    QModelIndexList selectedIndexes() const override
    {
        QModelIndexList out;
        for( const auto& value:selectedItems_ )
        {
            QModelIndex index( this->index( value ) );
            if( index.isValid() ) out << index;
        }
        return out;
    }

    //* restore currentIndex
    QModelIndex currentIndex() const override
    { return hasCurrentItem_ ? this->index( currentItem_ ) : QModelIndex(); }

    //* true if expended indexes are supported
    bool supportsExpandedIndexes() const override
    { return true; }

    //* get list of internal selected items
    QModelIndexList expandedIndexes() const override
    {
        QModelIndexList out;
        for( const auto& value:expandedItems_ )
        {
            QModelIndex index( this->index( value ) );
            if( index.isValid() ) out << index;
        }
        return out;
    }

    //* root item
    const Item& root() const
    { return root_; }

    //@}

    //*@name modifiers
    //@{

    //* clear internal list selected items
    void clearSelectedIndexes() override
    { selectedItems_.clear(); }

    //* set selected indexes
    void setSelectedIndexes( const QModelIndexList& indexes ) override
    {
        selectedItems_.clear();
        for( const auto& index:indexes )
        { if( index.isValid() ) selectedItems_ << get( index ); }
    }

    //* store index internal selection state
    void setIndexSelected( const QModelIndex& index, bool value ) override
    {
        if( !index.isValid() ) return;
        if( value ) selectedItems_ << get( index );
        else { selectedItems_.removeAll( get( index ) ); }
    }

    //* current index;
    void clearCurrentIndex() override
    { hasCurrentItem_ = false; }

    //* store current index
    void setCurrentIndex( const QModelIndex& index ) override
    {
        if( index.isValid() )
        {

            hasCurrentItem_ = true;
            currentItem_ = get( index );

        } else hasCurrentItem_ = false;
    }

    //* clear internal list of expanded items
    void clearExpandedIndexes() override
    { expandedItems_.clear(); }

    //* set selected indexes
    void setExpandedIndexes( const QModelIndexList& indexes ) override
    {
        expandedItems_.clear();
        for( const auto& index:indexes )
        { if( index.isValid() ) expandedItems_ << get( index ); }
    }

    //* store index internal selection state
    void setIndexExpanded( const QModelIndex& index, bool value ) override
    {
        if( !index.isValid() ) return;
        if( value ) expandedItems_ << get( index );
        else { expandedItems_.removeAll( get( index ) ); }
    }

    //* add values
    void add( ConstReference value )
    { add( List() << value ); }

    //* add values
    void add( List values )
    {

        // check if not empty
        // this avoids sending useless signals
        if( values.empty() ) return;

        emit layoutAboutToBeChanged();
        root_.update( values );
        _add( root_, values );
        _sort();
        emit layoutChanged();

        return;

    }

    //* replace
    bool replace( ConstReference first, ConstReference second )
    {
        Item* item( root_.find( first ) );
        if( item )
        {

            item->set( second );
            return true;

        } else return false;

    };

    //* update values
    /**
    items that are not found in list are removed
    items that are found are updated
    */
    void set( List values )
    {

        // check if not empty
        if( values.empty() ) clear();
        else {

            emit layoutAboutToBeChanged();

            // sort values if requested
            if( sortValues_ )
            { std::sort( values.begin(), values.end() ); }

            root_.set( values );
            _add( root_, values );
            _sort();
            emit layoutChanged();
        }

        return;

    }

    //* update values
    /**
    items that are not found in list are removed
    items that are found are updated
    */
    void set( ConstReference value, List values )
    {

        // find item matching value
        Item* item( root_.find( value ) );
        if( !item ) return;

        emit layoutAboutToBeChanged();
        if( values.empty() ) item->clear();
        else {

            // sort values if requested
            if( sortValues_ )
            { std::sort( values.begin(), values.end() ); }

            item->set( values );
            _add( *item, values );
            _sort();

        }

        emit layoutChanged();
    }

    //* remove
    void remove( ConstReference value )
    { remove( List() << value ); }

    //* remove
    void remove( List values )
    {

        // check if not empty
        // this avoids sending useless signals
        if( values.empty() ) return;

        emit layoutAboutToBeChanged();
        _remove( root_, values );
        _resetTree();
        emit layoutChanged();
        return;

    }

    //* reset tree
    void resetTree()
    {
        emit layoutAboutToBeChanged();
        _resetTree();
        emit layoutChanged();
    }


    //* clear
    void clear()
    {

        emit layoutAboutToBeChanged();
        map_.clear();
        root_ = Item( map_ );
        emit layoutChanged();

    }

    //* sort values
    void setSortValues( bool value )
    { sortValues_ = value; }

    //@}

    protected:

    //* root item
    Item& _root()
    { return root_; }

    //* add
    void _add( Item& item, List values )
    {
        for( const auto& value:values )
        { item.add( value ); }
    }

    //* find item matching id
    const Item& _find( typename Item::Id id ) const
    {
        typename Item::Map::const_iterator iter( map_.find( id ) );
        return iter == map_.end() ? root_:*iter.value();
    }

    //* remove, without update
    void _remove( Item& parent, List& values )
    {

        // remove all values from selection
        for( const auto& value:values )
        { selectedItems_.removeAll( value ); }

        // remove children that are found in list, and remove from list
        for( int row = 0; row < parent.childCount(); )
        {
            int found( values.indexOf( parent.child(row).get() ) );
            if( found >= 0 )
            {
                parent.remove( row );
                values.removeAt( found );
            } else ++row;

        }

        // do the same starting from children, if there are remaining items to remove
        if( !values.isEmpty() )
        {
            for( int row = 0; row < parent.childCount(); ++row )
            { _remove( parent.child(row), values ); }
        }

    }

    //* reset tree
    /** private version, with no signal emitted */
    void _resetTree()
    {
        List children( TreeModel::children() );
        map_.clear();
        root_ = Item( map_ );
        _add( root_, children );
        _sort();
    }

    private:

    //* item map
    /** used to allow fast mapping between index and value */
    typename Item::Map map_;

    //* root item
    Item root_;

    //* selection
    List selectedItems_;

    //* expanded indexes
    List expandedItems_;

    //* true if values should be sorted when retrieved
    bool sortValues_ = true;

    //* true if current item is valid
    bool hasCurrentItem_ = false;

    //* current item
    ValueType currentItem_;

};

#endif