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