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