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