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