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