File: TreeView.cpp

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 (1134 lines) | stat: -rw-r--r-- 34,024 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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
/******************************************************************************
*
* 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 "TreeView.h"

#include "BaseFindDialog.h"
#include "BaseIconNames.h"
#include "IconEngine.h"
#include "InformationDialog.h"
#include "ItemModel.h"
#include "ColorDisplay.h"
#include "ColumnSelectionMenu.h"
#include "ColumnSortingMenu.h"
#include "Color.h"
#include "Singleton.h"
#include "TextEditor.h"
#include "XmlOptions.h"

#include "TreeViewItemDelegate.h"

#include <QCursor>
#include <QHeaderView>
#include <QPainter>
#include <QScrollBar>
#include <QStyledItemDelegate>

//______________________________________________________________________
TreeView::TreeView( QWidget* parent ):
    QTreeView( parent ),
    Counter( "TreeView" )
{
    Debug::Throw( "TreeView::TreeView.\n" );

    // replace item delegate
    if( itemDelegate() ) itemDelegate()->deleteLater();
    auto delegate = new TreeViewItemDelegate( this );
    setItemDelegate( delegate );

    // actions
    _installActions();

    // default configuration
    setAllColumnsShowFocus( true );
    setRootIsDecorated( false );
    setSortingEnabled( true );
    setAnimated( false );

    #if QT_VERSION >= 0x040400
    setExpandsOnDoubleClick( false );
    #endif

    // header menu
    header()->setContextMenuPolicy( Qt::CustomContextMenu );
    header()->setSortIndicator( 0, Qt::AscendingOrder );
    connect( header(), SIGNAL(customContextMenuRequested(QPoint)), SLOT(_raiseHeaderMenu(QPoint)) );
    connect( header(), SIGNAL(sortIndicatorChanged(int,Qt::SortOrder)), SLOT(saveSortOrder()) );

    // hover
    connect( this, SIGNAL(entered(QModelIndex)), SLOT(_indexEntered(QModelIndex)) );

    // configuration
    connect( Base::Singleton::get().application(), SIGNAL(configurationChanged()), SLOT(_updateConfiguration()) );
    _updateConfiguration();

}

//______________________________________________________________________
void TreeView::setItemMargin( int value )
{
    itemMarginFromOptions_ = false;
    _setItemMargin( value );
}

//______________________________________________________________________
void TreeView::setModel( QAbstractItemModel* model )
{

    Debug::Throw( "TreeView::setModel.\n" );
    QTreeView::setModel( model );

    // selected indexes
    model_ = qobject_cast<ItemModel*>( model );
    if( model_ )
    {
        connect( model_, SIGNAL(layoutAboutToBeChanged()), SLOT(storeSelectedIndexes()) );
        connect( model_, SIGNAL(layoutChanged()), SLOT(restoreSelectedIndexes()) );
    }

    // expanded indexes
    if( model_ && model_->supportsExpandedIndexes() )
    {
        connect( model_, SIGNAL(layoutAboutToBeChanged()), SLOT(storeExpandedIndexes()) );
        connect( model_, SIGNAL(layoutChanged()), SLOT(restoreExpandedIndexes()) );
    }

}

//______________________________________________________________________
void TreeView::setItemDelegate( QAbstractItemDelegate* delegate )
{

    // assign new
    QTreeView::setItemDelegate( delegate );

    // update margin to store value
    _setItemMargin( itemMargin_ );

}

//______________________________________________________________________
void TreeView::setItemDelegateForColumn( int column, QAbstractItemDelegate* delegate )
{

    // assign new
    QTreeView::setItemDelegateForColumn( column, delegate );

    // update margin to store value
    _setItemMargin( itemMargin_ );

}

//______________________________________________________________________
void TreeView::setFindEnabled( bool value )
{
    Debug::Throw( "IconView::setFindEnabled.\n" );
    findAction_->setEnabled( value );
    findSelectionAction_->setEnabled( value );
    findAgainAction_->setEnabled( value );
    findSelectionBackwardAction_->setEnabled( value );
    findAgainBackwardAction_->setEnabled( value );
}

//______________________________________________________________________
TextSelection TreeView::selection() const
{

    Debug::Throw( "TreeView::selection.\n" );

    // copy last selection
    TextSelection out;
    out.setFlag( TextSelection::CaseSensitive, TextEditor::lastSelection().flag( TextSelection::CaseSensitive ) );
    out.setFlag( TextSelection::EntireWord, TextEditor::lastSelection().flag( TextSelection::EntireWord ) );

    QString text;
    if( !( text = qApp->clipboard()->text( QClipboard::Selection ) ).isEmpty() ) out.setText( text );
    else if( selectionModel() && model() && selectionModel()->currentIndex().isValid() )
    {

        const QModelIndex current( selectionModel()->currentIndex() );
        if( !(text =  model()->data( current ).toString()).isEmpty() ) out.setText( text );
        else if( allColumnsShowFocus() )
        {

            QModelIndex parent( model()->parent( current ) );

            // loop over all columns, retrieve
            for( int column = 0; column < model()->columnCount( parent ); column++ )
            {
                // get index from column
                const QModelIndex index( model()->index( current.row(), column, parent ) );
                if( index.isValid() && !(text =  model()->data( index ).toString()).isEmpty() )
                {
                    out.setText( text );
                    break;
                }

            }

        }
    }

    // if everything else failed, retrieve last selection
    if( text.isEmpty() ) out.setText( TextEditor::lastSelection().text() );

    return out;

}

//_______________________________________________
bool TreeView::isVisible( const QModelIndex& index ) const
{
    if( !( model() && index.isValid() ) ) return false;
    QModelIndex parent( model()->parent( index ) );
    return (!parent.isValid() ) || ( isExpanded( parent ) && isVisible( parent ) );
}

//_______________________________________________
int TreeView::visibleColumnCount() const
{
    int out(0);
    for( int index=0; model() && index < model()->columnCount(); index++ )
    { if( !isColumnHidden( index ) ) out++; }

    return out;
}

//_______________________________________________
bool TreeView::setOptionName( const QString& value )
{

    Debug::Throw() << "TreeView::setOptionName - value: " << value << endl;

    QString tmp;

    // mask
    bool maskChanged( false );
    tmp = value + "_MASK";
    if( maskOptionName_ != tmp  )
    {
        maskOptionName_ = tmp;
        maskChanged = true;
        if( !XmlOptions::get().contains( maskOptionName() ) ) saveMask();
        else updateMask();

    }

    // sort order
    bool sortChanged( false );
    tmp = value + "_SORT_ORDER";
    if( sortOrderOptionName_ != tmp  )
    {
        sortOrderOptionName_ = tmp;
        sortChanged = true;
    }

    // sort column
    tmp = value + "_SORT_COLUMN";
    if( sortColumnOptionName_ != tmp  )
    {

        sortColumnOptionName_ = tmp;
        sortChanged = true;

    }

    // show header
    bool showHeaderChanged( false );
    tmp = value + "_SHOW_HEADER";
    if( showHeaderOptionName_ != tmp )
    {
        showHeaderOptionName_ = tmp;
        showHeaderChanged = true;
        if( !XmlOptions::get().contains( showHeaderOptionName() ) )
        {

            XmlOptions::get().set<bool>( showHeaderOptionName_, showHeaderAction().isChecked() );

        } else showHeaderAction().setChecked( XmlOptions::get().get<bool>( showHeaderOptionName_ ) );

    }

    // reload sorting
    if( sortChanged )
    {
        if( !( XmlOptions::get().contains( sortOrderOptionName() ) && XmlOptions::get().contains( sortColumnOptionName() ) ) ) saveSortOrder();
        else updateSortOrder();
    }

    return maskChanged || sortChanged || showHeaderChanged;

}

//_______________________________________________
int TreeView::mask() const
{
    Debug::Throw( "TreeView::mask.\n" );
    int mask = 0;
    for( int index=0; model() && index < model()->columnCount(); index++ )
    { if( !isColumnHidden( index ) ) mask |= (1<<index); }
    return mask;
}

//_______________________________________________
void TreeView::setMask( int mask )
{

    Debug::Throw( "TreeView::setMask.\n" );
    for( int index=0; index < model()->columnCount(); index++ )
    {

        // check mask
        if( lockedColumns_ & (1<<index ) ) continue;

        // see if there is a change between new and old mask
        if( isColumnHidden( index ) == !(mask & (1<<index) ) ) continue;
        setColumnHidden( index, !(mask & (1<<index) ) );

    }

    return;

}

//______________________________________________________
void TreeView::storeScrollBarPosition()
{
    if( verticalScrollBar() ) vertical_ = verticalScrollBar()->value();
    if( horizontalScrollBar() ) horizontal_ = horizontalScrollBar()->value();
}

//______________________________________________________
void TreeView::restoreScrollBarPosition()
{
    if( verticalScrollBar() ) verticalScrollBar()->setValue( vertical_ );
    if( horizontalScrollBar() ) horizontalScrollBar()->setValue( horizontal_ );
}

//______________________________________________________
void TreeView::resizeColumns( int mask )
{

    // if no items present, do nothing
    if( !( model() && model()->rowCount() ) ) return;

    for( int i = 0; i < model()->columnCount(); i++ )
    { if( mask & (1<<i) ) resizeColumnToContents(i); }

}

//___________________________________
void TreeView::toggleShowHeader( bool value )
{
    if( header() ) header()->setVisible( value );
    showHeaderAction().setChecked( value );
    if( hasOptionName() ) XmlOptions::get().set<bool>( showHeaderOptionName_, value );
}

//_______________________________________________
void TreeView::updateMask()
{

    Debug::Throw( "TreeView::updateMask.\n" );

    // check model and option availability
    if( !model() ) return;
    if( !hasOptionName() ) return;
    if( !XmlOptions::get().contains( maskOptionName() ) ) return;

    // assign mask from options
    setMask( XmlOptions::get().get<int>( maskOptionName() ) );
    resizeColumns();

}

//_______________________________________________
void TreeView::saveMask()
{

    Debug::Throw( "TreeView::saveMask.\n" );
    if( !hasOptionName() ) return;
    XmlOptions::get().set<int>( maskOptionName(), mask() );

}

//_____________________________________________________________________
void TreeView::updateSortOrder()
{

    Debug::Throw( "TreeView::updateSortOrder.\n" );
    if( !hasOptionName() ) return;
    if( XmlOptions::get().contains( sortColumnOptionName() ) && XmlOptions::get().contains( sortColumnOptionName() ) )
    {
        const bool changed(
            header()->sortIndicatorSection() != XmlOptions::get().get<int>( sortColumnOptionName() ) ||
            header()->sortIndicatorOrder() != XmlOptions::get().get<int>( sortOrderOptionName() ) );

        if( changed )
        { sortByColumn( XmlOptions::get().get<int>( sortColumnOptionName() ), (Qt::SortOrder)(XmlOptions::get().get<int>( sortOrderOptionName() ) ) ); }

    }

}

//_____________________________________________________________________
void TreeView::saveSortOrder()
{

    Debug::Throw( "TreeView::saveSortOrder.\n" );

    // save option
    if( !hasOptionName() ) return;
    XmlOptions::get().set<int>( sortOrderOptionName(), header()->sortIndicatorOrder() );
    XmlOptions::get().set<int>( sortColumnOptionName(), header()->sortIndicatorSection() );

}

//______________________________________________________________________
void TreeView::find( TextSelection selection )
{
    Debug::Throw( "TreeView::find.\n" );
    bool found( selection.flag( TextSelection::Backward ) ? _findBackward( selection, true ):_findForward( selection, true ) );
    if( found ) emit matchFound();
    else emit noMatchFound();
}

//______________________________________________________________________
void TreeView::findAgainForward()
{ _findForward( TextEditor::lastSelection(), true ); }

//______________________________________________________________________
void TreeView::findAgainBackward()
{ _findBackward( TextEditor::lastSelection(), true ); }

//__________________________________________________________
void TreeView::_setItemMargin( int value )
{

    Debug::Throw() << "TreeView::_setItemMargin - value: " << value << endl;
    itemMargin_ = value;

    if( TreeViewItemDelegate* delegate = qobject_cast<TreeViewItemDelegate*>( itemDelegate() ) )
    { delegate->setItemMargin( itemMargin_ ); }

    if( model() )
    {
        for( int iColumn = 0; iColumn < model()->columnCount(); ++iColumn )
        {
            if( TreeViewItemDelegate* delegate = qobject_cast<TreeViewItemDelegate*>( itemDelegateForColumn(iColumn) ) )
            { delegate->setItemMargin( itemMargin_ ); }
        }
    }

}

//__________________________________________________________
void TreeView::storeSelectedIndexes()
{
    if( selectionModel() )
    {
        model_->setSelectedIndexes( selectionModel()->selectedRows() );
        model_->setCurrentIndex( selectionModel()->currentIndex() );
    }
}

//__________________________________________________________
void TreeView::restoreSelectedIndexes()
{

    if( selectionModel() )
    {

        auto selection( model_->selectedIndexes() );

        selectionModel()->clear();
        for( const auto& index:selection )
        { selectionModel()->select( index, QItemSelectionModel::Select|QItemSelectionModel::Rows ); }

        selectionModel()->setCurrentIndex( model_->currentIndex(), QItemSelectionModel::Current );

    }

    return;
}


//__________________________________________________________
void TreeView::storeExpandedIndexes()
{

    // clear
    model_->clearExpandedIndexes();

    // retrieve selected indexes in list
    for( const auto& index:model_->indexes() )
    { if( isExpanded( index ) ) model_->setIndexExpanded( index, true ); }

    storeScrollBarPosition();

}

//________________________________________
void TreeView::restoreExpandedIndexes()
{

    auto indexes( model_->expandedIndexes() );

    collapseAll();
    for( const auto& index:indexes )
    { setExpanded( index, true ); }

    restoreScrollBarPosition();

}

//____________________________________________________________________________
bool TreeView::event( QEvent* event )
{

    switch( event->type() )
    {

        case QEvent::Leave:
        case QEvent::HoverLeave:
        {
            _setHoverIndex( QModelIndex() );
            break;
        }

        default: break;
    }

    return QTreeView::event( event );

}

//____________________________________________________________________
void TreeView::mouseMoveEvent( QMouseEvent *event )
{

    if( hasMouseTracking() && event->buttons() == Qt::NoButton )
    {

        // when mouse tracking is no, need to intercept mouseMoveEvents
        // because they break drag and drop
        _setHoverIndex( indexAt( event->pos() ) );

    } else {

        if( !indexAt( event->pos() ).isValid() )
        { _setHoverIndex( QModelIndex() ); }

        return QTreeView::mouseMoveEvent( event );

    }

}

//__________________________________________________________
void TreeView::mousePressEvent( QMouseEvent* event )
{
    // clear hover index
    _setHoverIndex( QModelIndex() );

    if( (event->button() == Qt::RightButton) && selectionModel() && !indexAt( event->pos() ).isValid() )
    { selectionModel()->clear(); }

    return QTreeView::mousePressEvent( event );
}

//__________________________________________________________
void TreeView::paintEvent( QPaintEvent* event )
{

    if(
        useSelectedColumnColor_ && visibleColumnCount() >= 2 &&
        header() && header()->isVisible() &&
        header()->isSortIndicatorShown() )
    {

        // get selected column
        int selectedColumn( header()->sortIndicatorSection() );
        QRect rect( visualRect( model()->index( 0, selectedColumn ) ) );

        QPainter painter( viewport() );
        painter.setClipRect( event->rect() );
        rect.setTop(0);
        rect.setHeight( height() );
        painter.setBrush( palette().color( QPalette::AlternateBase ) );
        painter.setPen( Qt::NoPen );
        painter.drawRect( rect );
        painter.end();

    }

    return QTreeView::paintEvent( event );

}

//______________________________________________________________________
void TreeView::_createFindDialog()
{

    Debug::Throw( "TreeView::_createFindDialog.\n" );
    if( !findDialog_ )
    {

        // create dialog
        findDialog_ = new BaseFindDialog( this );
        findDialog_->setWindowTitle( tr( "Find in List" ) );

        if( !findWidget_ ) _createFindWidget( false );
        findDialog_->setBaseFindWidget( findWidget_ );

    }

    return;

}

//______________________________________________________________________
void TreeView::_createFindWidget( bool compact )
{

    Debug::Throw( "TreeView::_createFindWidget.\n" );
    if( !findWidget_ )
    {

        // create dialog
        findWidget_ = new BaseFindWidget( this, compact );

        // for now entire word is disabled, because it is unclear how to handle it
        findWidget_->enableEntireWord( false );

        // connections
        connect( findWidget_, SIGNAL(find(TextSelection)), SLOT(find(TextSelection)) );
        connect( this, SIGNAL(matchFound()), findWidget_, SLOT(matchFound()) );
        connect( this, SIGNAL(noMatchFound()), findWidget_, SLOT(noMatchFound()) );
        connect( this, SIGNAL(destroyed()), findWidget_, SLOT(deleteLater()) );

    }

    return;

}

//______________________________________________________________________
bool TreeView::_findForward( const TextSelection& selection, bool rewind )
{
    Debug::Throw( "TreeView::_findForward.\n" );
    if( selection.text().isEmpty() ) return false;

    // store selection
    TextEditor::setLastSelection( selection );

    // check model and selection model
    if( !( model() && selectionModel() ) ) return false;

    QRegExp regexp;
    if( selection.flag( TextSelection::RegExp ) )
    {

        // construct regexp and check
        regexp.setPattern( selection.text() );
        if( !regexp.isValid() )
        {
            InformationDialog( this, tr( "Invalid regular expression. Find canceled" ) ).exec();
            return false;
        }

        // case sensitivity
        regexp.setCaseSensitivity( selection.flag( TextSelection::CaseSensitive ) ? Qt::CaseSensitive : Qt::CaseInsensitive );

    }

    // set first index
    QModelIndex current( selectionModel()->currentIndex() );
    QModelIndex index( ( selection.flag( TextSelection::NoIncrement ) ) ? current:_indexAfter( current ) );

    // if index index is invalid and rewind, set index index of the model
    if( (!index.isValid()) && rewind )
    {
        rewind = false;
        index = _firstIndex();
    }

    // no starting index found. Return
    if( !index.isValid() ) return false;

    // loop over indexes
    while( index.isValid() )
    {

        QString text;
        bool accepted( false );

        // check if column is visible
        if( !( (text = model()->data( index ).toString() ).isEmpty() || isColumnHidden( index.column() ) ) )
        {

            // check if text match
            if( regexp.isValid() && !regexp.pattern().isEmpty() )
            {

                if( regexp.indexIn( text ) >= 0 ) accepted = true;

            } else if( selection.flag( TextSelection::BeginOfWord ) ) {

                if( text.indexOf( selection.text(), 0, selection.flag( TextSelection::CaseSensitive ) ? Qt::CaseSensitive : Qt::CaseInsensitive ) == 0 )
                { accepted = true; }

            } else if( text.indexOf( selection.text(), 0, selection.flag( TextSelection::CaseSensitive ) ? Qt::CaseSensitive : Qt::CaseInsensitive ) >= 0 ) {

                accepted = true;

            }

        }

        if( accepted )
        {

            QItemSelectionModel::SelectionFlags command( QItemSelectionModel::Clear|QItemSelectionModel::Select );
            if( allColumnsShowFocus() ) command |= QItemSelectionModel::Rows;
            selectionModel()->select( index, command );

            // update current index
            command = QItemSelectionModel::Current;
            if( allColumnsShowFocus() ) command |= QItemSelectionModel::Rows;
            selectionModel()->setCurrentIndex( index,  command );

            // quit loop
            return true;

        } else {

            index = _indexAfter( index );
            if( rewind && !index.isValid() )
            {
                rewind = false;
                index = _firstIndex();
            }

        }

    }

    // no match found
    return false;

}

//______________________________________________________________________
bool TreeView::_findBackward( const TextSelection& selection, bool rewind )
{

    Debug::Throw( "TreeView::_findBackward.\n" );
    if( selection.text().isEmpty() ) return false;

    // store selection
    TextEditor::setLastSelection( selection );

    // check model and selection model
    if( !( model() && selectionModel() ) ) return false;

    QRegExp regexp;
    if( selection.flag( TextSelection::RegExp ) )
    {

        // construct regexp and check
        regexp.setPattern( selection.text() );
        if( !regexp.isValid() )
        {
            InformationDialog( this, tr( "Invalid regular expression. Find canceled" ) ).exec();
            return false;
        }

        // case sensitivity
        regexp.setCaseSensitivity( selection.flag( TextSelection::CaseSensitive ) ? Qt::CaseSensitive : Qt::CaseInsensitive );

    }

    // set first index
    QModelIndex current( selectionModel()->currentIndex() );
    QModelIndex index( ( selection.flag( TextSelection::NoIncrement ) ) ? current:_indexBefore( current ) );

    // if index index is invalid and rewind, set index index of the model
    if( (!index.isValid()) && rewind )
    {
        rewind = false;
        index = _lastIndex();
    }

    // no starting index found. Return
    if( !index.isValid() ) return false;

    // loop over indexes
    while( index.isValid() )
    {

        QString text;
        bool accepted( false );

        // check if column is visible
        if( !( (text = model()->data( index ).toString() ).isEmpty() || isColumnHidden( index.column() ) ) )
        {

            // check if text match
            if( regexp.isValid() && !regexp.pattern().isEmpty() )
            {

                if( regexp.indexIn( text ) >= 0 ) accepted = true;

            } else if( selection.flag( TextSelection::BeginOfWord ) ) {

                if( text.indexOf( selection.text(), 0, selection.flag( TextSelection::CaseSensitive ) ? Qt::CaseSensitive : Qt::CaseInsensitive ) == 0 )
                { accepted = true; }

            } else if( text.indexOf( selection.text(), 0, selection.flag( TextSelection::CaseSensitive ) ? Qt::CaseSensitive : Qt::CaseInsensitive ) >= 0 ) {

                accepted = true;

            }

        }

        if( accepted )
        {

            QItemSelectionModel::SelectionFlags command( QItemSelectionModel::Clear|QItemSelectionModel::Select );
            if( allColumnsShowFocus() ) command |= QItemSelectionModel::Rows;
            selectionModel()->select( index, command );

            // update current index
            command = QItemSelectionModel::Current;
            if( allColumnsShowFocus() ) command |= QItemSelectionModel::Rows;
            selectionModel()->setCurrentIndex( index,  command );

            // quit loop
            return true;

        } else {

            index = _indexBefore( index );
            if( rewind && !index.isValid() )
            {
                rewind = false;
                index = _lastIndex();
            }

        }

    }

    return false;

}

//__________________________________________________________
void TreeView::_installActions()
{
    Debug::Throw( "TreeView::_installActions.\n" );

    addAction( selectAllAction_ = new QAction( tr("Select All"), this ) );
    selectAllAction_->setShortcut( QKeySequence::SelectAll );
    selectAllAction_->setShortcutContext( Qt::WidgetShortcut );
    connect( selectAllAction_, SIGNAL(triggered()), SLOT(selectAll()) );

    addAction( findAction_ = new QAction( IconEngine::get( IconNames::Find ), tr("Find"), this ) );
    findAction_->setShortcut( QKeySequence::Find );
    findAction_->setShortcutContext( Qt::WidgetShortcut );
    connect( findAction_, SIGNAL(triggered()), SLOT(_findFromDialog()) );

    addAction( findAgainAction_ = new QAction( tr("Find Again"), this ) );
    findAgainAction_->setShortcut( Qt::CTRL + Qt::Key_G );
    findAgainAction_->setShortcutContext( Qt::WidgetShortcut );
    connect( findAgainAction_, SIGNAL(triggered()), SLOT(findAgainForward()) );

    addAction( findAgainBackwardAction_ = new QAction( this ) );
    findAgainBackwardAction_->setShortcut( Qt::SHIFT + Qt::CTRL + Qt::Key_G );
    findAgainBackwardAction_->setShortcutContext( Qt::WidgetShortcut );
    connect( findAgainBackwardAction_, SIGNAL(triggered()), SLOT(findAgainBackward()) );

    addAction( findSelectionAction_ = new QAction( tr("Find Selection"), this ) );
    findSelectionAction_->setShortcut( Qt::CTRL + Qt::Key_H );
    findSelectionAction_->setShortcutContext( Qt::WidgetShortcut );
    connect( findSelectionAction_, SIGNAL(triggered()), SLOT(findSelectionForward()) );

    addAction( findSelectionBackwardAction_ = new QAction( this ) );
    findSelectionBackwardAction_->setShortcut( Qt::SHIFT + Qt::CTRL + Qt::Key_H );
    findSelectionBackwardAction_->setShortcutContext( Qt::WidgetShortcut );
    connect( findSelectionBackwardAction_, SIGNAL(triggered()), SLOT(findSelectionBackward()) );


    // show header action
    showHeaderAction_ = new QAction( tr("Show List Header"), this );
    showHeaderAction_->setCheckable( true );
    showHeaderAction_->setChecked( true );
    connect( showHeaderAction_, SIGNAL(toggled(bool)), SLOT(toggleShowHeader(bool)) );

}

//___________________________________
void TreeView::_raiseHeaderMenu( const QPoint & pos )
{
    Debug::Throw( "TreeView::_raiseHeaderMenu.\n" );

    // check number of columns
    if( header()->count() <= 1 ) return;

    // create menu and raise.
    ColumnSelectionMenu menu( this, this );
    menu.setCurrentColumn( header()->logicalIndexAt( pos ) );
    if( isSortingEnabled() )
    {
        menu.addSeparator();
        menu.addMenu( new ColumnSortingMenu( &menu, this ) );
    }

    menu.adjustSize();
    menu.exec( header()->mapToGlobal( pos ) );

    // save mask after menu execution,
    // to keep visible columns in sync with option
    saveMask();

}

//_____________________________________________________________________
void TreeView::_findFromDialog()
{
    Debug::Throw( "TreeView::_findFromDialog.\n" );

    // set default text
    // update find text
    QString text( selection().text() );
    if( !text.isEmpty() )
    {
        const int max_length( 1024 );
        text = text.left( max_length );
    }

    // create
    if( useEmbeddedWidgets_ )
    {

        if( !findWidget_ ) _createFindWidget( true );
        findWidget_->show();

    } else {

        if( !findDialog_ ) _createFindDialog();
        findDialog_->centerOnParent();
        findDialog_->show();
        findDialog_->activateWindow();

    }

    findWidget_->enableRegExp( true );
    findWidget_->editor().setFocus();
    findWidget_->synchronize();
    findWidget_->matchFound();
    findWidget_->setText( text );

    return;
}

//____________________________________________________________________
void TreeView::_indexEntered( const QModelIndex& index )
{ if( updatesEnabled() ) _setHoverIndex( index ); }

//____________________________________________________________________
void TreeView::_setHoverIndex( const QModelIndex& index )
{
    if( hoverIndex_ == index ) return;
    hoverIndex_ = index;

    // emit signal
    emit hovered( index );

}

//_____________________________________________________________________
void TreeView::_updateConfiguration()
{
    Debug::Throw( "TreeView::_updateConfiguration.\n" );

    // load mask from option, if any
    updateMask();
    updateSortOrder();

    // alternate color
    const QPalette palette( this->palette() );
    setAlternatingRowColors(
        ( XmlOptions::get().get<bool>( "USE_ALTERNATE_COLOR" ) || forceAlternatingRowColors_ ) &&
        palette.color( QPalette::AlternateBase ) != palette.color( QPalette::Base ) );

    // try load selected column color from option
    useSelectedColumnColor_ = XmlOptions::get().get<bool>( "USE_SELECTED_COLUMN_COLOR" );

    // item margin
    if( itemMarginFromOptions_ && XmlOptions::get().contains( "LIST_ITEM_MARGIN" ) )
    { _setItemMargin( XmlOptions::get().get<int>( "LIST_ITEM_MARGIN" ) ); }

    // icon size
    if( iconSizeFromOptions_ && XmlOptions::get().contains( "LIST_ICON_SIZE" )  )
    {
        int iconSize( XmlOptions::get().get<int>( "LIST_ICON_SIZE" ) );
        QTreeView::setIconSize( QSize( iconSize, iconSize )  );

        #if QT_VERSION < 0x050000
        emit iconSizeChanged( this->iconSize() );
        #endif

    }

}

//_________________________________________________________
QModelIndex TreeView::_firstIndex() const
{ return model()->index( 0, 0 ); }

//_________________________________________________________
QModelIndex TreeView::_lastIndex() const
{

    if( !model()->rowCount() ) return QModelIndex();

    QModelIndex out( model()->index( model()->rowCount()-1, 0 ) );
    while( out.isValid() && isExpanded( out ) && model()->hasChildren( out ) )
    { out = model()->index( model()->rowCount( out )-1, 0, out ); }

    // select last column
    QModelIndex parent = model()->parent( out );
    out = model()->index( out.row(), model()->columnCount( parent )-1, parent );

    return out;

}

//_________________________________________________________
QModelIndex TreeView::_indexAfter( const QModelIndex& current ) const
{

    QModelIndex out;
    if( !current.isValid() ) return out;

    // get parent
    QModelIndex parent( model()->parent( current ) );

    // assign next column if valid
    if( current.column()+1 < model()->columnCount( parent ) ) out = model()->index( current.row(), current.column()+1, parent );
    else {

        QModelIndex first_column_index( model()->index( current.row(), 0, parent ) );

        // assign first children if current is expanded and has children
        if( first_column_index.isValid() && isExpanded( first_column_index ) && model()->hasChildren( first_column_index ) )
        { out = model()->index( 0, 0, first_column_index ); }

        // assign next row if valid
        if( !out.isValid() ) out = model()->index( current.row()+1, 0, parent );

        // assign next row from parent if valid
        if( (!out.isValid()) && parent.isValid() ) out = model()->index( parent.row()+1, 0, model()->parent( parent ) );

    }

    return out;

}

//_________________________________________________________
QModelIndex TreeView::_indexBefore( const QModelIndex& current ) const
{
    Debug::Throw() << "TreeView::_indexBefore - " << current.row() << "," << current.column() << "," << current.isValid() << endl;
    QModelIndex out;
    if( !current.isValid() ) return out;

    // get parent
    QModelIndex parent( model()->parent( current ) );

    // assign next column if valid
    if( current.column() > 0 ) out = model()->index( current.row(), current.column()-1, parent );
    else {

        if( current.row() > 0 )
        {

            out = model()->index( current.row()-1, 0, parent );
            while( out.isValid() && isExpanded( out ) && model()->hasChildren( out ) )
            { out = model()->index( model()->rowCount( out )-1, 0, out ); }

            // select last column
            parent = model()->parent( out );
            out = model()->index( out.row(), model()->columnCount( parent )-1, parent );

        } else {

            // select last column of parent
            if( parent.isValid() )
            { out = model()->index( parent.row(), model()->columnCount( model()->parent( parent ) )-1, model()->parent( parent ) ); }

        }

    }

    return out;

}

//_________________________________________________________
TreeView::Container::Container( QWidget* parent ):
    QWidget( parent ),
    Counter( "TreeView::Container" ),
    treeView_( new TreeView )
{ _initialize(); }

//_________________________________________________________
TreeView::Container::Container( QWidget* parent, TreeView* treeView ):
    QWidget( parent ),
    Counter( "TreeView::Container" ),
    treeView_( treeView )
{ _initialize(); }

//_________________________________________________________
void TreeView::Container::_initialize()
{
    Debug::Throw( "TreeView::Container::_initialize.\n" );
    treeView_->setParent( this );

    // setup layout
    QVBoxLayout* vLayout = new QVBoxLayout;
    vLayout->setMargin(0);
    vLayout->setSpacing(2);
    setLayout( vLayout );

    // treeview
    vLayout->addWidget( treeView_ );
    treeView_->useEmbeddedWidgets_ = true;

    // find widget
    treeView_->_createFindWidget( true );
    treeView_->findWidget_->setParent( this );
    vLayout->addWidget( treeView_->findWidget_ );
    treeView_->findWidget_->hide();

    connect( &treeView_->findWidget_->closeButton(), SIGNAL(clicked()), treeView_, SLOT(setFocus()) );
}