File: functionselection.cpp

package info (click to toggle)
kcachegrind 4%3A16.08.3-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 1,844 kB
  • ctags: 3,250
  • sloc: cpp: 28,541; perl: 325; python: 235; makefile: 7; sh: 5
file content (899 lines) | stat: -rw-r--r-- 25,771 bytes parent folder | download
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
/* This file is part of KCachegrind.
   Copyright (c) 2002-2015 Josef Weidendorfer <Josef.Weidendorfer@gmx.de>

   KCachegrind 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, version 2.

   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; see the file COPYING.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.
*/

/*
 * For function selection, to be put into a QDockWindow
 */

#include "functionselection.h"

#include <QLabel>
#include <QPushButton>
#include <QComboBox>
#include <QLineEdit>
#include <QRegExp>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QAction>
#include <QMenu>
#include <QDebug>
#include <QTreeView>
#include <QHeaderView>
#include <QToolTip>
#include <QHelpEvent>

#include "traceitemview.h"
#include "stackbrowser.h"
#include "costlistitem.h"
#include "globalconfig.h"
#include "functionlistmodel.h"


// custom item delegate for function list
AutoToolTipDelegate::AutoToolTipDelegate(QObject* parent)
    : QStyledItemDelegate(parent)
{}

AutoToolTipDelegate::~AutoToolTipDelegate()
{}

bool AutoToolTipDelegate::helpEvent(QHelpEvent* e, QAbstractItemView* view,
                                    const QStyleOptionViewItem& option,
                                    const QModelIndex& index)
{
    if (!e || !view)
        return false;

    if ( e->type() != QEvent::ToolTip )
        return QStyledItemDelegate::helpEvent(e, view, option, index);

    QRect rect = view->visualRect(index);
    QSize size = sizeHint(option, index);
    if ( rect.width() < size.width() ) {
        QVariant tooltip = index.data(Qt::DisplayRole);
        if ( tooltip.canConvert<QString>() ) {
            QToolTip::showText(e->globalPos(), tooltip.toString(), view );
            return true;
        }
    }

    if ( !QStyledItemDelegate::helpEvent( e, view, option, index ) )
        QToolTip::hideText();

    return true;
}




//
// FunctionSelection
//

FunctionSelection::FunctionSelection( TopLevelBase* top,
				      QWidget* parent)
    : QWidget(parent), TraceItemView(0, top)
{
  _group = 0;
  _inSetGroup = false;
  _inSetFunction = false;
  _functionListSortOrder = Qt::DescendingOrder;

  setTitle(tr("Function Profile"));

  // first row with search label and group type combo
  QHBoxLayout* hboxLayout = new QHBoxLayout();
  hboxLayout->setSpacing(6);
  hboxLayout->setMargin(0);

  searchLabel = new QLabel(this);
  searchLabel->setText(tr("&Search:"));
  searchLabel->setWordWrap(false);
  hboxLayout->addWidget(searchLabel);

  searchEdit = new QLineEdit(this);
  searchLabel->setBuddy(searchEdit);
  hboxLayout->addWidget(searchEdit);

  groupBox = new QComboBox(this);
  hboxLayout->addWidget(groupBox);

  // vertical layout: first row, group list, function list
  QVBoxLayout* vboxLayout = new QVBoxLayout(this);
  vboxLayout->setSpacing(6);
  vboxLayout->setMargin(3);
  vboxLayout->addLayout(hboxLayout);

  groupList = new QTreeWidget(this);
  QStringList groupHeader;
  groupHeader << tr("Self") << tr("Group");
  groupList->setHeaderLabels(groupHeader);

#if QT_VERSION >= 0x050000
  groupList->header()->setSectionsClickable(true);
#else
  groupList->header()->setClickable(true);
#endif
  groupList->header()->setSortIndicatorShown(false);
  groupList->header()->stretchLastSection();
  groupList->setIconSize(QSize(99,99));
  groupList->setMaximumHeight(150);
  groupList->setRootIsDecorated(false);
  groupList->setUniformRowHeights(true);
  groupList->sortByColumn(0, Qt::AscendingOrder);
  vboxLayout->addWidget(groupList);

  functionListModel = new FunctionListModel();
  functionListModel->setMaxCount(GlobalConfig::maxListCount());

  functionList = new QTreeView(this);
  functionList->setRootIsDecorated(false);
  functionList->setAllColumnsShowFocus(true);
  functionList->setAutoScroll(false);
  functionList->setContextMenuPolicy(Qt::CustomContextMenu);
  functionList->setUniformRowHeights(true);
#if QT_VERSION >= 0x050000
  functionList->header()->setSectionsClickable(true);
  functionList->header()->setSectionResizeMode(QHeaderView::Interactive);
#else
  functionList->header()->setClickable(true);
  functionList->header()->setResizeMode(QHeaderView::Interactive);
#endif
  functionList->header()->setSortIndicatorShown(false);
  functionList->header()->setSortIndicator(0, Qt::DescendingOrder);
  // for columns 3 and 4 (all others get resized)
  functionList->header()->setDefaultSectionSize(200);
  functionList->setModel(functionListModel);
  functionList->setItemDelegate(new AutoToolTipDelegate(functionList));
  vboxLayout->addWidget(functionList);

  // only to adjust size, will be repopulated on data change
  QStringList args;
  args << tr("(No Grouping)")
       << ProfileContext::i18nTypeName(ProfileContext::Object)
       << ProfileContext::i18nTypeName(ProfileContext::File)
       << ProfileContext::i18nTypeName(ProfileContext::Class)
       << ProfileContext::i18nTypeName(ProfileContext::FunctionCycle);
  groupBox->addItems(args);
  connect(groupBox, SIGNAL(activated(int)),
	  this, SLOT(groupTypeSelected(int)));

  // search while typing...
  connect(searchEdit, SIGNAL(textChanged(const QString&)),
	  this, SLOT(searchChanged(const QString&)));
  connect(&_searchTimer, SIGNAL(timeout()),
	  this, SLOT(queryDelayed()));
  // select first matching group/function on return
  connect(searchEdit, SIGNAL(returnPressed()),
	  this, SLOT(searchReturnPressed()));
  searchEdit->setMinimumWidth(50);

  // single click release activation
  connect(functionList, SIGNAL(clicked(QModelIndex)),
          this, SLOT(functionActivated(QModelIndex)));
  connect(functionList, SIGNAL(activated(QModelIndex)),
          this, SLOT(functionActivated(QModelIndex)));
  connect(functionList, SIGNAL(customContextMenuRequested(const QPoint &)),
          this, SLOT(functionContext(const QPoint &)));
  connect(functionList->header(), SIGNAL(sectionClicked(int)),
          this, SLOT(functionHeaderClicked(int)));

  connect(groupList,
          SIGNAL( currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)),
          this, SLOT( groupSelected(QTreeWidgetItem*,QTreeWidgetItem*) ) );
  connect(groupList, SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)),
          this, SLOT(groupDoubleClicked(QTreeWidgetItem*,int)));

  groupList->setContextMenuPolicy(Qt::CustomContextMenu);
  connect(groupList,
          SIGNAL(customContextMenuRequested(const QPoint &) ),
          this, SLOT(groupContext(const QPoint &)));
  connect(groupList->header(),
          SIGNAL(sectionClicked(int)), this, SLOT(groupHeaderClicked(int)));

  // start hidden
  groupList->hide();

  setWhatsThis(whatsThis());
}

QString FunctionSelection::whatsThis() const
{
    return tr(
	// xgettext: no-c-format
	"<b>The Flat Profile</b>"
	"<p>The flat profile contains a group and a function "
	"selection list. The group list contains all groups "
	"where costs "
	"are spent in, depending on the chosen group type. "
	"The group list is hidden when group type 'Function' "
	"is selected.</p>"
	"<p>The function list contains the functions of the "
	"selected group (or all for 'Function' group type), "
	"ordered by the costs spent therein. Functions with "
	"costs less than 1% are hidden on default.</p>");
}

void FunctionSelection::setData(TraceData* d)
{
  TraceItemView::setData(d);

  _group = 0;
  _groupSize.clear();
  _hc.clear(GlobalConfig::maxListCount());
  groupList->clear();
  functionListModel->resetModelData(d, 0, QString(), 0);
}

void FunctionSelection::searchReturnPressed()
{
  query(searchEdit->text());

  QTreeWidgetItem* item;
  if (_groupType != ProfileContext::Function) {
      // if current group not matching, select first matching group
      item  = groupList->currentItem();
      if (!item || item->isHidden()) {
          int i;
          item = 0;
          for (i=0; i<groupList->topLevelItemCount(); i++) {
              item = groupList->topLevelItem(i);
              if (!item->isHidden()) break;
          }
          if (!item) return;

          setGroup(((CostListItem*)item)->costItem());
          return;
      }
  }
  // activate top function in functionList
  selectTopFunction();
  functionList->setFocus();
}

// trigger the query after some delay, dependent on length
void FunctionSelection::searchChanged(const QString& q)
{
  _searchDelayed = q;
  int ms = 100;
  if (q.length()<5) ms = 200;
  if (q.length()<2) ms = 300;
  _searchTimer.setSingleShot(true);
  _searchTimer.start(ms);
}

void FunctionSelection::queryDelayed()
{
  query(_searchDelayed);
}

void FunctionSelection::functionContext(const QPoint & p)
{
    QMenu popup;
    TraceFunction* f = 0;

    QAction* activateFunctionAction = 0;
    QModelIndex i = functionList->indexAt(p);
    if (i.isValid()) {
        f = functionListModel->function(i);
	if (f) {
	    QString menuText = tr("Go to '%1'").arg(GlobalConfig::shortenSymbol(f->prettyName()));
	    activateFunctionAction = popup.addAction(menuText);
	    popup.addSeparator();
	}
        if ((i.column() == 0) || (i.column() == 1)) {
            addEventTypeMenu(&popup,false);
            popup.addSeparator();
        }
    }

    addGroupMenu(&popup);
    popup.addSeparator();
    addGoMenu(&popup);

    QPoint pDiff = QPoint(0, functionList->header()->height());
    QAction* a = popup.exec(functionList->mapToGlobal(p + pDiff));
    if (a == activateFunctionAction)
	activated(f);
}

void FunctionSelection::groupContext(const QPoint & p)
{
    QMenu popup;

    int c = groupList->columnAt(p.x());
    if (c == 0) {
        addEventTypeMenu(&popup,false);
        popup.addSeparator();
    }
    addGroupMenu(&popup);
    popup.addSeparator();
    addGoMenu(&popup);

    QPoint headerSize = QPoint(0, groupList->header()->height());
    popup.exec(groupList->mapToGlobal(p + headerSize));
}

void FunctionSelection::addGroupAction(QMenu* m,
				       ProfileContext::Type v,
				       const QString& s)
{
    QAction* a;
    if (s.isEmpty())
	a = m->addAction(ProfileContext::i18nTypeName(v));
    else
	a = m->addAction(s);
    a->setData((int)v);
    a->setCheckable(true);
    a->setChecked(_groupType == v);
}

void FunctionSelection::addGroupMenu(QMenu* menu)
{
    QMenu* m = menu->addMenu(tr("Grouping"));

    if (_groupType != ProfileContext::Function) {
	addGroupAction(m,  ProfileContext::Function, tr("No Grouping"));
	m->addSeparator();
    }
    if (_data->objectMap().count()>1)
	addGroupAction(m, ProfileContext::Object);
    if (_data->fileMap().count()>1)
	addGroupAction(m, ProfileContext::File);
    if (_data->classMap().count()>1)
	addGroupAction(m, ProfileContext::Class);
    addGroupAction(m, ProfileContext::FunctionCycle);

    connect(m, SIGNAL(triggered(QAction*)),
	  this, SLOT(groupTypeSelected(QAction*)));
}    


void FunctionSelection::groupTypeSelected(QAction* a)
{
    selectedGroupType( (ProfileContext::Type) a->data().toInt() );
}

void FunctionSelection::groupTypeSelected(int cg)
{
    int t = groupBox->itemData(cg).toInt();
    if (t == 0)
	t = ProfileContext::Function; // always works

    selectedGroupType((ProfileContext::Type) t);
}

CostItem* FunctionSelection::canShow(CostItem* i)
{
    ProfileContext::Type t = i ? i->type() : ProfileContext::InvalidType;

    switch(t) {
    case ProfileContext::Function:
    case ProfileContext::FunctionCycle:
    case ProfileContext::Object:
    case ProfileContext::File:
    case ProfileContext::Class:
	break;

    case ProfileContext::Instr:
	i = ((TraceInstr*)i)->function();
	break;

    case ProfileContext::Line:
	i = ((TraceLine*)i)->functionSource()->function();
	break;

    default:
	i = 0;
	break;
  }
  return i;
}


void FunctionSelection::selectFunction(TraceFunction* f,
                                       bool ensureVisible)
{
    QModelIndex i = functionListModel->indexForFunction(f, true);
    if (!i.isValid()) return;

    if (ensureVisible)
        functionList->scrollTo(i, QAbstractItemView::EnsureVisible);

    _inSetFunction = true;
    QModelIndex last = functionListModel->index(i.row(), 4);
    QItemSelection s(i, last);
    functionList->selectionModel()->select(s, QItemSelectionModel::ClearAndSelect);
    _inSetFunction = false;
}

void FunctionSelection::doUpdate(int changeType, bool)
{
    // Special case ?
    if (changeType == selectedItemChanged) return;

    // we do not show cost 2 at all...
    if (changeType == eventType2Changed) return;

    if (changeType == eventTypeChanged) {
        int i;

#if QT_VERSION >= 0x050000
        groupList->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
#else
        groupList->header()->setResizeMode(0, QHeaderView::ResizeToContents);
#endif
        // need to disable sorting! Otherwise each change of shown cost
        // reorders list and changes order returned by topLevelItem()
        groupList->setSortingEnabled(false);
        for (i=0; i<groupList->topLevelItemCount(); ++i) {
            CostListItem* item = (CostListItem*) groupList->topLevelItem(i);
            item->setEventType(_eventType);
        }
#if QT_VERSION >= 0x050000
        groupList->header()->setSectionResizeMode(0, QHeaderView::Interactive);
#else
        groupList->header()->setResizeMode(0, QHeaderView::Interactive);
#endif
        groupList->setSortingEnabled(true);
        groupList->header()->setSortIndicatorShown(false);

        functionListModel->setEventType(_eventType);
        // previous line resets the model: reselect active item
        selectFunction(dynamic_cast<TraceFunction*>(_activeItem));
        setCostColumnWidths();
        return;
    }

    if (changeType == activeItemChanged) {
	if (_activeItem ==0) {
	    functionList->clearSelection();
	    return;
	}
	switch(_activeItem->type()) {
	case ProfileContext::Object:
	case ProfileContext::File:
	case ProfileContext::Class:
	    setGroup((TraceCostItem*)_activeItem);
	    return;
	default: break;
	}

	// active item is a function
	TraceFunction* f = (TraceFunction*) _activeItem;

	// if already current, nothing to do
        QModelIndex i = functionList->currentIndex();
        if (functionListModel->function(i) == f) {
	    return;	    
	}

        // reset search (as not activated from this view)
        query(QString::null);	//krazy:exclude=nullstrassign for old broken gcc

	// select cost item group of function
	switch(_groupType) {
	case ProfileContext::Object: setGroup(f->object()); break;
	case ProfileContext::Class:  setGroup(f->cls()); break;
	case ProfileContext::File:   setGroup(f->file());  break;
	case ProfileContext::FunctionCycle: setGroup(f->cycle());  break;
	default:
	    break;
	}

        selectFunction(f);
	return;
    }

    if (changeType & dataChanged) {
	groupBox->clear();
	groupBox->addItem(tr("(No Grouping)"), ProfileContext::Function);
	if (_data) {
	    if (_data->objectMap().count()>1)
		groupBox->addItem(ProfileContext::i18nTypeName(ProfileContext::Object),
				  ProfileContext::Object);
	    if (_data->fileMap().count()>1)
		groupBox->addItem(ProfileContext::i18nTypeName(ProfileContext::File),
				  ProfileContext::File);
	    if (_data->classMap().count()>1)
		groupBox->addItem(ProfileContext::i18nTypeName(ProfileContext::Class),
				  ProfileContext::Class);
	    groupBox->addItem(ProfileContext::i18nTypeName(ProfileContext::FunctionCycle),
			      ProfileContext::FunctionCycle);
	}
    }

    if (changeType & groupTypeChanged) {
	if (_activeItem && (_activeItem->type() == ProfileContext::Function)) {
	    TraceFunction* f = (TraceFunction*) _activeItem;

	    // select cost item group of function
	    switch(_groupType) {
	    case ProfileContext::Object: _group = f->object(); break;
	    case ProfileContext::Class:  _group = f->cls(); break;
	    case ProfileContext::File:   _group = f->file();  break;
	    case ProfileContext::FunctionCycle: _group = f->cycle();  break;
	    default:
		_group = 0;
		break;
	    }
	}

	int id = groupBox->findData(_groupType);
	if (id < 0) id = 0; // if not found, default to first entry
	groupBox->setCurrentIndex(id);

	if (_groupType == ProfileContext::Function)
	    groupList->hide();
	else
	    groupList->show();
    }

    // reset searchEdit
    _searchString = QString();
    query(QString::null);	//krazy:exclude=nullstrassign for old broken gcc

    refresh();
}


/*
 * This set/selects a group of the set available within the
 * current group type
 */
void FunctionSelection::setGroup(TraceCostItem* g)
{
  if (!g) return;
  if (g->type() != _groupType) return;
  if (g == _group) return;
  _group = g;

  QTreeWidgetItem* item = 0;
  int i;
  for (i=0; i < groupList->topLevelItemCount(); i++) {
      item = groupList->topLevelItem(i);
      if (((CostListItem*)item)->costItem() == g)
          break;
  }

  if (item) {
    groupList->scrollToItem(item);
    // prohibit signalling of a group selection
    _inSetGroup = true;
    _group = 0;
    groupList->setCurrentItem(item);
    _inSetGroup = false;
  }
  else
    groupList->clearSelection();
}


void FunctionSelection::refresh()
{
    groupList->clear();

    // make cost columns as small as possible:
    // the new functions make them as wide as needed
    groupList->setColumnWidth(0, 50);
    groupList->headerItem()->setText(1, ProfileContext::i18nTypeName(_groupType));

    functionListModel->setMaxCount(GlobalConfig::maxListCount());

    if (!_data || _data->parts().count()==0) {
        functionListModel->resetModelData(0, 0, QString(), 0);
        selectTopFunction();
	return;
    }


  TraceObjectMap::Iterator oit;
  TraceClassMap::Iterator cit;
  TraceFileMap::Iterator fit;

  // Fill up group list.
  // Always show group of current function, even if cost below low limit.
  //

  _hc.clear(GlobalConfig::maxListCount());

  switch(_groupType) {
  case ProfileContext::Object:

    for ( oit = _data->objectMap().begin();
          oit != _data->objectMap().end(); ++oit )
      _hc.addCost(&(*oit), (*oit).subCost(_eventType));
    break;

  case ProfileContext::Class:

    for ( cit = _data->classMap().begin();
          cit != _data->classMap().end(); ++cit )
      _hc.addCost(&(*cit), (*cit).subCost(_eventType));
    break;

  case ProfileContext::File:

    for ( fit = _data->fileMap().begin();
          fit != _data->fileMap().end(); ++fit )
      _hc.addCost(&(*fit), (*fit).subCost(_eventType));
    break;

  case ProfileContext::FunctionCycle:
    {
      // add all cycles
      foreach(TraceCostItem *group, _data->functionCycles())
	_hc.addCost(group, group->subCost(_eventType));
    }

  break;

  default:
    {
      _group = 0;
      functionListModel->resetModelData(_data, _group, _searchString, _eventType);
      selectFunction(dynamic_cast<TraceFunction*>(_activeItem));
      setCostColumnWidths();
      return;
    }
  }

  // update group from _activeItem if possible
  if (_activeItem && (_activeItem->type() == _groupType))
    _group = (TraceCostItem*) _activeItem;

  QTreeWidgetItem *item = 0, *activeItem = 0;
  QList<QTreeWidgetItem*> items;

  // we always put group of active item in list, even if
  // it would be skipped because of small costs
  if (_group) {
    activeItem = new CostListItem(groupList, _group, _eventType);
    items.append(activeItem);
  }

  for(int i=0; i<_hc.realCount(); i++) {
    TraceCostItem *group = (TraceCostItem*)_hc[i];
    // do not put group of active item twice into list
    if (group == _group) continue;
    item = new CostListItem(groupList, group, _eventType);
    items.append(item);
  }
  if (_hc.hasMore()) {
      // a placeholder for all the cost items skipped ...
      item = new CostListItem(groupList, _hc.count() - _hc.maxSize(),
                              (TraceCostItem*)_hc[_hc.maxSize()-1], _eventType);
      items.append(item);
  }

#if QT_VERSION >= 0x050000
  groupList->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
#else
  groupList->header()->setResizeMode(0, QHeaderView::ResizeToContents);
#endif
  groupList->setSortingEnabled(false);
  groupList->addTopLevelItems(items);
  groupList->setSortingEnabled(true);
  // always reset to cost sorting
  groupList->sortByColumn(0, Qt::DescendingOrder);
  groupList->header()->setSortIndicatorShown(false);
#if QT_VERSION >= 0x050000
  groupList->header()->setSectionResizeMode(0, QHeaderView::Interactive);
#else
  groupList->header()->setResizeMode(0, QHeaderView::Interactive);
#endif

  if (activeItem) {
    groupList->scrollToItem(activeItem);
    _inSetGroup = true;
    _group = 0;
    groupList->setCurrentItem(activeItem);
    _inSetGroup = false;
  }
  else
    groupList->clearSelection();
}


void FunctionSelection::groupSelected(QTreeWidgetItem* i, QTreeWidgetItem*)
{
  if (!i) return;
  if (!_data) return;

  TraceCostItem* g = ((CostListItem*) i)->costItem();
  if (!g) return;
  if (g == _group) return;
  _group = g;

  functionListModel->resetModelData(_data, g, _searchString, _eventType);
  selectFunction(dynamic_cast<TraceFunction*>(_activeItem));
  setCostColumnWidths();

  // Do not emit signal if cost item was changed programatically
  if (!_inSetGroup) {
      if (_topLevel)
	  _topLevel->setGroupDelayed(g);
  }
}

void FunctionSelection::groupDoubleClicked(QTreeWidgetItem* i, int)
{
  if (!i) return;
  if (!_data) return;
  TraceCostItem* g = ((CostListItem*) i)->costItem();

  if (!g) return;
  // group must be selected first
  if (g != _group) return;

  activated(g);
}

void FunctionSelection::groupHeaderClicked(int col)
{
    groupList->sortByColumn(col, Qt::DescendingOrder);
}

TraceCostItem* FunctionSelection::group(QString s)
{
    int i;
    for (i=0; i<groupList->topLevelItemCount(); i++) {
        CostListItem* item = (CostListItem*) groupList->topLevelItem(i);
        if (item->costItem()->name() == s)
          return item->costItem();
    }

    return 0;
}


void FunctionSelection::functionActivated(const QModelIndex& i)
{
  if (!_data) return;

  TraceFunction* f = functionListModel->function(i);
  if (!f) return;

  if (!_inSetFunction)
    activated(f);
}

void FunctionSelection::updateGroupSizes(bool hideEmpty)
{
    int i;
    for (i=0; i<groupList->topLevelItemCount(); i++) {
        CostListItem* item = (CostListItem*) groupList->topLevelItem(i);
        int size = (_groupSize.contains(item->costItem())) ?
                   _groupSize[item->costItem()] : -1;
        item->setSize(size);
        item->setHidden(hideEmpty && (size<0));
    }
}

void FunctionSelection::query(QString query)
{
  if(!_data)
     return;  
  if (searchEdit->text() != query)
    searchEdit->setText(query);
  if (_searchString == query) {
    // when resetting query, get rid of group sizes
    if (query.isEmpty()) {
      _groupSize.clear();
      updateGroupSizes(false);
    }
    return;
  }
  _searchString = query;

  QRegExp re(query, Qt::CaseInsensitive, QRegExp::Wildcard);
  _groupSize.clear();

  TraceFunction* f = 0;
  TraceFunctionList list2;

  _hc.clear(GlobalConfig::maxListCount());

  TraceFunctionMap::Iterator it;
  for ( it = _data->functionMap().begin();
	it != _data->functionMap().end(); ++it ) {
    f = &(*it);
    if (re.indexIn(f->prettyName())>=0) {
      if (_group) {
	if (_groupType==ProfileContext::Object) {
	  if (_groupSize.contains(f->object()))
	    _groupSize[f->object()]++;
	  else
	    _groupSize[f->object()] = 1;
	  if (f->object() != _group) continue;
	}
	else if (_groupType==ProfileContext::Class) {
	  if (_groupSize.contains(f->cls()))
	    _groupSize[f->cls()]++;
	  else
	    _groupSize[f->cls()] = 1;
	  if (f->cls() != _group) continue;
	}
	else if (_groupType==ProfileContext::File) {
	  if (_groupSize.contains(f->file()))
	    _groupSize[f->file()]++;
	  else
	    _groupSize[f->file()] = 1;
	  if (f->file() != _group) continue;
	}
	else if (_groupType==ProfileContext::FunctionCycle) {
	  if (_groupSize.contains(f->cycle()))
	    _groupSize[f->cycle()]++;
	  else
	    _groupSize[f->cycle()] = 1;
	  if (f->cycle() != _group) continue;
	}
      }
      _hc.addCost(f, f->inclusive()->subCost(_eventType));
    }
  }
  updateGroupSizes(true);

  functionListModel->resetModelData(_data, _group, _searchString, _eventType);
  selectFunction(dynamic_cast<TraceFunction*>(_activeItem));
  setCostColumnWidths();
}

bool FunctionSelection::selectTopFunction()
{
    QModelIndex i = functionListModel->index(0,0);
    TraceFunction* f = functionListModel->function(i);

    // pre-select before activation to not trigger a refresh of this view
    _activeItem = f;
    selectFunction(f);

    functionActivated(i);

    return (f!=0);
}

void FunctionSelection::setCostColumnWidths()
{
    functionList->resizeColumnToContents(1);

    if (_eventType && (_eventType->subCost(_data->callMax())>0) ) {
        functionList->resizeColumnToContents(0);
        functionList->resizeColumnToContents(2);
    }
    else {
        functionList->header()->resizeSection(0, 0);
        functionList->header()->resizeSection(2, 0);
    }
}

void FunctionSelection::functionHeaderClicked(int col)
{
    if ((_functionListSortOrder== Qt::AscendingOrder) || (col<3))
        _functionListSortOrder = Qt::DescendingOrder;
    else
        _functionListSortOrder = Qt::AscendingOrder;

    functionList->sortByColumn(col, _functionListSortOrder);
    selectFunction(dynamic_cast<TraceFunction*>(_activeItem), false);
    setCostColumnWidths();
}



#include "functionselection.moc"