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