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