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