]> git.cworth.org Git - apitrace/blob - gui/mainwindow.cpp
Merge branch 'd3d10'
[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     viewer->show();
622     viewer->raise();
623     viewer->activateWindow();
624 }
625
626 void MainWindow::initObjects()
627 {
628     m_ui.stateTreeWidget->sortByColumn(0, Qt::AscendingOrder);
629     m_ui.uniformsTreeWidget->sortByColumn(0, Qt::AscendingOrder);
630
631     m_sourcesWidget = new ShadersSourceWidget(m_ui.shadersTab);
632     QVBoxLayout *layout = new QVBoxLayout;
633     layout->addWidget(m_sourcesWidget);
634     m_ui.shadersTab->setLayout(layout);
635
636     m_trace = new ApiTrace();
637     m_retracer = new Retracer(this);
638
639     m_vdataInterpreter = new VertexDataInterpreter(this);
640     m_vdataInterpreter->setListWidget(m_ui.vertexDataListWidget);
641     m_vdataInterpreter->setStride(
642         m_ui.vertexStrideSB->value());
643     m_vdataInterpreter->setComponents(
644         m_ui.vertexComponentsSB->value());
645     m_vdataInterpreter->setStartingOffset(
646         m_ui.startingOffsetSB->value());
647     m_vdataInterpreter->setTypeFromString(
648         m_ui.vertexTypeCB->currentText());
649
650     m_model = new ApiTraceModel();
651     m_model->setApiTrace(m_trace);
652     m_proxyModel = new ApiTraceFilter();
653     m_proxyModel->setSourceModel(m_model);
654     m_ui.callView->setModel(m_proxyModel);
655     m_ui.callView->setItemDelegate(
656         new ApiCallDelegate(m_ui.callView));
657     m_ui.callView->resizeColumnToContents(0);
658     m_ui.callView->header()->swapSections(0, 1);
659     m_ui.callView->setColumnWidth(1, 42);
660     m_ui.callView->setContextMenuPolicy(Qt::CustomContextMenu);
661
662     m_progressBar = new QProgressBar();
663     m_progressBar->setRange(0, 100);
664     statusBar()->addPermanentWidget(m_progressBar);
665     m_progressBar->hide();
666
667     m_argsEditor = new ArgumentsEditor(this);
668
669     m_ui.detailsDock->hide();
670     m_ui.errorsDock->hide();
671     m_ui.vertexDataDock->hide();
672     m_ui.stateDock->hide();
673     setDockOptions(dockOptions() | QMainWindow::ForceTabbedDocks);
674
675     tabifyDockWidget(m_ui.stateDock, m_ui.vertexDataDock);
676     tabifyDockWidget(m_ui.detailsDock, m_ui.errorsDock);
677
678     m_ui.surfacesTreeWidget->setContextMenuPolicy(Qt::CustomContextMenu);
679
680     m_ui.detailsWebView->page()->setLinkDelegationPolicy(
681         QWebPage::DelegateExternalLinks);
682
683     m_jumpWidget = new JumpWidget(this);
684     m_ui.centralLayout->addWidget(m_jumpWidget);
685     m_jumpWidget->hide();
686
687     m_searchWidget = new SearchWidget(this);
688     m_ui.centralLayout->addWidget(m_searchWidget);
689     m_searchWidget->hide();
690
691     m_traceProcess = new TraceProcess(this);
692 }
693
694 void MainWindow::initConnections()
695 {
696     connect(m_trace, SIGNAL(startedLoadingTrace()),
697             this, SLOT(startedLoadingTrace()));
698     connect(m_trace, SIGNAL(loaded(int)),
699             this, SLOT(loadProgess(int)));
700     connect(m_trace, SIGNAL(finishedLoadingTrace()),
701             this, SLOT(finishedLoadingTrace()));
702     connect(m_trace, SIGNAL(startedSaving()),
703             this, SLOT(slotStartedSaving()));
704     connect(m_trace, SIGNAL(saved()),
705             this, SLOT(slotSaved()));
706     connect(m_trace, SIGNAL(changed(ApiTraceCall*)),
707             this, SLOT(slotTraceChanged(ApiTraceCall*)));
708     connect(m_trace, SIGNAL(findResult(ApiTrace::SearchResult,ApiTraceCall*)),
709             this, SLOT(slotSearchResult(ApiTrace::SearchResult,ApiTraceCall*)));
710     connect(m_trace, SIGNAL(foundFrameStart(ApiTraceFrame*)),
711             this, SLOT(slotFoundFrameStart(ApiTraceFrame*)));
712     connect(m_trace, SIGNAL(foundFrameEnd(ApiTraceFrame*)),
713             this, SLOT(slotFoundFrameEnd(ApiTraceFrame*)));
714     connect(m_trace, SIGNAL(foundCallIndex(ApiTraceCall*)),
715             this, SLOT(slotJumpToResult(ApiTraceCall*)));
716
717     connect(m_retracer, SIGNAL(finished(const QString&)),
718             this, SLOT(replayFinished(const QString&)));
719     connect(m_retracer, SIGNAL(error(const QString&)),
720             this, SLOT(replayError(const QString&)));
721     connect(m_retracer, SIGNAL(foundState(ApiTraceState*)),
722             this, SLOT(replayStateFound(ApiTraceState*)));
723     connect(m_retracer, SIGNAL(retraceErrors(const QList<ApiTraceError>&)),
724             this, SLOT(slotRetraceErrors(const QList<ApiTraceError>&)));
725
726     connect(m_ui.vertexInterpretButton, SIGNAL(clicked()),
727             m_vdataInterpreter, SLOT(interpretData()));
728     connect(m_ui.vertexTypeCB, SIGNAL(currentIndexChanged(const QString&)),
729             m_vdataInterpreter, SLOT(setTypeFromString(const QString&)));
730     connect(m_ui.vertexStrideSB, SIGNAL(valueChanged(int)),
731             m_vdataInterpreter, SLOT(setStride(int)));
732     connect(m_ui.vertexComponentsSB, SIGNAL(valueChanged(int)),
733             m_vdataInterpreter, SLOT(setComponents(int)));
734     connect(m_ui.startingOffsetSB, SIGNAL(valueChanged(int)),
735             m_vdataInterpreter, SLOT(setStartingOffset(int)));
736
737
738     connect(m_ui.actionNew, SIGNAL(triggered()),
739             this, SLOT(createTrace()));
740     connect(m_ui.actionOpen, SIGNAL(triggered()),
741             this, SLOT(openTrace()));
742     connect(m_ui.actionQuit, SIGNAL(triggered()),
743             this, SLOT(close()));
744
745     connect(m_ui.actionFind, SIGNAL(triggered()),
746             this, SLOT(slotSearch()));
747     connect(m_ui.actionGo, SIGNAL(triggered()),
748             this, SLOT(slotGoTo()));
749     connect(m_ui.actionGoFrameStart, SIGNAL(triggered()),
750             this, SLOT(slotGoFrameStart()));
751     connect(m_ui.actionGoFrameEnd, SIGNAL(triggered()),
752             this, SLOT(slotGoFrameEnd()));
753
754     connect(m_ui.actionReplay, SIGNAL(triggered()),
755             this, SLOT(replayStart()));
756     connect(m_ui.actionStop, SIGNAL(triggered()),
757             this, SLOT(replayStop()));
758     connect(m_ui.actionLookupState, SIGNAL(triggered()),
759             this, SLOT(lookupState()));
760     connect(m_ui.actionOptions, SIGNAL(triggered()),
761             this, SLOT(showSettings()));
762
763     connect(m_ui.callView, SIGNAL(activated(const QModelIndex &)),
764             this, SLOT(callItemSelected(const QModelIndex &)));
765     connect(m_ui.callView, SIGNAL(customContextMenuRequested(QPoint)),
766             this, SLOT(customContextMenuRequested(QPoint)));
767
768     connect(m_ui.surfacesTreeWidget,
769             SIGNAL(customContextMenuRequested(const QPoint &)),
770             SLOT(showSurfacesMenu(const QPoint &)));
771     connect(m_ui.surfacesTreeWidget,
772             SIGNAL(itemDoubleClicked(QTreeWidgetItem *, int)),
773             SLOT(showSelectedSurface()));
774
775     connect(m_ui.detailsWebView, SIGNAL(linkClicked(const QUrl&)),
776             this, SLOT(openHelp(const QUrl&)));
777
778     connect(m_ui.nonDefaultsCB, SIGNAL(toggled(bool)),
779             this, SLOT(fillState(bool)));
780
781     connect(m_jumpWidget, SIGNAL(jumpTo(int)),
782             SLOT(slotJumpTo(int)));
783
784     connect(m_searchWidget,
785             SIGNAL(searchNext(const QString&, Qt::CaseSensitivity)),
786             SLOT(slotSearchNext(const QString&, Qt::CaseSensitivity)));
787     connect(m_searchWidget,
788             SIGNAL(searchPrev(const QString&, Qt::CaseSensitivity)),
789             SLOT(slotSearchPrev(const QString&, Qt::CaseSensitivity)));
790
791     connect(m_traceProcess, SIGNAL(tracedFile(const QString&)),
792             SLOT(createdTrace(const QString&)));
793     connect(m_traceProcess, SIGNAL(error(const QString&)),
794             SLOT(traceError(const QString&)));
795
796     connect(m_ui.errorsDock, SIGNAL(visibilityChanged(bool)),
797             m_ui.actionShowErrorsDock, SLOT(setChecked(bool)));
798     connect(m_ui.actionShowErrorsDock, SIGNAL(triggered(bool)),
799             m_ui.errorsDock, SLOT(setVisible(bool)));
800     connect(m_ui.errorsTreeWidget,
801             SIGNAL(currentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*)),
802             this, SLOT(slotErrorSelected(QTreeWidgetItem*)));
803 }
804
805 void MainWindow::replayStateFound(ApiTraceState *state)
806 {
807     m_stateEvent->setState(state);
808     m_model->stateSetOnEvent(m_stateEvent);
809     if (m_selectedEvent == m_stateEvent ||
810         m_nonDefaultsLookupEvent == m_selectedEvent) {
811         fillStateForFrame();
812     } else {
813         m_ui.stateDock->hide();
814     }
815     m_nonDefaultsLookupEvent = 0;
816 }
817
818 void MainWindow::slotGoTo()
819 {
820     m_searchWidget->hide();
821     m_jumpWidget->show();
822 }
823
824 void MainWindow::slotJumpTo(int callNum)
825 {
826     m_trace->findCallIndex(callNum);
827 }
828
829 void MainWindow::createdTrace(const QString &path)
830 {
831     qDebug()<<"Done tracing "<<path;
832     newTraceFile(path);
833 }
834
835 void MainWindow::traceError(const QString &msg)
836 {
837     QMessageBox::warning(
838             this,
839             tr("Tracing Error"),
840             msg);
841 }
842
843 void MainWindow::slotSearch()
844 {
845     m_jumpWidget->hide();
846     m_searchWidget->show();
847 }
848
849 void MainWindow::slotSearchNext(const QString &str,
850                                 Qt::CaseSensitivity sensitivity)
851 {
852     ApiTraceCall *call = currentCall();
853     ApiTraceFrame *frame = currentFrame();
854
855     Q_ASSERT(call || frame);
856     if (!frame) {
857         frame = call->parentFrame();
858     }
859     Q_ASSERT(frame);
860
861     m_trace->findNext(frame, call, str, sensitivity);
862 }
863
864 void MainWindow::slotSearchPrev(const QString &str,
865                                 Qt::CaseSensitivity sensitivity)
866 {
867     ApiTraceCall *call = currentCall();
868     ApiTraceFrame *frame = currentFrame();
869
870     Q_ASSERT(call || frame);
871     if (!frame) {
872         frame = call->parentFrame();
873     }
874     Q_ASSERT(frame);
875
876     m_trace->findPrev(frame, call, str, sensitivity);
877 }
878
879 void MainWindow::fillState(bool nonDefaults)
880 {
881     if (nonDefaults) {
882         ApiTraceState defaultState = m_trace->defaultState();
883         if (defaultState.isEmpty()) {
884             m_ui.nonDefaultsCB->blockSignals(true);
885             m_ui.nonDefaultsCB->setChecked(false);
886             m_ui.nonDefaultsCB->blockSignals(false);
887             ApiTraceFrame *firstFrame =
888                 m_trace->frameAt(0);
889             if (!firstFrame) {
890                 return;
891             }
892             if (!firstFrame->isLoaded()) {
893                 m_trace->loadFrame(firstFrame);
894                 return;
895             }
896             ApiTraceCall *firstCall = firstFrame->calls().first();
897             ApiTraceEvent *oldSelected = m_selectedEvent;
898             m_nonDefaultsLookupEvent = m_selectedEvent;
899             m_selectedEvent = firstCall;
900             lookupState();
901             m_selectedEvent = oldSelected;
902         }
903     }
904     fillStateForFrame();
905 }
906
907 void MainWindow::customContextMenuRequested(QPoint pos)
908 {
909     QModelIndex index = m_ui.callView->indexAt(pos);
910
911     callItemSelected(index);
912     if (!index.isValid()) {
913         return;
914     }
915
916     ApiTraceEvent *event =
917         index.data(ApiTraceModel::EventRole).value<ApiTraceEvent*>();
918     if (!event) {
919         return;
920     }
921
922     QMenu menu;
923     menu.addAction(QIcon(":/resources/media-record.png"),
924                    tr("Lookup state"), this, SLOT(lookupState()));
925     if (event->type() == ApiTraceEvent::Call) {
926         menu.addAction(tr("Edit"), this, SLOT(editCall()));
927     }
928
929     menu.exec(QCursor::pos());
930 }
931
932 void MainWindow::editCall()
933 {
934     if (m_selectedEvent && m_selectedEvent->type() == ApiTraceEvent::Call) {
935         ApiTraceCall *call = static_cast<ApiTraceCall*>(m_selectedEvent);
936         m_argsEditor->setCall(call);
937         m_argsEditor->show();
938     }
939 }
940
941 void MainWindow::slotStartedSaving()
942 {
943     m_progressBar->show();
944     statusBar()->showMessage(
945         tr("Saving to %1").arg(m_trace->fileName()));
946 }
947
948 void MainWindow::slotSaved()
949 {
950     statusBar()->showMessage(
951         tr("Saved to %1").arg(m_trace->fileName()), 2000);
952     m_progressBar->hide();
953 }
954
955 void MainWindow::slotGoFrameStart()
956 {
957     ApiTraceFrame *frame = currentFrame();
958     ApiTraceCall *call = currentCall();
959
960     if (!frame && call) {
961         frame = call->parentFrame();
962     }
963
964     m_trace->findFrameStart(frame);
965 }
966
967 void MainWindow::slotGoFrameEnd()
968 {
969     ApiTraceFrame *frame = currentFrame();
970     ApiTraceCall *call = currentCall();
971
972     if (!frame && call) {
973         frame = call->parentFrame();
974     }
975
976     m_trace->findFrameEnd(frame);
977 }
978
979 ApiTraceFrame * MainWindow::selectedFrame() const
980 {
981     if (m_selectedEvent) {
982         if (m_selectedEvent->type() == ApiTraceEvent::Frame) {
983             return static_cast<ApiTraceFrame*>(m_selectedEvent);
984         } else {
985             Q_ASSERT(m_selectedEvent->type() == ApiTraceEvent::Call);
986             ApiTraceCall *call = static_cast<ApiTraceCall*>(m_selectedEvent);
987             return call->parentFrame();
988         }
989     }
990     return NULL;
991 }
992
993 void MainWindow::slotTraceChanged(ApiTraceCall *call)
994 {
995     Q_ASSERT(call);
996     if (call == m_selectedEvent) {
997         m_ui.detailsWebView->setHtml(call->toHtml());
998     }
999 }
1000
1001 void MainWindow::slotRetraceErrors(const QList<ApiTraceError> &errors)
1002 {
1003     m_ui.errorsTreeWidget->clear();
1004
1005     foreach(ApiTraceError error, errors) {
1006         m_trace->setCallError(error);
1007
1008         QTreeWidgetItem *item =
1009             new QTreeWidgetItem(m_ui.errorsTreeWidget);
1010         item->setData(0, Qt::DisplayRole, error.callIndex);
1011         item->setData(0, Qt::UserRole, error.callIndex);
1012         QString type = error.type;
1013         type[0] = type[0].toUpper();
1014         item->setData(1, Qt::DisplayRole, type);
1015         item->setData(2, Qt::DisplayRole, error.message);
1016     }
1017 }
1018
1019 void MainWindow::slotErrorSelected(QTreeWidgetItem *current)
1020 {
1021     if (current) {
1022         int callIndex =
1023             current->data(0, Qt::UserRole).toInt();
1024         m_trace->findCallIndex(callIndex);
1025     }
1026 }
1027
1028 ApiTraceCall * MainWindow::selectedCall() const
1029 {
1030     if (m_selectedEvent &&
1031         m_selectedEvent->type() == ApiTraceEvent::Call) {
1032         return static_cast<ApiTraceCall*>(m_selectedEvent);
1033     }
1034     return NULL;
1035 }
1036
1037 void MainWindow::saveSelectedSurface()
1038 {
1039     QTreeWidgetItem *item =
1040         m_ui.surfacesTreeWidget->currentItem();
1041
1042     if (!item || !m_trace) {
1043         return;
1044     }
1045
1046     QVariant var = item->data(0, Qt::UserRole);
1047     QImage img = var.value<QImage>();
1048
1049     QString imageIndex;
1050     if (selectedCall()) {
1051         imageIndex = tr("_call_%1")
1052                      .arg(selectedCall()->index());
1053     } else if (selectedFrame()) {
1054         ApiTraceCall *firstCall = selectedFrame()->call(0);
1055         if (firstCall) {
1056             imageIndex = tr("_frame_%1")
1057                          .arg(firstCall->index());
1058         } else {
1059             qDebug()<<"unknown frame number";
1060             imageIndex = tr("_frame_%1")
1061                          .arg(firstCall->index());
1062         }
1063     }
1064
1065     //which of the surfaces are we saving
1066     QTreeWidgetItem *parent = item->parent();
1067     int parentIndex =
1068         m_ui.surfacesTreeWidget->indexOfTopLevelItem(parent);
1069     if (parentIndex < 0) {
1070         parentIndex = 0;
1071     }
1072     int childIndex = 0;
1073     if (parent) {
1074         childIndex = parent->indexOfChild(item);
1075     } else {
1076         childIndex = m_ui.surfacesTreeWidget->indexOfTopLevelItem(item);
1077     }
1078
1079
1080     QString fileName =
1081         tr("%1%2-%3_%4.png")
1082         .arg(m_trace->fileName())
1083         .arg(imageIndex)
1084         .arg(parentIndex)
1085         .arg(childIndex);
1086     //qDebug()<<"save "<<fileName;
1087     img.save(fileName, "PNG");
1088     statusBar()->showMessage( tr("Saved '%1'").arg(fileName), 5000);
1089 }
1090
1091 void MainWindow::loadProgess(int percent)
1092 {
1093     m_progressBar->setValue(percent);
1094 }
1095
1096 void MainWindow::slotSearchResult(ApiTrace::SearchResult result,
1097                                   ApiTraceCall *call)
1098 {
1099     switch (result) {
1100     case ApiTrace::SearchResult_NotFound:
1101         m_searchWidget->setFound(false);
1102         break;
1103     case ApiTrace::SearchResult_Found: {
1104         QModelIndex index = m_proxyModel->indexForCall(call);
1105         m_ui.callView->setCurrentIndex(index);
1106         m_searchWidget->setFound(true);
1107     }
1108         break;
1109     case ApiTrace::SearchResult_Wrapped:
1110         m_searchWidget->setFound(false);
1111         break;
1112     }
1113 }
1114
1115 ApiTraceFrame * MainWindow::currentFrame() const
1116 {
1117     QModelIndex index = m_ui.callView->currentIndex();
1118     ApiTraceEvent *event = 0;
1119
1120     if (!index.isValid()) {
1121         index = m_proxyModel->index(0, 0, QModelIndex());
1122         if (!index.isValid()) {
1123             qDebug()<<"no currently valid index";
1124             return 0;
1125         }
1126     }
1127
1128     event = index.data(ApiTraceModel::EventRole).value<ApiTraceEvent*>();
1129     Q_ASSERT(event);
1130     if (!event) {
1131         return 0;
1132     }
1133
1134     ApiTraceFrame *frame = 0;
1135     if (event->type() == ApiTraceCall::Frame) {
1136         frame = static_cast<ApiTraceFrame*>(event);
1137     }
1138     return frame;
1139 }
1140
1141 ApiTraceCall * MainWindow::currentCall() const
1142 {
1143     QModelIndex index = m_ui.callView->currentIndex();
1144     ApiTraceEvent *event = 0;
1145
1146     if (!index.isValid()) {
1147         index = m_proxyModel->index(0, 0, QModelIndex());
1148         if (!index.isValid()) {
1149             qDebug()<<"no currently valid index";
1150             return 0;
1151         }
1152     }
1153
1154     event = index.data(ApiTraceModel::EventRole).value<ApiTraceEvent*>();
1155     Q_ASSERT(event);
1156     if (!event) {
1157         return 0;
1158     }
1159
1160     ApiTraceCall *call = 0;
1161     if (event->type() == ApiTraceCall::Call) {
1162         call = static_cast<ApiTraceCall*>(event);
1163     }
1164
1165     return call;
1166
1167 }
1168
1169 void MainWindow::slotFoundFrameStart(ApiTraceFrame *frame)
1170 {
1171     Q_ASSERT(frame->isLoaded());
1172     if (!frame || frame->isEmpty()) {
1173         return;
1174     }
1175
1176     QVector<ApiTraceCall*>::const_iterator itr;
1177     QVector<ApiTraceCall*> calls = frame->calls();
1178
1179     itr = calls.constBegin();
1180     while (itr != calls.constEnd()) {
1181         ApiTraceCall *call = *itr;
1182         QModelIndex idx = m_proxyModel->indexForCall(call);
1183         if (idx.isValid()) {
1184             m_ui.callView->setCurrentIndex(idx);
1185             break;
1186         }
1187         ++itr;
1188     }
1189 }
1190
1191 void MainWindow::slotFoundFrameEnd(ApiTraceFrame *frame)
1192 {
1193     Q_ASSERT(frame->isLoaded());
1194     if (!frame || frame->isEmpty()) {
1195         return;
1196     }
1197     QVector<ApiTraceCall*>::const_iterator itr;
1198     QVector<ApiTraceCall*> calls = frame->calls();
1199
1200     itr = calls.constEnd();
1201     do {
1202         --itr;
1203         ApiTraceCall *call = *itr;
1204         QModelIndex idx = m_proxyModel->indexForCall(call);
1205         if (idx.isValid()) {
1206             m_ui.callView->setCurrentIndex(idx);
1207             break;
1208         }
1209     } while (itr != calls.constBegin());
1210 }
1211
1212 void MainWindow::slotJumpToResult(ApiTraceCall *call)
1213 {
1214     QModelIndex index = m_proxyModel->indexForCall(call);
1215     if (index.isValid()) {
1216         m_ui.callView->setCurrentIndex(index);
1217     } else {
1218         statusBar()->showMessage(tr("Call has been filtered out."));
1219     }
1220 }
1221
1222 #include "mainwindow.moc"