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