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