File: sourceview.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 (945 lines) | stat: -rw-r--r-- 27,323 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
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
/* This file is part of KCachegrind.
   Copyright (c) 2011-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.
*/

/*
 * Source View
 */

#include "sourceview.h"

#include <QDebug>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QAction>
#include <QMenu>
#include <QScrollBar>
#include <QHeaderView>
#include <QKeyEvent>

#include "globalconfig.h"
#include "sourceitem.h"



//
// SourceView
//


SourceView::SourceView(TraceItemView* parentView,
                       QWidget* parent)
  : QTreeWidget(parent), TraceItemView(parentView)
{
  _inSelectionUpdate = false;

  _arrowLevels = 0;

  setColumnCount(5);
  setRootIsDecorated(false);
  setAllColumnsShowFocus(true);
  setUniformRowHeights(true);
  // collapsing call/jump lines by double-click is confusing
  setExpandsOnDoubleClick(false);

  QStringList headerLabels;
  headerLabels << tr( "#" )
               << tr( "Cost" )
               << tr( "Cost 2" )
               << ""
	       <<  tr( "Source");
  setHeaderLabels(headerLabels);

  // sorting will be enabled after refresh()
  sortByColumn(0, Qt::AscendingOrder);
  header()->setSortIndicatorShown(false);
  this->setItemDelegate(new SourceItemDelegate(this));
  this->setWhatsThis( whatsThis());

  connect( this,
           SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)),
           SLOT(selectedSlot(QTreeWidgetItem*,QTreeWidgetItem*)));

  setContextMenuPolicy(Qt::CustomContextMenu);
  connect( this,
           SIGNAL(customContextMenuRequested(const QPoint &)),
           SLOT(context(const QPoint &)));

  connect(this,
          SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)),
          SLOT(activatedSlot(QTreeWidgetItem*,int)));

  connect(header(), SIGNAL(sectionClicked(int)),
          this, SLOT(headerClicked(int)));
}

QString SourceView::whatsThis() const
{
    return tr( "<b>Annotated Source</b>"
		 "<p>The annotated source list shows the "
		 "source lines of the current selected function "
		 "together with (self) cost spent while executing the "
		 "code of this source line. If there was a call "
		 "in a source line, lines with details on the "
		 "call happening are inserted into the source: "
		 "the cost spent inside of the call, the "
		 "number of calls happening, and the call destination.</p>"
		 "<p>Select a inserted call information line to "
		 "make the destination function current.</p>");
}

void SourceView::context(const QPoint & p)
{
  int c = columnAt(p.x());
  QTreeWidgetItem* i = itemAt(p);
  QMenu popup;

  TraceLineCall* lc = i ? ((SourceItem*) i)->lineCall() : 0;
  TraceLineJump* lj = i ? ((SourceItem*) i)->lineJump() : 0;
  TraceFunction* f = lc ? lc->call()->called() : 0;
  TraceLine* line = lj ? lj->lineTo() : 0;

  QAction* activateFunctionAction = 0;
  QAction* activateLineAction = 0;
  if (f) {
      QString menuText = tr("Go to '%1'").arg(GlobalConfig::shortenSymbol(f->prettyName()));
      activateFunctionAction = popup.addAction(menuText);
      popup.addSeparator();
  }
  else if (line) {
      QString menuText = tr("Go to Line %1").arg(line->name());
      activateLineAction = popup.addAction(menuText);
      popup.addSeparator();
  }

  if ((c == 1) || (c == 2)) {
    addEventTypeMenu(&popup);
    popup.addSeparator();
  }
  addGoMenu(&popup);

  QAction* a = popup.exec(mapToGlobal(p + QPoint(0,header()->height())));
  if (a == activateFunctionAction)
      TraceItemView::activated(f);
  else if (a == activateLineAction)
      TraceItemView::activated(line);
}


void SourceView::selectedSlot(QTreeWidgetItem *i, QTreeWidgetItem *)
{
  if (!i) return;
  // programatically selected items are not signalled
  if (_inSelectionUpdate) return;

  TraceLineCall* lc = ((SourceItem*) i)->lineCall();
  TraceLineJump* lj = ((SourceItem*) i)->lineJump();

  if (!lc && !lj) {
      TraceLine* l = ((SourceItem*) i)->line();
      if (l) {
	  _selectedItem = l;
	  selected(l);
      }
      return;
  }

  TraceFunction* f = lc ? lc->call()->called() : 0;
  if (f) {
      _selectedItem = f;
      selected(f);
  }
  else {
    TraceLine* line = lj ? lj->lineTo() : 0;
    if (line) {
	_selectedItem = line;
	selected(line);
    }
  }
}

void SourceView::activatedSlot(QTreeWidgetItem* i, int)
{
  if (!i) return;

  TraceLineCall* lc = ((SourceItem*) i)->lineCall();
  TraceLineJump* lj = ((SourceItem*) i)->lineJump();

  if (!lc && !lj) {
      TraceLine* l = ((SourceItem*) i)->line();
      if (l) TraceItemView::activated(l);
      return;
  }

  TraceFunction* f = lc ? lc->call()->called() : 0;
  if (f) TraceItemView::activated(f);
  else {
    TraceLine* line = lj ? lj->lineTo() : 0;
    if (line) TraceItemView::activated(line);
  }
}

void SourceView::keyPressEvent(QKeyEvent* event)
{
    QTreeWidgetItem *item = currentItem();
    if (item && ((event->key() == Qt::Key_Return) ||
                 (event->key() == Qt::Key_Space)))
    {
        activatedSlot(item, 0);
    }
    QTreeView::keyPressEvent(event);
}

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

    switch(t) {
    case ProfileContext::Function:
    case ProfileContext::Instr:
    case ProfileContext::Line:
	return i;

    default:
	break;
    }

    return 0;
}

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

      if (!_selectedItem) {
	  clearSelection();
	  return;
      }

      TraceLine* sLine = 0;
      if (_selectedItem->type() == ProfileContext::Line)
          sLine = (TraceLine*) _selectedItem;
      if (_selectedItem->type() == ProfileContext::Instr)
	  sLine = ((TraceInstr*)_selectedItem)->line();
      if ((_selectedItem->type() != ProfileContext::Function) && (sLine == 0))
	  return;

      QList<QTreeWidgetItem*> items = selectedItems();
      SourceItem* si = (items.count() > 0) ? (SourceItem*)items[0] : 0;
      if (si) {
	  if (sLine && (si->line() == sLine)) return;
	  if (si->lineCall() &&
	      (si->lineCall()->call()->called() == _selectedItem)) return;
      }

      QTreeWidgetItem *item, *item2;
      for (int i=0; i<topLevelItemCount(); i++) {
          item = topLevelItem(i);
	  si = (SourceItem*)item;
	  if (sLine && (si->line() == sLine)) {
              scrollToItem(item);
              _inSelectionUpdate = true;
	      setCurrentItem(item);
              _inSelectionUpdate = false;
	      break;
	  }
	  bool foundCall = false;
	  for (int j=0; j<item->childCount(); j++) {
              item2 = item->child(j);
	      si = (SourceItem*)item2;
	      if (!si->lineCall()) continue;
	      if (si->lineCall()->call()->called() == _selectedItem) {
                  scrollToItem(item2);
                  _inSelectionUpdate = true;
		  setCurrentItem(item2);
                  _inSelectionUpdate = false;
		  foundCall = true;
		  break;
	      }
	  }
	  if (foundCall) break;
      }
      return;
  }

  if (changeType == groupTypeChanged) {
      // update group colors for call lines
      QTreeWidgetItem *item, *item2;
      for (int i=0; i<topLevelItemCount(); i++) {
          item = topLevelItem(i);
          for (int j=0; i<item->childCount(); i++) {
              item2 = item->child(j);
              ((SourceItem*)item2)->updateGroup();
          }
      }
      return;
  }

  // On eventTypeChanged, we can not just change the costs shown in
  // already existing items, as costs of 0 should make the line to not
  // be shown at all. So we do a full refresh.

  refresh();
}

void SourceView::refresh()
{
  int originalPosition = verticalScrollBar()->value();
  clear();
  setColumnWidth(0, 20);
  setColumnWidth(1, 50);
  setColumnWidth(2, _eventType2 ? 50:0);
  setColumnWidth(3, 0); // arrows, defaults to invisible
  if (_eventType)
      headerItem()->setText(1, _eventType->name());
  if (_eventType2)
      headerItem()->setText(2, _eventType2->name());

  _arrowLevels = 0;
  if (!_data || !_activeItem) {
      return;
  }

  ProfileContext::Type t = _activeItem->type();
  TraceFunction* f = 0;
  if (t == ProfileContext::Function) f = (TraceFunction*) _activeItem;
  if (t == ProfileContext::Instr) {
    f = ((TraceInstr*)_activeItem)->function();
    if (!_selectedItem)
	_selectedItem = ((TraceInstr*)_activeItem)->line();
  }
  if (t == ProfileContext::Line) {
    f = ((TraceLine*)_activeItem)->functionSource()->function();
    if (!_selectedItem) _selectedItem = _activeItem;
  }

  if (!f) return;

  TraceFunctionSource* mainSF = f->sourceFile();

  // skip first source if there is no debug info and there are more sources
  // (this is for a bug in GCC 2.95.x giving unknown source for prologs)
  if (mainSF &&
      (mainSF->firstLineno() == 0) &&
      (mainSF->lastLineno() == 0) &&
      (f->sourceFiles().count()>1) ) {
	  // skip
  }
  else
      fillSourceFile(mainSF, 0);

  int fileno = 0;
  foreach(TraceFunctionSource* sf, f->sourceFiles()) {
      fileno++;
      if (sf != mainSF)
          fillSourceFile(sf, fileno);
  }

  if (!_eventType2) {
#if QT_VERSION >= 0x050000
      header()->setSectionResizeMode(2, QHeaderView::Interactive);
#else
      header()->setResizeMode(2, QHeaderView::Interactive);
#endif
      setColumnWidth(2, 0);
  }
  // reset to the original position - this is useful when the view
  // is refreshed just because we change between relative/absolute
  // FIXME: this overrides scrolling to selected item
  verticalScrollBar()->setValue(originalPosition);
}


/* Helper for fillSourceList:
 * search recursive for a file, starting from a base dir
 * If found, returns true and <dir> is set to the file path.
 */
static bool searchFileRecursive(QString& dir, const QString& name)
{
  // we leave this in...
  qDebug("Checking %s/%s", qPrintable(dir), qPrintable(name));

  if (QFile::exists(dir + '/' + name)) return true;

  // check in subdirectories
  QDir d(dir);
  d.setFilter( QDir::Dirs | QDir::NoSymLinks );
  d.setSorting( QDir::Unsorted );
  QStringList subdirs = d.entryList();
  QStringList::const_iterator it =subdirs.constBegin();
  for(; it != subdirs.constEnd(); ++it ) {
    if (*it == "." || *it == ".." || *it == "CVS") continue;

    dir = d.filePath(*it);
    if (searchFileRecursive(dir, name)) return true;
  }
  return false;
}

/* Search for a source file in different places.
 * If found, returns true and <dir> is set to the file path.
 */
bool SourceView::searchFile(QString& dir,
			    TraceFunctionSource* sf)
{
    QString name = sf->file()->shortName();

    if (QDir::isAbsolutePath(dir)) {
	if (QFile::exists(dir + '/' + name)) return true;
    }
    else {
	/* Directory is relative. Check
	 * - relative to cwd
	 * - relative to path of data file
	 */
	QString base = QDir::currentPath() + '/' + dir;
	if (QFile::exists(base + '/' + name)) {
	    dir = base;
	    return true;
	}

	TracePart* firstPart = _data->parts().first();
	if (firstPart) {
	    QFileInfo partFile(firstPart->name());
	    if (QFileInfo(partFile.absolutePath(), name).exists()) {
		dir = partFile.absolutePath();
		return true;
	    }
	}
    }

    QStringList list = GlobalConfig::sourceDirs(_data,
						sf->function()->object());
    QStringList::const_iterator it;
    for ( it = list.constBegin(); it != list.constEnd(); ++it ) {
        dir = *it;
        if (searchFileRecursive(dir, name)) return true;
    }

    return false;
}


void SourceView::updateJumpArray(uint lineno, SourceItem* si,
				 bool ignoreFrom, bool ignoreTo)
{
    uint lowLineno, highLineno;
    int iEnd = -1, iStart = -1;

    if (0) qDebug("updateJumpArray(line %d, jump to %s)",
		  lineno,
		  si->lineJump()
		  ? qPrintable(si->lineJump()->lineTo()->name()) : "?" );

    while(_lowListIter != _lowList.end()) {
        TraceLineJump* lj= *_lowListIter;
	lowLineno = lj->lineFrom()->lineno();
	if (lj->lineTo()->lineno() < lowLineno)
	    lowLineno = lj->lineTo()->lineno();

	if (lowLineno > lineno) break;

	if (ignoreFrom && (lowLineno < lj->lineTo()->lineno())) break;
	if (ignoreTo && (lowLineno < lj->lineFrom()->lineno())) break;

	if (si->lineJump() && (lj != si->lineJump())) break;

	int asize = (int)_jump.size();
#if 0
	for(iStart=0;iStart<asize;iStart++)
	    if (_jump[iStart] &&
		(_jump[iStart]->lineTo() == lj->lineTo())) break;
#else
	iStart = asize;
#endif

	if (iStart == asize) {
            for(iStart=0; iStart<asize; ++iStart)
		if (_jump[iStart] == 0) break;

	    if (iStart== asize) {
		asize++;
		_jump.resize(asize);
		if (asize > _arrowLevels) _arrowLevels = asize;
	    }

	    if (0) qDebug(" start %d (%s to %s)",
			  iStart,
			  qPrintable(lj->lineFrom()->name()),
			  qPrintable(lj->lineTo()->name()));

	    _jump[iStart] = lj;
	}
        _lowListIter++;
    }

    si->setJumpArray(_jump);

    while(_highListIter != _highList.end()) {
        TraceLineJump* lj= *_highListIter;
	highLineno = lj->lineFrom()->lineno();
	if (lj->lineTo()->lineno() > highLineno) {
	    highLineno = lj->lineTo()->lineno();
	    if (ignoreTo) break;
	}
	else if (ignoreFrom) break;

	if (highLineno > lineno) break;

        for(iEnd=0; iEnd< (int)_jump.size(); ++iEnd)
	    if (_jump[iEnd] == lj) break;
	if (iEnd == (int)_jump.size()) {
	    qDebug("LineView: no jump start for end at %x ?", highLineno);
	    iEnd = -1;
	}

	if (0 && (iEnd>=0))
	    qDebug(" end %d (%s to %s)",
		   iEnd,
		   qPrintable(_jump[iEnd]->lineFrom()->name()),
		   qPrintable(_jump[iEnd]->lineTo()->name()));

	if (0 && lj) qDebug("next end: %s to %s",
			    qPrintable(lj->lineFrom()->name()),
			    qPrintable(lj->lineTo()->name()));

        _highListIter++;

	if (highLineno > lineno)
	    break;
	else {
	    if (iEnd>=0) _jump[iEnd] = 0;
	    iEnd = -1;
	}
    }
    if (iEnd>=0) _jump[iEnd] = 0;
}


// compare functions for jump arrow drawing

void getJumpLines(const TraceLineJump* jump, uint& low, uint& high)
{
    low  = jump->lineFrom()->lineno();
    high = jump->lineTo()->lineno();

    if (low > high) {
        uint t = low;
        low = high;
        high = t;
    }
}

// sort jumps according to lower line number
bool lineJumpLowLessThan(const TraceLineJump* jump1,
                          const TraceLineJump* jump2)
{
    uint line1Low, line1High, line2Low, line2High;

    getJumpLines(jump1, line1Low, line1High);
    getJumpLines(jump2, line2Low, line2High);

    if (line1Low != line2Low) return (line1Low < line2Low);
    // jump ends come before jump starts
    if (line1Low == jump1->lineTo()->lineno()) return true;
    if (line2Low == jump2->lineTo()->lineno()) return false;
    return (line1High < line2High);
}

// sort jumps according to higher line number
bool lineJumpHighLessThan(const TraceLineJump* jump1,
                           const TraceLineJump* jump2)
{
    uint line1Low, line1High, line2Low, line2High;

    getJumpLines(jump1, line1Low, line1High);
    getJumpLines(jump2, line2Low, line2High);

    if (line1High != line2High) return (line1High < line2High);
    // jump ends come before jump starts
    if (line1High == jump1->lineTo()->lineno()) return true;
    if (line2High == jump2->lineTo()->lineno()) return false;
    return (line1Low < line2Low);
}

/* If sourceList is empty we set the source file name into the header,
 * else this code is of a inlined function, and we add "inlined from..."
 */
void SourceView::fillSourceFile(TraceFunctionSource* sf, int fileno)
{
  if (!sf) return;

  if (0) qDebug("Selected Item %s",
                _selectedItem ? qPrintable(_selectedItem->name()) : "(none)");

  TraceLineMap::Iterator lineIt, lineItEnd;
  int nextCostLineno = 0, lastCostLineno = 0;

  bool validSourceFile = (!sf->file()->name().isEmpty());

  TraceLine* sLine = 0;
  if (_selectedItem) {
    if (_selectedItem->type() == ProfileContext::Line)
      sLine = (TraceLine*) _selectedItem;
    if (_selectedItem->type() == ProfileContext::Instr)
      sLine = ((TraceInstr*)_selectedItem)->line();
  }

  if (validSourceFile) {
      TraceLineMap* lineMap = sf->lineMap();
      if (lineMap) {
	  lineIt    = lineMap->begin();
	  lineItEnd = lineMap->end();
	  // get first line with cost of selected type
	  while(lineIt != lineItEnd) {
	    if (&(*lineIt) == sLine) break;
	    if ((*lineIt).hasCost(_eventType)) break;
	    if (_eventType2 && (*lineIt).hasCost(_eventType2)) break;
	    ++lineIt;
	  }

	  nextCostLineno     = (lineIt == lineItEnd) ? 0 : (*lineIt).lineno();
	  if (nextCostLineno<0) {
	    qDebug() << "SourceView::fillSourceFile: Negative line number "
			<< nextCostLineno;
	    qDebug() << "  Function '" << sf->function()->name() << "'";
	    qDebug() << "  File '" << sf->file()->name() << "'";
	    nextCostLineno = 0;
	  }

      }

      if (nextCostLineno == 0) {
	  new SourceItem(this, this, fileno, 1, false,
			 tr("There is no cost of current selected type associated"));
	  new SourceItem(this, this, fileno, 2, false,
			 tr("with any source line of this function in file"));
	  new SourceItem(this, this, fileno, 3, false,
             QString("    '%1'").arg(sf->file()->prettyName()));
	  new SourceItem(this, this, fileno, 4, false,
			 tr("Thus, no annotated source can be shown."));
	  return;
      }
  }

  QString filename = sf->file()->shortName();
  QString dir = sf->file()->directory();
  if (!dir.isEmpty())
    filename = dir + '/' + filename;

  if (nextCostLineno>0) {
      // we have debug info... search for source file
      if (searchFile(dir, sf)) {
	  filename = dir + '/' + sf->file()->shortName();
	  // no need to search again
	  sf->file()->setDirectory(dir);
      }
      else
	  nextCostLineno = 0;
  }

  // do it here, because the source directory could have been set before
  if (topLevelItemCount()==0) {
      if (validSourceFile && (nextCostLineno != 0))
	  new SourceItem(this, this, fileno, 0, true,
			 tr("--- From '%1' ---").arg(filename));
  }
  else {
    new SourceItem(this, this, fileno, 0, true,
                   validSourceFile ?
                   tr("--- Inlined from '%1' ---").arg(filename) :
                   tr("--- Inlined from unknown source ---"));
  }

  if (nextCostLineno == 0) {
    new SourceItem(this, this, fileno, 1, false,
                   tr("There is no source available for the following function:"));
    new SourceItem(this, this, fileno, 2, false,
                   QString("    '%1'").arg(sf->function()->prettyName()));
    if (sf->file()->name().isEmpty()) {
      new SourceItem(this, this, fileno, 3, false,
                     tr("This is because no debug information is present."));
      new SourceItem(this, this, fileno, 4, false,
                     tr("Recompile source and redo the profile run."));
      if (sf->function()->object()) {
	new SourceItem(this, this, fileno, 5, false,
                       tr("The function is located in this ELF object:"));
	new SourceItem(this, this, fileno, 6, false,
                       QString("    '%1'")
                       .arg(sf->function()->object()->prettyName()));
      }
    }
    else {
      new SourceItem(this, this, fileno, 3, false,
                     tr("This is because its source file cannot be found:"));
      new SourceItem(this, this, fileno, 4, false,
                     QString("    '%1'").arg(sf->file()->name()));
      new SourceItem(this, this, fileno, 5, false,
                     tr("Add the folder of this file to the source folder list."));
      new SourceItem(this, this, fileno, 6, false,
                     tr("The list can be found in the configuration dialog."));
    }
    return;
  }

  // initialisation for arrow drawing
  // create sorted list of jumps (for jump arrows)
  TraceLineMap::Iterator it = lineIt, nextIt;
  _lowList.clear();
  _highList.clear();
  while(1) {

      nextIt = it;
      ++nextIt;
      while(nextIt != lineItEnd) {
	if (&(*nextIt) == sLine) break;
	if ((*nextIt).hasCost(_eventType)) break;
	if (_eventType2 && (*nextIt).hasCost(_eventType2)) break;
	++nextIt;
      }

      TraceLineJumpList jlist = (*it).lineJumps();
      foreach(TraceLineJump* lj, jlist) {
	  if (lj->executedCount()==0) continue;
	  // skip jumps to next source line with cost
	  //if (lj->lineTo() == &(*nextIt)) continue;

	  _lowList.append(lj);
	  _highList.append(lj);
      }
      it = nextIt;
      if (it == lineItEnd) break;
  }
  qSort(_lowList.begin(), _lowList.end(), lineJumpLowLessThan);
  qSort(_highList.begin(), _highList.end(), lineJumpHighLessThan);
  _lowListIter = _lowList.begin(); // iterators to list start
  _highListIter = _highList.begin();
  _jump.resize(0);

  char buf[160];
  bool inside = false, skipLineWritten = true;
  int readBytes;
  int fileLineno = 0;
  SubCost most = 0;

  QList<QTreeWidgetItem*> items;
  TraceLine* currLine;
  SourceItem *si, *si2, *item = 0, *first = 0, *selected = 0;
  QFile file(filename);
  bool fileEndReached = false;
  if (!file.open(QIODevice::ReadOnly)) return;
  while (1) {
    readBytes=file.readLine(buf, sizeof( buf ));
    if (readBytes<=0) {
      // for nice empty 4 lines after function with EOF
      buf[0] = 0;
      if (readBytes<0) fileEndReached = true;
    }

    if ((readBytes >0) && (buf[readBytes-1] != '\n')) {
        /* Something was read but not ending in newline. I.e.
         * - buffer was not big enough: discard rest of line, add "..."
         * - this is last line of file, not ending in newline
         * NB: checking for '\n' is enough for all systems.
         */
        int r;
        char buf2[32];
        bool somethingRead = false;
        while(1) {
            r = file.readLine(buf2, sizeof(buf2));
            if ((r<=0) || (buf2[r-1] == '\n')) break;
            somethingRead = true;
        }
        if (somethingRead) {
            // add dots as sign that we truncated the line
            Q_ASSERT(readBytes>3);
            buf[readBytes-1] = buf[readBytes-2] = buf[readBytes-3] = '.';
        }
    }
    else if ((readBytes>0) && (buf[readBytes-1] == '\n'))
      buf[readBytes-1] = 0;


    // keep fileLineno inside [lastCostLineno;nextCostLineno]
    fileLineno++;
    if (fileLineno == nextCostLineno) {
	currLine = &(*lineIt);

	// get next line with cost of selected type
	++lineIt;
	while(lineIt != lineItEnd) {
	  if (&(*lineIt) == sLine) break;
	  if ((*lineIt).hasCost(_eventType)) break;
	  if (_eventType2 && (*lineIt).hasCost(_eventType2)) break;
	  ++lineIt;
	}

	lastCostLineno = nextCostLineno;
	nextCostLineno = (lineIt == lineItEnd) ? 0 : (*lineIt).lineno();
    }
    else
	currLine = 0;

    // update inside
    if (!inside) {
	if (currLine) inside = true;
    }
    else {
	if ( (fileLineno > lastCostLineno) &&
	     ((nextCostLineno == 0) ||
	      (fileLineno < nextCostLineno - GlobalConfig::noCostInside()) ))
	    inside = false;
    }

    int context = GlobalConfig::context();

    if ( ((lastCostLineno==0) || (fileLineno > lastCostLineno + context)) &&
	 ((nextCostLineno==0) || (fileLineno < nextCostLineno - context))) {
	if ((lineIt == lineItEnd) || fileEndReached) break;

	if (!skipLineWritten) {
	    skipLineWritten = true;
	    // a "skipping" line: print "..." instead of a line number
	    strcpy(buf,"...");
	}
	else
	    continue;
    }
    else
	skipLineWritten = false;

    QString s = QString(buf);
    if(s.size() > 0 && s.at(s.length()-1) == '\r')
        s = s.left(s.length()-1);
    si = new SourceItem(this, 0,
                        fileno, fileLineno, inside, s,
                        currLine);
    items.append(si);

    if (!currLine) continue;

    if (!selected && (currLine == sLine)) selected = si;
    if (!first) first = si;

    if (currLine->subCost(_eventType) > most) {
      item = si;
      most = currLine->subCost(_eventType);
    }

    si->setExpanded(true);
    foreach(TraceLineCall* lc,  currLine->lineCalls()) {
	if ((lc->subCost(_eventType)==0) &&
	    (lc->subCost(_eventType2)==0)) continue;

      if (lc->subCost(_eventType) > most) {
        item = si;
        most = lc->subCost(_eventType);
      }

      si2 = new SourceItem(this, si, fileno, fileLineno, currLine, lc);

      if (!selected && (lc->call()->called() == _selectedItem))
	  selected = si2;
    }

    foreach(TraceLineJump* lj, currLine->lineJumps()) {
	if (lj->executedCount()==0) continue;

	new SourceItem(this, si, fileno, fileLineno, currLine, lj);
    }
  }

  file.close();

  // Resize column 0 (line number) and 1/2 (cost) to contents
#if QT_VERSION >= 0x050000
  header()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
  header()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
  header()->setSectionResizeMode(2, QHeaderView::ResizeToContents);
#else
  header()->setResizeMode(0, QHeaderView::ResizeToContents);
  header()->setResizeMode(1, QHeaderView::ResizeToContents);
  header()->setResizeMode(2, QHeaderView::ResizeToContents);
#endif

  setSortingEnabled(false);
  addTopLevelItems(items);
  this->expandAll();
  setSortingEnabled(true);
  // always reset to line number sort
  sortByColumn(0, Qt::AscendingOrder);
  header()->setSortIndicatorShown(false);

  // Reallow interactive column size change after resizing to content
#if QT_VERSION >= 0x050000
  header()->setSectionResizeMode(0, QHeaderView::Interactive);
  header()->setSectionResizeMode(1, QHeaderView::Interactive);
  header()->setSectionResizeMode(2, QHeaderView::Interactive);
#else
  header()->setResizeMode(0, QHeaderView::Interactive);
  header()->setResizeMode(1, QHeaderView::Interactive);
  header()->setResizeMode(2, QHeaderView::Interactive);
#endif

  if (selected) item = selected;
  if (item) first = item;
  if (first) {
      scrollToItem(first);
      _inSelectionUpdate = true;
      setCurrentItem(first);
      _inSelectionUpdate = false;
  }

  // for arrows: go down the list according to list sorting
  QTreeWidgetItem *item1, *item2;
  for (int i=0; i<topLevelItemCount(); i++) {
      item1 = topLevelItem(i);
      si = (SourceItem*)item1;
      updateJumpArray(si->lineno(), si, true, false);

      for (int j=0; j<item1->childCount(); j++) {
          item2 = item1->child(j);
          si2 = (SourceItem*)item2;
          if (si2->lineJump())
              updateJumpArray(si->lineno(), si2, false, true);
          else
              si2->setJumpArray(_jump);
      }
  }

  if (arrowLevels())
      //fix this: setColumnWidth(3, 10 + 6*arrowLevels() + itemMargin() * 2);
      setColumnWidth(3, 10 + 6*arrowLevels() + 2);
  else
      setColumnWidth(3, 0);
}


void SourceView::headerClicked(int col)
{
    if (col == 0) {
        sortByColumn(col, Qt::AscendingOrder);
    }
    //All others but Source Text column Descending
    else if (col !=4) {
        sortByColumn(col, Qt::DescendingOrder);
    }
}

#include "sourceview.moc"