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