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