]> git.cworth.org Git - apitrace/blob - gui/mainwindow.cpp
Implement grouping of calls.
[apitrace] / gui / mainwindow.cpp
1 #include "mainwindow.h"
2
3 #include "apitrace.h"
4 #include "apitracecall.h"
5 #include "apicalldelegate.h"
6 #include "apitracemodel.h"
7 #include "apitracefilter.h"
8 #include "argumentseditor.h"
9 #include "imageviewer.h"
10 #include "jumpwidget.h"
11 #include "profiledialog.h"
12 #include "retracer.h"
13 #include "searchwidget.h"
14 #include "settingsdialog.h"
15 #include "shaderssourcewidget.h"
16 #include "tracedialog.h"
17 #include "traceprocess.h"
18 #include "trimprocess.h"
19 #include "thumbnail.h"
20 #include "ui_retracerdialog.h"
21 #include "ui_profilereplaydialog.h"
22 #include "vertexdatainterpreter.h"
23 #include "trace_profiler.hpp"
24
25 #include <QAction>
26 #include <QApplication>
27 #include <QDebug>
28 #include <QDesktopServices>
29 #include <QDesktopWidget>
30 #include <QDir>
31 #include <QFileDialog>
32 #include <QLineEdit>
33 #include <QMessageBox>
34 #include <QProgressBar>
35 #include <QToolBar>
36 #include <QUrl>
37 #include <QVBoxLayout>
38 #include <QWebPage>
39 #include <QWebView>
40
41
42 MainWindow::MainWindow()
43     : QMainWindow(),
44       m_api(trace::API_GL),
45       m_initalCallNum(-1),
46       m_selectedEvent(0),
47       m_stateEvent(0),
48       m_nonDefaultsLookupEvent(0)
49 {
50     m_ui.setupUi(this);
51     updateActionsState(false);
52     initObjects();
53     initConnections();
54 }
55
56 MainWindow::~MainWindow()
57 {
58     delete m_trace;
59     m_trace = 0;
60
61     delete m_proxyModel;
62     delete m_model;
63 }
64
65 void MainWindow::createTrace()
66 {
67     if (!m_traceProcess->canTrace()) {
68         QMessageBox::warning(
69             this,
70             tr("Unsupported"),
71             tr("Current configuration doesn't support tracing."));
72         return;
73     }
74
75     TraceDialog dialog;
76     if (dialog.exec() == QDialog::Accepted) {
77         qDebug()<< "App : " <<dialog.applicationPath();
78         qDebug()<< "  Arguments: "<<dialog.arguments();
79         m_traceProcess->setApi(dialog.api());
80         m_traceProcess->setExecutablePath(dialog.applicationPath());
81         m_traceProcess->setArguments(dialog.arguments());
82         m_traceProcess->start();
83     }
84 }
85
86 void MainWindow::openTrace()
87 {
88     QString fileName =
89             QFileDialog::getOpenFileName(
90                 this,
91                 tr("Open Trace"),
92                 QDir::homePath(),
93                 tr("Trace Files (*.trace)"));
94
95     if (!fileName.isEmpty() && QFile::exists(fileName)) {
96         newTraceFile(fileName);
97     }
98 }
99
100 void MainWindow::loadTrace(const QString &fileName, int callNum)
101 {
102     if (!QFile::exists(fileName)) {
103         QMessageBox::warning(this, tr("File Missing"),
104                              tr("File '%1' doesn't exist.").arg(fileName));
105         return;
106     }
107
108     m_initalCallNum = callNum;
109     newTraceFile(fileName);
110 }
111
112 void MainWindow::setRemoteTarget(const QString &host)
113 {
114     m_retracer->setRemoteTarget(host);
115 }
116
117 void MainWindow::callItemSelected(const QModelIndex &index)
118 {
119     ApiTraceEvent *event =
120         index.data(ApiTraceModel::EventRole).value<ApiTraceEvent*>();
121
122     if (event && event->type() == ApiTraceEvent::Call) {
123         ApiTraceCall *call = static_cast<ApiTraceCall*>(event);
124         m_ui.detailsDock->setWindowTitle(
125             tr("Details View. Frame %1, Call %2")
126             .arg(call->parentFrame() ? call->parentFrame()->number : 0)
127             .arg(call->index()));
128         m_ui.detailsWebView->setHtml(call->toHtml());
129         m_ui.detailsDock->show();
130         if (call->hasBinaryData()) {
131             QByteArray data =
132                 call->arguments()[call->binaryDataIndex()].toByteArray();
133             m_vdataInterpreter->setData(data);
134
135             QVector<QVariant> args = call->arguments();
136             for (int i = 0; i < call->argNames().count(); ++i) {
137                 QString name = call->argNames()[i];
138                 if (name == QLatin1String("stride")) {
139                     int stride = args[i].toInt();
140                     m_ui.vertexStrideSB->setValue(stride);
141                 } else if (name == QLatin1String("size")) {
142                     int components = args[i].toInt();
143                     m_ui.vertexComponentsSB->setValue(components);
144                 } else if (name == QLatin1String("type")) {
145                     QString val = args[i].toString();
146                     int textIndex = m_ui.vertexTypeCB->findText(val);
147                     if (textIndex >= 0) {
148                         m_ui.vertexTypeCB->setCurrentIndex(textIndex);
149                     }
150                 }
151             }
152         }
153         m_ui.backtraceBrowser->setText(call->backtrace());
154         m_ui.backtraceDock->setVisible(!call->backtrace().isNull());
155         m_ui.vertexDataDock->setVisible(call->hasBinaryData());
156         m_selectedEvent = call;
157     } else {
158         if (event && event->type() == ApiTraceEvent::Frame) {
159             m_selectedEvent = static_cast<ApiTraceFrame*>(event);
160         } else {
161             m_selectedEvent = 0;
162         }
163         m_ui.detailsDock->hide();
164         m_ui.backtraceDock->hide();
165         m_ui.vertexDataDock->hide();
166     }
167     if (m_selectedEvent && m_selectedEvent->hasState()) {
168         fillStateForFrame();
169     } else {
170         m_ui.stateDock->hide();
171     }
172 }
173
174 void MainWindow::callItemActivated(const QModelIndex &index) {
175     lookupState();
176 }
177
178 void MainWindow::replayStart()
179 {
180     if (m_trace->isSaving()) {
181         QMessageBox::warning(
182             this,
183             tr("Trace Saving"),
184             tr("QApiTrace is currently saving the edited trace file. "
185                "Please wait until it finishes and try again."));
186         return;
187     }
188
189     QDialog dlg;
190     Ui_RetracerDialog dlgUi;
191     dlgUi.setupUi(&dlg);
192
193     dlgUi.doubleBufferingCB->setChecked(
194         m_retracer->isDoubleBuffered());
195
196     dlgUi.errorCheckCB->setChecked(
197         !m_retracer->isBenchmarking());
198
199     dlgUi.singlethreadCB->setChecked(
200         m_retracer->isSinglethread());
201
202     if (dlg.exec() == QDialog::Accepted) {
203         m_retracer->setDoubleBuffered(
204             dlgUi.doubleBufferingCB->isChecked());
205
206         m_retracer->setBenchmarking(
207             !dlgUi.errorCheckCB->isChecked());
208
209         m_retracer->setSinglethread(
210             dlgUi.singlethreadCB->isChecked());
211
212         m_retracer->setProfiling(false, false, false);
213
214         replayTrace(false, false);
215     }
216 }
217
218 void MainWindow::replayProfile()
219 {
220     if (m_trace->isSaving()) {
221         QMessageBox::warning(
222             this,
223             tr("Trace Saving"),
224             tr("QApiTrace is currently saving the edited trace file. "
225                "Please wait until it finishes and try again."));
226         return;
227     }
228
229     QDialog dlg;
230     Ui_ProfileReplayDialog dlgUi;
231     dlgUi.setupUi(&dlg);
232
233     if (dlg.exec() == QDialog::Accepted) {
234         m_retracer->setProfiling(
235             dlgUi.gpuTimesCB->isChecked(),
236             dlgUi.cpuTimesCB->isChecked(),
237             dlgUi.pixelsDrawnCB->isChecked());
238
239         replayTrace(false, false);
240     }
241 }
242
243 void MainWindow::replayStop()
244 {
245     m_retracer->quit();
246     updateActionsState(true, true);
247 }
248
249 void MainWindow::newTraceFile(const QString &fileName)
250 {
251     qDebug()<< "Loading  : " <<fileName;
252
253     m_progressBar->setValue(0);
254     m_trace->setFileName(fileName);
255
256     if (fileName.isEmpty()) {
257         updateActionsState(false);
258         setWindowTitle(tr("QApiTrace"));
259     } else {
260         updateActionsState(true);
261         QFileInfo info(fileName);
262         setWindowTitle(
263             tr("QApiTrace - %1").arg(info.fileName()));
264     }
265 }
266
267 void MainWindow::replayFinished(const QString &message)
268 {
269     updateActionsState(true);
270     m_progressBar->hide();
271     statusBar()->showMessage(message, 2000);
272     m_stateEvent = 0;
273     m_ui.actionShowErrorsDock->setEnabled(m_trace->hasErrors());
274     m_ui.errorsDock->setVisible(m_trace->hasErrors());
275     if (!m_trace->hasErrors()) {
276         m_ui.errorsTreeWidget->clear();
277     }
278 }
279
280 void MainWindow::replayError(const QString &message)
281 {
282     updateActionsState(true);
283     m_stateEvent = 0;
284     m_nonDefaultsLookupEvent = 0;
285
286     m_progressBar->hide();
287     statusBar()->showMessage(
288         tr("Replaying unsuccessful."), 2000);
289     QMessageBox::warning(
290         this, tr("Replay Failed"), message);
291 }
292
293 void MainWindow::startedLoadingTrace()
294 {
295     Q_ASSERT(m_trace);
296     m_progressBar->show();
297     QFileInfo info(m_trace->fileName());
298     statusBar()->showMessage(
299         tr("Loading %1...").arg(info.fileName()));
300 }
301
302 void MainWindow::finishedLoadingTrace()
303 {
304     m_progressBar->hide();
305     if (!m_trace) {
306         return;
307     }
308     m_api = m_trace->api();
309     QFileInfo info(m_trace->fileName());
310     statusBar()->showMessage(
311         tr("Loaded %1").arg(info.fileName()), 3000);
312     if (m_initalCallNum >= 0) {
313         m_trace->findCallIndex(m_initalCallNum);
314         m_initalCallNum = -1;
315     }
316 }
317
318 void MainWindow::replayTrace(bool dumpState, bool dumpThumbnails)
319 {
320     if (m_trace->fileName().isEmpty()) {
321         return;
322     }
323
324     m_retracer->setFileName(m_trace->fileName());
325     m_retracer->setAPI(m_api);
326     m_retracer->setCaptureState(dumpState);
327     m_retracer->setCaptureThumbnails(dumpThumbnails);
328     if (m_retracer->captureState() && m_selectedEvent) {
329         int index = 0;
330         if (m_selectedEvent->type() == ApiTraceEvent::Call) {
331             index = static_cast<ApiTraceCall*>(m_selectedEvent)->index();
332         } else if (m_selectedEvent->type() == ApiTraceEvent::Frame) {
333             ApiTraceFrame *frame =
334                 static_cast<ApiTraceFrame*>(m_selectedEvent);
335             if (frame->isEmpty()) {
336                 //XXX i guess we could still get the current state
337                 qDebug()<<"tried to get a state for an empty frame";
338                 return;
339             }
340             index = frame->lastCallIndex();
341         } else {
342             qDebug()<<"Unknown event type";
343             return;
344         }
345         m_retracer->setCaptureAtCallNumber(index);
346     }
347     m_retracer->start();
348
349     m_ui.actionStop->setEnabled(true);
350     m_progressBar->show();
351     if (dumpState || dumpThumbnails) {
352         if (dumpState && dumpThumbnails) {
353             statusBar()->showMessage(
354                 tr("Looking up the state and capturing thumbnails..."));
355         } else if (dumpState) {
356             statusBar()->showMessage(
357                 tr("Looking up the state..."));
358         } else if (dumpThumbnails) {
359             statusBar()->showMessage(
360                 tr("Capturing thumbnails..."));
361         }
362     } else if (m_retracer->isProfiling()) {
363         statusBar()->showMessage(
364                     tr("Profiling draw calls in trace file..."));
365     } else {
366         statusBar()->showMessage(
367             tr("Replaying the trace file..."));
368     }
369 }
370
371 void MainWindow::trimEvent()
372 {
373     int trimIndex = 0;
374
375     Q_ASSERT(m_trimEvent->type() == ApiTraceEvent::Call ||
376              m_trimEvent->type() == ApiTraceEvent::Frame);
377
378     if (m_trimEvent->type() == ApiTraceEvent::Call) {
379         ApiTraceCall *call = static_cast<ApiTraceCall*>(m_trimEvent);
380         trimIndex = call->index();
381     } else if (m_trimEvent->type() == ApiTraceEvent::Frame) {
382         ApiTraceFrame *frame = static_cast<ApiTraceFrame*>(m_trimEvent);
383         const QList<ApiTraceFrame*> frames = m_trace->frames();
384         trimIndex = frame->lastCallIndex();
385     }
386
387     m_trimProcess->setTracePath(m_trace->fileName());
388     m_trimProcess->setTrimIndex(trimIndex);
389
390     m_trimProcess->start();
391 }
392
393 void MainWindow::lookupState()
394 {
395     if (!m_selectedEvent) {
396         QMessageBox::warning(
397             this, tr("Unknown Event"),
398             tr("To inspect the state select an event in the event list."));
399         return;
400     }
401     if (m_trace->isSaving()) {
402         QMessageBox::warning(
403             this,
404             tr("Trace Saving"),
405             tr("QApiTrace is currently saving the edited trace file. "
406                "Please wait until it finishes and try again."));
407         return;
408     }
409     m_stateEvent = m_selectedEvent;
410     replayTrace(true, false);
411 }
412
413 void MainWindow::showThumbnails()
414 {
415     replayTrace(false, true);
416 }
417
418 void MainWindow::trim()
419 {
420     if (!m_selectedEvent) {
421         QMessageBox::warning(
422             this, tr("Unknown Event"),
423             tr("To trim select a frame or an event in the event list."));
424         return;
425     }
426     m_trimEvent = m_selectedEvent;
427     trimEvent();
428 }
429
430 static void
431 variantToString(const QVariant &var, QString &str)
432 {
433     if (var.type() == QVariant::List) {
434         QVector<QVariant> lst = var.toList().toVector();
435         str += QLatin1String("[");
436         for (int i = 0; i < lst.count(); ++i) {
437             QVariant val = lst[i];
438             variantToString(val, str);
439             if (i < lst.count() - 1)
440                 str += QLatin1String(", ");
441         }
442         str += QLatin1String("]");
443     } else if (var.type() == QVariant::Map) {
444         Q_ASSERT(!"unsupported state type");
445     } else if (var.type() == QVariant::Hash) {
446         Q_ASSERT(!"unsupported state type");
447     } else {
448         str += var.toString();
449     }
450 }
451
452 static QTreeWidgetItem *
453 variantToItem(const QString &key, const QVariant &var,
454               const QVariant &defaultVar);
455
456 static void
457 variantMapToItems(const QVariantMap &map, const QVariantMap &defaultMap,
458                   QList<QTreeWidgetItem *> &items)
459 {
460     QVariantMap::const_iterator itr;
461     for (itr = map.constBegin(); itr != map.constEnd(); ++itr) {
462         QString key = itr.key();
463         QVariant var = itr.value();
464         QVariant defaultVar = defaultMap[key];
465
466         QTreeWidgetItem *item = variantToItem(key, var, defaultVar);
467         if (item) {
468             items.append(item);
469         }
470     }
471 }
472
473 static void
474 variantListToItems(const QVector<QVariant> &lst,
475                    const QVector<QVariant> &defaultLst,
476                    QList<QTreeWidgetItem *> &items)
477 {
478     for (int i = 0; i < lst.count(); ++i) {
479         QString key = QString::number(i);
480         QVariant var = lst[i];
481         QVariant defaultVar;
482         
483         if (i < defaultLst.count()) {
484             defaultVar = defaultLst[i];
485         }
486
487         QTreeWidgetItem *item = variantToItem(key, var, defaultVar);
488         if (item) {
489             items.append(item);
490         }
491     }
492 }
493
494 static bool
495 isVariantDeep(const QVariant &var)
496 {
497     if (var.type() == QVariant::List) {
498         QVector<QVariant> lst = var.toList().toVector();
499         for (int i = 0; i < lst.count(); ++i) {
500             if (isVariantDeep(lst[i])) {
501                 return true;
502             }
503         }
504         return false;
505     } else if (var.type() == QVariant::Map) {
506         return true;
507     } else if (var.type() == QVariant::Hash) {
508         return true;
509     } else {
510         return false;
511     }
512 }
513
514 static QTreeWidgetItem *
515 variantToItem(const QString &key, const QVariant &var,
516               const QVariant &defaultVar)
517 {
518     if (var == defaultVar) {
519         return NULL;
520     }
521
522     QString val;
523
524     bool deep = isVariantDeep(var);
525     if (!deep) {
526         variantToString(var, val);
527     }
528
529     //qDebug()<<"key = "<<key;
530     //qDebug()<<"val = "<<val;
531     QStringList lst;
532     lst += key;
533     lst += val;
534
535     QTreeWidgetItem *item = new QTreeWidgetItem((QTreeWidgetItem *)0, lst);
536
537     if (deep) {
538         QList<QTreeWidgetItem *> children;
539         if (var.type() == QVariant::Map) {
540             QVariantMap map = var.toMap();
541             QVariantMap defaultMap = defaultVar.toMap();
542             variantMapToItems(map, defaultMap, children);
543         }
544         if (var.type() == QVariant::List) {
545             QVector<QVariant> lst = var.toList().toVector();
546             QVector<QVariant> defaultLst = defaultVar.toList().toVector();
547             variantListToItems(lst, defaultLst, children);
548         }
549         item->addChildren(children);
550     }
551
552     return item;
553 }
554
555 static void addSurfaceItem(const ApiSurface &surface,
556                            const QString &label,
557                            QTreeWidgetItem *parent,
558                            QTreeWidget *tree)
559 {
560     QIcon icon(QPixmap::fromImage(surface.thumb()));
561     QTreeWidgetItem *item = new QTreeWidgetItem(parent);
562     item->setIcon(0, icon);
563
564     int width = surface.size().width();
565     int height = surface.size().height();
566     QString descr =
567         QString::fromLatin1("%1, %2, %3 x %4")
568         .arg(label)
569         .arg(surface.formatName())
570         .arg(width)
571         .arg(height);
572
573     //item->setText(1, descr);
574     QLabel *l = new QLabel(descr, tree);
575     l->setWordWrap(true);
576     tree->setItemWidget(item, 1, l);
577
578     item->setData(0, Qt::UserRole, surface.base64Data());
579 }
580
581 void MainWindow::fillStateForFrame()
582 {
583     if (!m_selectedEvent || !m_selectedEvent->hasState()) {
584         return;
585     }
586
587     if (m_nonDefaultsLookupEvent) {
588         m_ui.nonDefaultsCB->blockSignals(true);
589         m_ui.nonDefaultsCB->setChecked(true);
590         m_ui.nonDefaultsCB->blockSignals(false);
591     }
592
593     bool nonDefaults = m_ui.nonDefaultsCB->isChecked();
594     QVariantMap defaultParams;
595     if (nonDefaults) {
596         ApiTraceState defaultState = m_trace->defaultState();
597         defaultParams = defaultState.parameters();
598     }
599
600     const ApiTraceState &state = *m_selectedEvent->state();
601     m_ui.stateTreeWidget->clear();
602     QList<QTreeWidgetItem *> items;
603     variantMapToItems(state.parameters(), defaultParams, items);
604     m_ui.stateTreeWidget->insertTopLevelItems(0, items);
605
606     QMap<QString, QString> shaderSources = state.shaderSources();
607     if (shaderSources.isEmpty()) {
608         m_sourcesWidget->setShaders(shaderSources);
609     } else {
610         m_sourcesWidget->setShaders(shaderSources);
611     }
612
613     m_ui.uniformsTreeWidget->clear();
614     QList<QTreeWidgetItem *> uniformsItems;
615     variantMapToItems(state.uniforms(), QVariantMap(), uniformsItems);
616     m_ui.uniformsTreeWidget->insertTopLevelItems(0, uniformsItems);
617
618     const QList<ApiTexture> &textures =
619         state.textures();
620     const QList<ApiFramebuffer> &fbos =
621         state.framebuffers();
622
623     m_ui.surfacesTreeWidget->clear();
624     if (textures.isEmpty() && fbos.isEmpty()) {
625         m_ui.surfacesTab->setDisabled(false);
626     } else {
627         m_ui.surfacesTreeWidget->setIconSize(QSize(THUMBNAIL_SIZE, THUMBNAIL_SIZE));
628         if (!textures.isEmpty()) {
629             QTreeWidgetItem *textureItem =
630                 new QTreeWidgetItem(m_ui.surfacesTreeWidget);
631             textureItem->setText(0, tr("Textures"));
632             if (textures.count() <= 6) {
633                 textureItem->setExpanded(true);
634             }
635
636             for (int i = 0; i < textures.count(); ++i) {
637                 const ApiTexture &texture =
638                     textures[i];
639                 addSurfaceItem(texture, texture.label(),
640                                textureItem,
641                                m_ui.surfacesTreeWidget);
642             }
643         }
644         if (!fbos.isEmpty()) {
645             QTreeWidgetItem *fboItem =
646                 new QTreeWidgetItem(m_ui.surfacesTreeWidget);
647             fboItem->setText(0, tr("Framebuffers"));
648             if (fbos.count() <= 6) {
649                 fboItem->setExpanded(true);
650             }
651
652             for (int i = 0; i < fbos.count(); ++i) {
653                 const ApiFramebuffer &fbo =
654                     fbos[i];
655                 addSurfaceItem(fbo, fbo.type(),
656                                fboItem,
657                                m_ui.surfacesTreeWidget);
658             }
659         }
660         m_ui.surfacesTab->setEnabled(true);
661     }
662     m_ui.stateDock->show();
663 }
664
665 void MainWindow::showSettings()
666 {
667     SettingsDialog dialog;
668     dialog.setFilterModel(m_proxyModel);
669
670     dialog.exec();
671 }
672
673 void MainWindow::openHelp(const QUrl &url)
674 {
675     QDesktopServices::openUrl(url);
676 }
677
678 void MainWindow::showSurfacesMenu(const QPoint &pos)
679 {
680     QTreeWidget *tree = m_ui.surfacesTreeWidget;
681     QTreeWidgetItem *item = tree->itemAt(pos);
682     if (!item) {
683         return;
684     }
685
686     QMenu menu(tr("Surfaces"), this);
687
688     QAction *act = menu.addAction(tr("View Image"));
689     act->setStatusTip(tr("View the currently selected surface"));
690     connect(act, SIGNAL(triggered()),
691             SLOT(showSelectedSurface()));
692
693     act = menu.addAction(tr("Save Image"));
694     act->setStatusTip(tr("Save the currently selected surface"));
695     connect(act, SIGNAL(triggered()),
696             SLOT(saveSelectedSurface()));
697
698     menu.exec(tree->viewport()->mapToGlobal(pos));
699 }
700
701 void MainWindow::showSelectedSurface()
702 {
703     QTreeWidgetItem *item =
704         m_ui.surfacesTreeWidget->currentItem();
705
706     if (!item) {
707         return;
708     }
709
710     ImageViewer *viewer = new ImageViewer(this);
711
712     QString title;
713     if (selectedCall()) {
714         title = tr("QApiTrace - Surface at %1 (%2)")
715                 .arg(selectedCall()->name())
716                 .arg(selectedCall()->index());
717     } else {
718         title = tr("QApiTrace - Surface Viewer");
719     }
720     viewer->setWindowTitle(title);
721
722     viewer->setAttribute(Qt::WA_DeleteOnClose, true);
723
724     QVariant var = item->data(0, Qt::UserRole);
725     QByteArray base64Data = var.value<QByteArray>();
726     viewer->setBase64Data(base64Data);
727
728     viewer->show();
729     viewer->raise();
730     viewer->activateWindow();
731 }
732
733 void MainWindow::initObjects()
734 {
735     m_ui.stateTreeWidget->sortByColumn(0, Qt::AscendingOrder);
736     m_ui.uniformsTreeWidget->sortByColumn(0, Qt::AscendingOrder);
737
738     m_sourcesWidget = new ShadersSourceWidget(m_ui.shadersTab);
739     QVBoxLayout *layout = new QVBoxLayout;
740     layout->addWidget(m_sourcesWidget);
741     m_ui.shadersTab->setLayout(layout);
742
743     m_trace = new ApiTrace();
744     m_retracer = new Retracer(this);
745
746     m_vdataInterpreter = new VertexDataInterpreter(this);
747     m_vdataInterpreter->setListWidget(m_ui.vertexDataListWidget);
748     m_vdataInterpreter->setStride(
749         m_ui.vertexStrideSB->value());
750     m_vdataInterpreter->setComponents(
751         m_ui.vertexComponentsSB->value());
752     m_vdataInterpreter->setStartingOffset(
753         m_ui.startingOffsetSB->value());
754     m_vdataInterpreter->setTypeFromString(
755         m_ui.vertexTypeCB->currentText());
756
757     m_model = new ApiTraceModel();
758     m_model->setApiTrace(m_trace);
759     m_proxyModel = new ApiTraceFilter();
760     m_proxyModel->setSourceModel(m_model);
761     m_ui.callView->setModel(m_proxyModel);
762     m_ui.callView->setItemDelegate(
763         new ApiCallDelegate(m_ui.callView));
764     m_ui.callView->resizeColumnToContents(0);
765     m_ui.callView->header()->swapSections(0, 1);
766     m_ui.callView->setColumnWidth(1, 42);
767     m_ui.callView->setContextMenuPolicy(Qt::CustomContextMenu);
768
769     m_progressBar = new QProgressBar();
770     m_progressBar->setRange(0, 100);
771     statusBar()->addPermanentWidget(m_progressBar);
772     m_progressBar->hide();
773
774     m_argsEditor = new ArgumentsEditor(this);
775
776     m_ui.detailsDock->hide();
777     m_ui.backtraceDock->hide();
778     m_ui.errorsDock->hide();
779     m_ui.vertexDataDock->hide();
780     m_ui.stateDock->hide();
781     setDockOptions(dockOptions() | QMainWindow::ForceTabbedDocks);
782
783     tabifyDockWidget(m_ui.stateDock, m_ui.vertexDataDock);
784     tabifyDockWidget(m_ui.detailsDock, m_ui.errorsDock);
785     tabifyDockWidget(m_ui.detailsDock, m_ui.backtraceDock);
786
787     m_ui.surfacesTreeWidget->setContextMenuPolicy(Qt::CustomContextMenu);
788
789     m_ui.detailsWebView->page()->setLinkDelegationPolicy(
790         QWebPage::DelegateExternalLinks);
791
792     m_jumpWidget = new JumpWidget(this);
793     m_ui.centralLayout->addWidget(m_jumpWidget);
794     m_jumpWidget->hide();
795
796     m_searchWidget = new SearchWidget(this);
797     m_ui.centralLayout->addWidget(m_searchWidget);
798     m_searchWidget->hide();
799
800     m_traceProcess = new TraceProcess(this);
801     m_trimProcess = new TrimProcess(this);
802
803     m_profileDialog = new ProfileDialog();
804 }
805
806 void MainWindow::initConnections()
807 {
808     connect(m_trace, SIGNAL(startedLoadingTrace()),
809             this, SLOT(startedLoadingTrace()));
810     connect(m_trace, SIGNAL(loaded(int)),
811             this, SLOT(loadProgess(int)));
812     connect(m_trace, SIGNAL(finishedLoadingTrace()),
813             this, SLOT(finishedLoadingTrace()));
814     connect(m_trace, SIGNAL(startedSaving()),
815             this, SLOT(slotStartedSaving()));
816     connect(m_trace, SIGNAL(saved()),
817             this, SLOT(slotSaved()));
818     connect(m_trace, SIGNAL(changed(ApiTraceEvent*)),
819             this, SLOT(slotTraceChanged(ApiTraceEvent*)));
820     connect(m_trace, SIGNAL(findResult(ApiTrace::SearchRequest,ApiTrace::SearchResult,ApiTraceCall*)),
821             this, SLOT(slotSearchResult(ApiTrace::SearchRequest,ApiTrace::SearchResult,ApiTraceCall*)));
822     connect(m_trace, SIGNAL(foundFrameStart(ApiTraceFrame*)),
823             this, SLOT(slotFoundFrameStart(ApiTraceFrame*)));
824     connect(m_trace, SIGNAL(foundFrameEnd(ApiTraceFrame*)),
825             this, SLOT(slotFoundFrameEnd(ApiTraceFrame*)));
826     connect(m_trace, SIGNAL(foundCallIndex(ApiTraceCall*)),
827             this, SLOT(slotJumpToResult(ApiTraceCall*)));
828
829     connect(m_retracer, SIGNAL(finished(const QString&)),
830             this, SLOT(replayFinished(const QString&)));
831     connect(m_retracer, SIGNAL(error(const QString&)),
832             this, SLOT(replayError(const QString&)));
833     connect(m_retracer, SIGNAL(foundState(ApiTraceState*)),
834             this, SLOT(replayStateFound(ApiTraceState*)));
835     connect(m_retracer, SIGNAL(foundProfile(trace::Profile*)),
836             this, SLOT(replayProfileFound(trace::Profile*)));
837     connect(m_retracer, SIGNAL(foundThumbnails(const QList<QImage>&)),
838             this, SLOT(replayThumbnailsFound(const QList<QImage>&)));
839     connect(m_retracer, SIGNAL(retraceErrors(const QList<ApiTraceError>&)),
840             this, SLOT(slotRetraceErrors(const QList<ApiTraceError>&)));
841
842     connect(m_ui.vertexInterpretButton, SIGNAL(clicked()),
843             m_vdataInterpreter, SLOT(interpretData()));
844     connect(m_ui.vertexTypeCB, SIGNAL(currentIndexChanged(const QString&)),
845             m_vdataInterpreter, SLOT(setTypeFromString(const QString&)));
846     connect(m_ui.vertexStrideSB, SIGNAL(valueChanged(int)),
847             m_vdataInterpreter, SLOT(setStride(int)));
848     connect(m_ui.vertexComponentsSB, SIGNAL(valueChanged(int)),
849             m_vdataInterpreter, SLOT(setComponents(int)));
850     connect(m_ui.startingOffsetSB, SIGNAL(valueChanged(int)),
851             m_vdataInterpreter, SLOT(setStartingOffset(int)));
852
853
854     connect(m_ui.actionNew, SIGNAL(triggered()),
855             this, SLOT(createTrace()));
856     connect(m_ui.actionOpen, SIGNAL(triggered()),
857             this, SLOT(openTrace()));
858     connect(m_ui.actionQuit, SIGNAL(triggered()),
859             this, SLOT(close()));
860
861     connect(m_ui.actionFind, SIGNAL(triggered()),
862             this, SLOT(slotSearch()));
863     connect(m_ui.actionGo, SIGNAL(triggered()),
864             this, SLOT(slotGoTo()));
865     connect(m_ui.actionGoFrameStart, SIGNAL(triggered()),
866             this, SLOT(slotGoFrameStart()));
867     connect(m_ui.actionGoFrameEnd, SIGNAL(triggered()),
868             this, SLOT(slotGoFrameEnd()));
869
870     connect(m_ui.actionReplay, SIGNAL(triggered()),
871             this, SLOT(replayStart()));
872     connect(m_ui.actionProfile, SIGNAL(triggered()),
873             this, SLOT(replayProfile()));
874     connect(m_ui.actionStop, SIGNAL(triggered()),
875             this, SLOT(replayStop()));
876     connect(m_ui.actionLookupState, SIGNAL(triggered()),
877             this, SLOT(lookupState()));
878     connect(m_ui.actionTrim, SIGNAL(triggered()),
879             this, SLOT(trim()));
880     connect(m_ui.actionShowThumbnails, SIGNAL(triggered()),
881             this, SLOT(showThumbnails()));
882     connect(m_ui.actionOptions, SIGNAL(triggered()),
883             this, SLOT(showSettings()));
884
885     connect(m_ui.callView->selectionModel(), SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)),
886             this, SLOT(callItemSelected(const QModelIndex &)));
887     connect(m_ui.callView, SIGNAL(doubleClicked(const QModelIndex &)),
888             this, SLOT(callItemActivated(const QModelIndex &)));
889     connect(m_ui.callView, SIGNAL(customContextMenuRequested(QPoint)),
890             this, SLOT(customContextMenuRequested(QPoint)));
891
892     connect(m_ui.surfacesTreeWidget,
893             SIGNAL(customContextMenuRequested(const QPoint &)),
894             SLOT(showSurfacesMenu(const QPoint &)));
895     connect(m_ui.surfacesTreeWidget,
896             SIGNAL(itemDoubleClicked(QTreeWidgetItem *, int)),
897             SLOT(showSelectedSurface()));
898
899     connect(m_ui.detailsWebView, SIGNAL(linkClicked(const QUrl&)),
900             this, SLOT(openHelp(const QUrl&)));
901
902     connect(m_ui.nonDefaultsCB, SIGNAL(toggled(bool)),
903             this, SLOT(fillState(bool)));
904
905     connect(m_jumpWidget, SIGNAL(jumpTo(int)),
906             SLOT(slotJumpTo(int)));
907
908     connect(m_searchWidget,
909             SIGNAL(searchNext(const QString&, Qt::CaseSensitivity)),
910             SLOT(slotSearchNext(const QString&, Qt::CaseSensitivity)));
911     connect(m_searchWidget,
912             SIGNAL(searchPrev(const QString&, Qt::CaseSensitivity)),
913             SLOT(slotSearchPrev(const QString&, Qt::CaseSensitivity)));
914
915     connect(m_traceProcess, SIGNAL(tracedFile(const QString&)),
916             SLOT(createdTrace(const QString&)));
917     connect(m_traceProcess, SIGNAL(error(const QString&)),
918             SLOT(traceError(const QString&)));
919
920     connect(m_trimProcess, SIGNAL(trimmedFile(const QString&)),
921             SLOT(createdTrim(const QString&)));
922     connect(m_trimProcess, SIGNAL(error(const QString&)),
923             SLOT(trimError(const QString&)));
924
925     connect(m_ui.errorsDock, SIGNAL(visibilityChanged(bool)),
926             m_ui.actionShowErrorsDock, SLOT(setChecked(bool)));
927     connect(m_ui.actionShowErrorsDock, SIGNAL(triggered(bool)),
928             m_ui.errorsDock, SLOT(setVisible(bool)));
929     connect(m_ui.errorsTreeWidget,
930             SIGNAL(itemActivated(QTreeWidgetItem*, int)),
931             this, SLOT(slotErrorSelected(QTreeWidgetItem*)));
932
933     connect(m_ui.actionShowProfileDialog, SIGNAL(triggered(bool)),
934             m_profileDialog, SLOT(show()));
935     connect(m_profileDialog, SIGNAL(jumpToCall(int)),
936             this, SLOT(slotJumpTo(int)));
937 }
938
939 void MainWindow::updateActionsState(bool traceLoaded, bool stopped)
940 {
941     if (traceLoaded) {
942         /* Edit */
943         m_ui.actionFind          ->setEnabled(true);
944         m_ui.actionGo            ->setEnabled(true);
945         m_ui.actionGoFrameStart  ->setEnabled(true);
946         m_ui.actionGoFrameEnd    ->setEnabled(true);
947
948         /* Trace */
949         if (stopped) {
950             m_ui.actionStop->setEnabled(false);
951             m_ui.actionReplay->setEnabled(true);
952         }
953         else {
954             m_ui.actionStop->setEnabled(true);
955             m_ui.actionReplay->setEnabled(false);
956         }
957
958         m_ui.actionProfile       ->setEnabled(true);
959         m_ui.actionLookupState   ->setEnabled(true);
960         m_ui.actionShowThumbnails->setEnabled(true);
961         m_ui.actionTrim          ->setEnabled(true);
962     }
963     else {
964         /* Edit */
965         m_ui.actionFind          ->setEnabled(false);
966         m_ui.actionGo            ->setEnabled(false);
967         m_ui.actionGoFrameStart  ->setEnabled(false);
968         m_ui.actionGoFrameEnd    ->setEnabled(false);
969
970         /* Trace */
971         m_ui.actionReplay        ->setEnabled(false);
972         m_ui.actionProfile       ->setEnabled(false);
973         m_ui.actionStop          ->setEnabled(false);
974         m_ui.actionLookupState   ->setEnabled(false);
975         m_ui.actionShowThumbnails->setEnabled(false);
976         m_ui.actionTrim          ->setEnabled(false);
977     }
978 }
979
980 void MainWindow::closeEvent(QCloseEvent * event)
981 {
982     m_profileDialog->close();
983     QMainWindow::closeEvent(event);
984 }
985
986 void MainWindow::replayProfileFound(trace::Profile *profile)
987 {
988     m_ui.actionShowProfileDialog->setEnabled(true);
989     m_profileDialog->setProfile(profile);
990     m_profileDialog->show();
991     m_profileDialog->activateWindow();
992     m_profileDialog->setFocus();
993 }
994
995 void MainWindow::replayStateFound(ApiTraceState *state)
996 {
997     m_stateEvent->setState(state);
998     m_model->stateSetOnEvent(m_stateEvent);
999     if (m_selectedEvent == m_stateEvent ||
1000         m_nonDefaultsLookupEvent == m_selectedEvent) {
1001         fillStateForFrame();
1002     } else {
1003         m_ui.stateDock->hide();
1004     }
1005     m_nonDefaultsLookupEvent = 0;
1006 }
1007
1008 void MainWindow::replayThumbnailsFound(const QList<QImage> &thumbnails)
1009 {
1010     m_ui.callView->setUniformRowHeights(false);
1011     m_trace->bindThumbnailsToFrames(thumbnails);
1012 }
1013
1014 void MainWindow::slotGoTo()
1015 {
1016     m_searchWidget->hide();
1017     m_jumpWidget->show();
1018 }
1019
1020 void MainWindow::slotJumpTo(int callNum)
1021 {
1022     m_trace->findCallIndex(callNum);
1023 }
1024
1025 void MainWindow::createdTrace(const QString &path)
1026 {
1027     qDebug()<<"Done tracing "<<path;
1028     newTraceFile(path);
1029 }
1030
1031 void MainWindow::traceError(const QString &msg)
1032 {
1033     QMessageBox::warning(
1034             this,
1035             tr("Tracing Error"),
1036             msg);
1037 }
1038
1039 void MainWindow::createdTrim(const QString &path)
1040 {
1041     qDebug()<<"Done trimming "<<path;
1042
1043     newTraceFile(path);
1044 }
1045
1046 void MainWindow::trimError(const QString &msg)
1047 {
1048     QMessageBox::warning(
1049             this,
1050             tr("Trim Error"),
1051             msg);
1052 }
1053
1054 void MainWindow::slotSearch()
1055 {
1056     m_jumpWidget->hide();
1057     m_searchWidget->show();
1058 }
1059
1060 void MainWindow::slotSearchNext(const QString &str,
1061                                 Qt::CaseSensitivity sensitivity)
1062 {
1063     ApiTraceCall *call = currentCall();
1064     ApiTraceFrame *frame = currentFrame();
1065
1066     Q_ASSERT(call || frame);
1067     if (!frame) {
1068         frame = call->parentFrame();
1069     }
1070     Q_ASSERT(frame);
1071
1072     m_trace->findNext(frame, call, str, sensitivity);
1073 }
1074
1075 void MainWindow::slotSearchPrev(const QString &str,
1076                                 Qt::CaseSensitivity sensitivity)
1077 {
1078     ApiTraceCall *call = currentCall();
1079     ApiTraceFrame *frame = currentFrame();
1080
1081     Q_ASSERT(call || frame);
1082     if (!frame) {
1083         frame = call->parentFrame();
1084     }
1085     Q_ASSERT(frame);
1086
1087     m_trace->findPrev(frame, call, str, sensitivity);
1088 }
1089
1090 void MainWindow::fillState(bool nonDefaults)
1091 {
1092     if (nonDefaults) {
1093         ApiTraceState defaultState = m_trace->defaultState();
1094         if (defaultState.isEmpty()) {
1095             m_ui.nonDefaultsCB->blockSignals(true);
1096             m_ui.nonDefaultsCB->setChecked(false);
1097             m_ui.nonDefaultsCB->blockSignals(false);
1098             ApiTraceFrame *firstFrame =
1099                 m_trace->frameAt(0);
1100             if (!firstFrame) {
1101                 return;
1102             }
1103             if (!firstFrame->isLoaded()) {
1104                 m_trace->loadFrame(firstFrame);
1105                 return;
1106             }
1107             ApiTraceCall *firstCall = firstFrame->calls().first();
1108             ApiTraceEvent *oldSelected = m_selectedEvent;
1109             m_nonDefaultsLookupEvent = m_selectedEvent;
1110             m_selectedEvent = firstCall;
1111             lookupState();
1112             m_selectedEvent = oldSelected;
1113         }
1114     }
1115     fillStateForFrame();
1116 }
1117
1118 void MainWindow::customContextMenuRequested(QPoint pos)
1119 {
1120     QModelIndex index = m_ui.callView->indexAt(pos);
1121
1122     callItemSelected(index);
1123     if (!index.isValid()) {
1124         return;
1125     }
1126
1127     ApiTraceEvent *event =
1128         index.data(ApiTraceModel::EventRole).value<ApiTraceEvent*>();
1129     if (!event) {
1130         return;
1131     }
1132
1133     QMenu menu;
1134     menu.addAction(QIcon(":/resources/media-record.png"),
1135                    tr("Lookup state"), this, SLOT(lookupState()));
1136     if (event->type() == ApiTraceEvent::Call) {
1137         menu.addAction(tr("Edit"), this, SLOT(editCall()));
1138     }
1139
1140     menu.exec(QCursor::pos());
1141 }
1142
1143 void MainWindow::editCall()
1144 {
1145     if (m_selectedEvent && m_selectedEvent->type() == ApiTraceEvent::Call) {
1146         ApiTraceCall *call = static_cast<ApiTraceCall*>(m_selectedEvent);
1147         m_argsEditor->setCall(call);
1148         m_argsEditor->show();
1149     }
1150 }
1151
1152 void MainWindow::slotStartedSaving()
1153 {
1154     m_progressBar->show();
1155     statusBar()->showMessage(
1156         tr("Saving to %1").arg(m_trace->fileName()));
1157 }
1158
1159 void MainWindow::slotSaved()
1160 {
1161     statusBar()->showMessage(
1162         tr("Saved to %1").arg(m_trace->fileName()), 2000);
1163     m_progressBar->hide();
1164 }
1165
1166 void MainWindow::slotGoFrameStart()
1167 {
1168     ApiTraceFrame *frame = currentFrame();
1169     ApiTraceCall *call = currentCall();
1170
1171     if (!frame && call) {
1172         frame = call->parentFrame();
1173     }
1174
1175     m_trace->findFrameStart(frame);
1176 }
1177
1178 void MainWindow::slotGoFrameEnd()
1179 {
1180     ApiTraceFrame *frame = currentFrame();
1181     ApiTraceCall *call = currentCall();
1182
1183     if (!frame && call) {
1184         frame = call->parentFrame();
1185     }
1186
1187     m_trace->findFrameEnd(frame);
1188 }
1189
1190 ApiTraceFrame * MainWindow::selectedFrame() const
1191 {
1192     if (m_selectedEvent) {
1193         if (m_selectedEvent->type() == ApiTraceEvent::Frame) {
1194             return static_cast<ApiTraceFrame*>(m_selectedEvent);
1195         } else {
1196             Q_ASSERT(m_selectedEvent->type() == ApiTraceEvent::Call);
1197             ApiTraceCall *call = static_cast<ApiTraceCall*>(m_selectedEvent);
1198             return call->parentFrame();
1199         }
1200     }
1201     return NULL;
1202 }
1203
1204 void MainWindow::slotTraceChanged(ApiTraceEvent *event)
1205 {
1206     Q_ASSERT(event);
1207     if (event == m_selectedEvent) {
1208         if (event->type() == ApiTraceEvent::Call) {
1209             ApiTraceCall *call = static_cast<ApiTraceCall*>(event);
1210             m_ui.detailsWebView->setHtml(call->toHtml());
1211         }
1212     }
1213 }
1214
1215 void MainWindow::slotRetraceErrors(const QList<ApiTraceError> &errors)
1216 {
1217     m_ui.errorsTreeWidget->clear();
1218
1219     foreach(ApiTraceError error, errors) {
1220         m_trace->setCallError(error);
1221
1222         QTreeWidgetItem *item =
1223             new QTreeWidgetItem(m_ui.errorsTreeWidget);
1224         item->setData(0, Qt::DisplayRole, error.callIndex);
1225         item->setData(0, Qt::UserRole, error.callIndex);
1226         QString type = error.type;
1227         type[0] = type[0].toUpper();
1228         item->setData(1, Qt::DisplayRole, type);
1229         item->setData(2, Qt::DisplayRole, error.message);
1230     }
1231 }
1232
1233 void MainWindow::slotErrorSelected(QTreeWidgetItem *current)
1234 {
1235     if (current) {
1236         int callIndex =
1237             current->data(0, Qt::UserRole).toInt();
1238         m_trace->findCallIndex(callIndex);
1239     }
1240 }
1241
1242 ApiTraceCall * MainWindow::selectedCall() const
1243 {
1244     if (m_selectedEvent &&
1245         m_selectedEvent->type() == ApiTraceEvent::Call) {
1246         return static_cast<ApiTraceCall*>(m_selectedEvent);
1247     }
1248     return NULL;
1249 }
1250
1251 void MainWindow::saveSelectedSurface()
1252 {
1253     QTreeWidgetItem *item =
1254         m_ui.surfacesTreeWidget->currentItem();
1255
1256     if (!item || !m_trace) {
1257         return;
1258     }
1259
1260     QVariant var = item->data(0, Qt::UserRole);
1261     QImage img = var.value<QImage>();
1262
1263     QString imageIndex;
1264     if (selectedCall()) {
1265         imageIndex = tr("_call_%1")
1266                      .arg(selectedCall()->index());
1267     } else if (selectedFrame()) {
1268         ApiTraceCall *firstCall =
1269             static_cast<ApiTraceCall *>(selectedFrame()->eventAtRow(0));
1270         if (firstCall) {
1271             imageIndex = tr("_frame_%1")
1272                          .arg(firstCall->index());
1273         } else {
1274             qDebug()<<"unknown frame number";
1275             imageIndex = tr("_frame_%1")
1276                          .arg(firstCall->index());
1277         }
1278     }
1279
1280     //which of the surfaces are we saving
1281     QTreeWidgetItem *parent = item->parent();
1282     int parentIndex =
1283         m_ui.surfacesTreeWidget->indexOfTopLevelItem(parent);
1284     if (parentIndex < 0) {
1285         parentIndex = 0;
1286     }
1287     int childIndex = 0;
1288     if (parent) {
1289         childIndex = parent->indexOfChild(item);
1290     } else {
1291         childIndex = m_ui.surfacesTreeWidget->indexOfTopLevelItem(item);
1292     }
1293
1294
1295     QString fileName =
1296         tr("%1%2-%3_%4.png")
1297         .arg(m_trace->fileName())
1298         .arg(imageIndex)
1299         .arg(parentIndex)
1300         .arg(childIndex);
1301     //qDebug()<<"save "<<fileName;
1302     img.save(fileName, "PNG");
1303     statusBar()->showMessage( tr("Saved '%1'").arg(fileName), 5000);
1304 }
1305
1306 void MainWindow::loadProgess(int percent)
1307 {
1308     m_progressBar->setValue(percent);
1309 }
1310
1311 void MainWindow::slotSearchResult(const ApiTrace::SearchRequest &request,
1312                                   ApiTrace::SearchResult result,
1313                                   ApiTraceCall *call)
1314 {
1315     switch (result) {
1316     case ApiTrace::SearchResult_NotFound:
1317         m_searchWidget->setFound(false);
1318         break;
1319     case ApiTrace::SearchResult_Found: {
1320         QModelIndex index = m_proxyModel->indexForCall(call);
1321
1322         if (index.isValid()) {
1323             m_ui.callView->setCurrentIndex(index);
1324             m_searchWidget->setFound(true);
1325         } else {
1326             //call is filtered out, so continue searching but from the
1327             // filtered call
1328             if (!call) {
1329                 qDebug()<<"Error: search success with no call";
1330                 return;
1331             }
1332 //            qDebug()<<"filtered! search from "<<call->searchText()
1333 //                   <<", call idx = "<<call->index();
1334
1335             if (request.direction == ApiTrace::SearchRequest::Next) {
1336                 m_trace->findNext(call->parentFrame(), call,
1337                                   request.text, request.cs);
1338             } else {
1339                 m_trace->findNext(call->parentFrame(), call,
1340                                   request.text, request.cs);
1341             }
1342         }
1343     }
1344         break;
1345     case ApiTrace::SearchResult_Wrapped:
1346         m_searchWidget->setFound(false);
1347         break;
1348     }
1349 }
1350
1351 ApiTraceFrame * MainWindow::currentFrame() const
1352 {
1353     QModelIndex index = m_ui.callView->currentIndex();
1354     ApiTraceEvent *event = 0;
1355
1356     if (!index.isValid()) {
1357         index = m_proxyModel->index(0, 0, QModelIndex());
1358         if (!index.isValid()) {
1359             qDebug()<<"no currently valid index";
1360             return 0;
1361         }
1362     }
1363
1364     event = index.data(ApiTraceModel::EventRole).value<ApiTraceEvent*>();
1365     Q_ASSERT(event);
1366     if (!event) {
1367         return 0;
1368     }
1369
1370     ApiTraceFrame *frame = 0;
1371     if (event->type() == ApiTraceCall::Frame) {
1372         frame = static_cast<ApiTraceFrame*>(event);
1373     }
1374     return frame;
1375 }
1376
1377 ApiTraceCall * MainWindow::currentCall() const
1378 {
1379     QModelIndex index = m_ui.callView->currentIndex();
1380     ApiTraceEvent *event = 0;
1381
1382     if (!index.isValid()) {
1383         index = m_proxyModel->index(0, 0, QModelIndex());
1384         if (!index.isValid()) {
1385             qDebug()<<"no currently valid index";
1386             return 0;
1387         }
1388     }
1389
1390     event = index.data(ApiTraceModel::EventRole).value<ApiTraceEvent*>();
1391     Q_ASSERT(event);
1392     if (!event) {
1393         return 0;
1394     }
1395
1396     ApiTraceCall *call = 0;
1397     if (event->type() == ApiTraceCall::Call) {
1398         call = static_cast<ApiTraceCall*>(event);
1399     }
1400
1401     return call;
1402
1403 }
1404
1405 void MainWindow::slotFoundFrameStart(ApiTraceFrame *frame)
1406 {
1407     Q_ASSERT(frame->isLoaded());
1408     if (!frame || frame->isEmpty()) {
1409         return;
1410     }
1411
1412     QVector<ApiTraceCall*>::const_iterator itr;
1413     QVector<ApiTraceCall*> calls = frame->calls();
1414
1415     itr = calls.constBegin();
1416     while (itr != calls.constEnd()) {
1417         ApiTraceCall *call = *itr;
1418         QModelIndex idx = m_proxyModel->indexForCall(call);
1419         if (idx.isValid()) {
1420             m_ui.callView->setCurrentIndex(idx);
1421             m_ui.callView->scrollTo(idx, QAbstractItemView::PositionAtTop);
1422             break;
1423         }
1424         ++itr;
1425     }
1426 }
1427
1428 void MainWindow::slotFoundFrameEnd(ApiTraceFrame *frame)
1429 {
1430     Q_ASSERT(frame->isLoaded());
1431     if (!frame || frame->isEmpty()) {
1432         return;
1433     }
1434     QVector<ApiTraceCall*>::const_iterator itr;
1435     QVector<ApiTraceCall*> calls = frame->calls();
1436
1437     itr = calls.constEnd();
1438     do {
1439         --itr;
1440         ApiTraceCall *call = *itr;
1441         QModelIndex idx = m_proxyModel->indexForCall(call);
1442         if (idx.isValid()) {
1443             m_ui.callView->setCurrentIndex(idx);
1444             m_ui.callView->scrollTo(idx, QAbstractItemView::PositionAtBottom);
1445             break;
1446         }
1447     } while (itr != calls.constBegin());
1448 }
1449
1450 void MainWindow::slotJumpToResult(ApiTraceCall *call)
1451 {
1452     QModelIndex idx = m_proxyModel->indexForCall(call);
1453     if (idx.isValid()) {
1454         activateWindow();
1455         m_ui.callView->setFocus();
1456         m_ui.callView->setCurrentIndex(idx);
1457         m_ui.callView->scrollTo(idx, QAbstractItemView::PositionAtCenter);
1458     } else {
1459         statusBar()->showMessage(tr("Call has been filtered out."));
1460     }
1461 }
1462
1463 #include "mainwindow.moc"