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