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