]> git.cworth.org Git - apitrace/blob - gui/mainwindow.cpp
Add trim support to qapitrace GUI app.
[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.setAPI(m_api);
629     dialog.setFilterModel(m_proxyModel);
630
631     dialog.exec();
632
633     m_api = dialog.getAPI();
634 }
635
636 void MainWindow::openHelp(const QUrl &url)
637 {
638     QDesktopServices::openUrl(url);
639 }
640
641 void MainWindow::showSurfacesMenu(const QPoint &pos)
642 {
643     QTreeWidget *tree = m_ui.surfacesTreeWidget;
644     QTreeWidgetItem *item = tree->itemAt(pos);
645     if (!item) {
646         return;
647     }
648
649     QMenu menu(tr("Surfaces"), this);
650
651     QAction *act = menu.addAction(tr("View Image"));
652     act->setStatusTip(tr("View the currently selected surface"));
653     connect(act, SIGNAL(triggered()),
654             SLOT(showSelectedSurface()));
655
656     act = menu.addAction(tr("Save Image"));
657     act->setStatusTip(tr("Save the currently selected surface"));
658     connect(act, SIGNAL(triggered()),
659             SLOT(saveSelectedSurface()));
660
661     menu.exec(tree->viewport()->mapToGlobal(pos));
662 }
663
664 void MainWindow::showSelectedSurface()
665 {
666     QTreeWidgetItem *item =
667         m_ui.surfacesTreeWidget->currentItem();
668
669     if (!item) {
670         return;
671     }
672
673     ImageViewer *viewer = new ImageViewer(this);
674
675     QString title;
676     if (selectedCall()) {
677         title = tr("QApiTrace - Surface at %1 (%2)")
678                 .arg(selectedCall()->name())
679                 .arg(selectedCall()->index());
680     } else {
681         title = tr("QApiTrace - Surface Viewer");
682     }
683     viewer->setWindowTitle(title);
684
685     viewer->setAttribute(Qt::WA_DeleteOnClose, true);
686
687     QVariant var = item->data(0, Qt::UserRole);
688     QImage img = var.value<QImage>();
689     viewer->setImage(img);
690
691     viewer->show();
692     viewer->raise();
693     viewer->activateWindow();
694 }
695
696 void MainWindow::initObjects()
697 {
698     m_ui.stateTreeWidget->sortByColumn(0, Qt::AscendingOrder);
699     m_ui.uniformsTreeWidget->sortByColumn(0, Qt::AscendingOrder);
700
701     m_sourcesWidget = new ShadersSourceWidget(m_ui.shadersTab);
702     QVBoxLayout *layout = new QVBoxLayout;
703     layout->addWidget(m_sourcesWidget);
704     m_ui.shadersTab->setLayout(layout);
705
706     m_trace = new ApiTrace();
707     m_retracer = new Retracer(this);
708
709     m_vdataInterpreter = new VertexDataInterpreter(this);
710     m_vdataInterpreter->setListWidget(m_ui.vertexDataListWidget);
711     m_vdataInterpreter->setStride(
712         m_ui.vertexStrideSB->value());
713     m_vdataInterpreter->setComponents(
714         m_ui.vertexComponentsSB->value());
715     m_vdataInterpreter->setStartingOffset(
716         m_ui.startingOffsetSB->value());
717     m_vdataInterpreter->setTypeFromString(
718         m_ui.vertexTypeCB->currentText());
719
720     m_model = new ApiTraceModel();
721     m_model->setApiTrace(m_trace);
722     m_proxyModel = new ApiTraceFilter();
723     m_proxyModel->setSourceModel(m_model);
724     m_ui.callView->setModel(m_proxyModel);
725     m_ui.callView->setItemDelegate(
726         new ApiCallDelegate(m_ui.callView));
727     m_ui.callView->resizeColumnToContents(0);
728     m_ui.callView->header()->swapSections(0, 1);
729     m_ui.callView->setColumnWidth(1, 42);
730     m_ui.callView->setContextMenuPolicy(Qt::CustomContextMenu);
731
732     m_progressBar = new QProgressBar();
733     m_progressBar->setRange(0, 100);
734     statusBar()->addPermanentWidget(m_progressBar);
735     m_progressBar->hide();
736
737     m_argsEditor = new ArgumentsEditor(this);
738
739     m_ui.detailsDock->hide();
740     m_ui.errorsDock->hide();
741     m_ui.vertexDataDock->hide();
742     m_ui.stateDock->hide();
743     setDockOptions(dockOptions() | QMainWindow::ForceTabbedDocks);
744
745     tabifyDockWidget(m_ui.stateDock, m_ui.vertexDataDock);
746     tabifyDockWidget(m_ui.detailsDock, m_ui.errorsDock);
747
748     m_ui.surfacesTreeWidget->setContextMenuPolicy(Qt::CustomContextMenu);
749
750     m_ui.detailsWebView->page()->setLinkDelegationPolicy(
751         QWebPage::DelegateExternalLinks);
752
753     m_jumpWidget = new JumpWidget(this);
754     m_ui.centralLayout->addWidget(m_jumpWidget);
755     m_jumpWidget->hide();
756
757     m_searchWidget = new SearchWidget(this);
758     m_ui.centralLayout->addWidget(m_searchWidget);
759     m_searchWidget->hide();
760
761     m_traceProcess = new TraceProcess(this);
762     m_trimProcess = new TrimProcess(this);
763 }
764
765 void MainWindow::initConnections()
766 {
767     connect(m_trace, SIGNAL(startedLoadingTrace()),
768             this, SLOT(startedLoadingTrace()));
769     connect(m_trace, SIGNAL(loaded(int)),
770             this, SLOT(loadProgess(int)));
771     connect(m_trace, SIGNAL(finishedLoadingTrace()),
772             this, SLOT(finishedLoadingTrace()));
773     connect(m_trace, SIGNAL(startedSaving()),
774             this, SLOT(slotStartedSaving()));
775     connect(m_trace, SIGNAL(saved()),
776             this, SLOT(slotSaved()));
777     connect(m_trace, SIGNAL(changed(ApiTraceEvent*)),
778             this, SLOT(slotTraceChanged(ApiTraceEvent*)));
779     connect(m_trace, SIGNAL(findResult(ApiTrace::SearchRequest,ApiTrace::SearchResult,ApiTraceCall*)),
780             this, SLOT(slotSearchResult(ApiTrace::SearchRequest,ApiTrace::SearchResult,ApiTraceCall*)));
781     connect(m_trace, SIGNAL(foundFrameStart(ApiTraceFrame*)),
782             this, SLOT(slotFoundFrameStart(ApiTraceFrame*)));
783     connect(m_trace, SIGNAL(foundFrameEnd(ApiTraceFrame*)),
784             this, SLOT(slotFoundFrameEnd(ApiTraceFrame*)));
785     connect(m_trace, SIGNAL(foundCallIndex(ApiTraceCall*)),
786             this, SLOT(slotJumpToResult(ApiTraceCall*)));
787
788     connect(m_retracer, SIGNAL(finished(const QString&)),
789             this, SLOT(replayFinished(const QString&)));
790     connect(m_retracer, SIGNAL(error(const QString&)),
791             this, SLOT(replayError(const QString&)));
792     connect(m_retracer, SIGNAL(foundState(ApiTraceState*)),
793             this, SLOT(replayStateFound(ApiTraceState*)));
794     connect(m_retracer, SIGNAL(foundThumbnails(const QList<QImage>&)),
795             this, SLOT(replayThumbnailsFound(const QList<QImage>&)));
796     connect(m_retracer, SIGNAL(retraceErrors(const QList<ApiTraceError>&)),
797             this, SLOT(slotRetraceErrors(const QList<ApiTraceError>&)));
798
799     connect(m_ui.vertexInterpretButton, SIGNAL(clicked()),
800             m_vdataInterpreter, SLOT(interpretData()));
801     connect(m_ui.vertexTypeCB, SIGNAL(currentIndexChanged(const QString&)),
802             m_vdataInterpreter, SLOT(setTypeFromString(const QString&)));
803     connect(m_ui.vertexStrideSB, SIGNAL(valueChanged(int)),
804             m_vdataInterpreter, SLOT(setStride(int)));
805     connect(m_ui.vertexComponentsSB, SIGNAL(valueChanged(int)),
806             m_vdataInterpreter, SLOT(setComponents(int)));
807     connect(m_ui.startingOffsetSB, SIGNAL(valueChanged(int)),
808             m_vdataInterpreter, SLOT(setStartingOffset(int)));
809
810
811     connect(m_ui.actionNew, SIGNAL(triggered()),
812             this, SLOT(createTrace()));
813     connect(m_ui.actionOpen, SIGNAL(triggered()),
814             this, SLOT(openTrace()));
815     connect(m_ui.actionQuit, SIGNAL(triggered()),
816             this, SLOT(close()));
817
818     connect(m_ui.actionFind, SIGNAL(triggered()),
819             this, SLOT(slotSearch()));
820     connect(m_ui.actionGo, SIGNAL(triggered()),
821             this, SLOT(slotGoTo()));
822     connect(m_ui.actionGoFrameStart, SIGNAL(triggered()),
823             this, SLOT(slotGoFrameStart()));
824     connect(m_ui.actionGoFrameEnd, SIGNAL(triggered()),
825             this, SLOT(slotGoFrameEnd()));
826
827     connect(m_ui.actionReplay, SIGNAL(triggered()),
828             this, SLOT(replayStart()));
829     connect(m_ui.actionStop, SIGNAL(triggered()),
830             this, SLOT(replayStop()));
831     connect(m_ui.actionLookupState, SIGNAL(triggered()),
832             this, SLOT(lookupState()));
833     connect(m_ui.actionTrim, SIGNAL(triggered()),
834             this, SLOT(trim()));
835     connect(m_ui.actionShowThumbnails, SIGNAL(triggered()),
836             this, SLOT(showThumbnails()));
837     connect(m_ui.actionOptions, SIGNAL(triggered()),
838             this, SLOT(showSettings()));
839
840     connect(m_ui.callView->selectionModel(), SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)),
841             this, SLOT(callItemSelected(const QModelIndex &)));
842     connect(m_ui.callView, SIGNAL(doubleClicked(const QModelIndex &)),
843             this, SLOT(callItemActivated(const QModelIndex &)));
844     connect(m_ui.callView, SIGNAL(customContextMenuRequested(QPoint)),
845             this, SLOT(customContextMenuRequested(QPoint)));
846
847     connect(m_ui.surfacesTreeWidget,
848             SIGNAL(customContextMenuRequested(const QPoint &)),
849             SLOT(showSurfacesMenu(const QPoint &)));
850     connect(m_ui.surfacesTreeWidget,
851             SIGNAL(itemDoubleClicked(QTreeWidgetItem *, int)),
852             SLOT(showSelectedSurface()));
853
854     connect(m_ui.detailsWebView, SIGNAL(linkClicked(const QUrl&)),
855             this, SLOT(openHelp(const QUrl&)));
856
857     connect(m_ui.nonDefaultsCB, SIGNAL(toggled(bool)),
858             this, SLOT(fillState(bool)));
859
860     connect(m_jumpWidget, SIGNAL(jumpTo(int)),
861             SLOT(slotJumpTo(int)));
862
863     connect(m_searchWidget,
864             SIGNAL(searchNext(const QString&, Qt::CaseSensitivity)),
865             SLOT(slotSearchNext(const QString&, Qt::CaseSensitivity)));
866     connect(m_searchWidget,
867             SIGNAL(searchPrev(const QString&, Qt::CaseSensitivity)),
868             SLOT(slotSearchPrev(const QString&, Qt::CaseSensitivity)));
869
870     connect(m_traceProcess, SIGNAL(tracedFile(const QString&)),
871             SLOT(createdTrace(const QString&)));
872     connect(m_traceProcess, SIGNAL(error(const QString&)),
873             SLOT(traceError(const QString&)));
874
875     connect(m_trimProcess, SIGNAL(trimmedFile(const QString&)),
876             SLOT(createdTrim(const QString&)));
877     connect(m_trimProcess, SIGNAL(error(const QString&)),
878             SLOT(trimError(const QString&)));
879
880     connect(m_ui.errorsDock, SIGNAL(visibilityChanged(bool)),
881             m_ui.actionShowErrorsDock, SLOT(setChecked(bool)));
882     connect(m_ui.actionShowErrorsDock, SIGNAL(triggered(bool)),
883             m_ui.errorsDock, SLOT(setVisible(bool)));
884     connect(m_ui.errorsTreeWidget,
885             SIGNAL(itemActivated(QTreeWidgetItem*, int)),
886             this, SLOT(slotErrorSelected(QTreeWidgetItem*)));
887 }
888
889 void MainWindow::replayStateFound(ApiTraceState *state)
890 {
891     m_stateEvent->setState(state);
892     m_model->stateSetOnEvent(m_stateEvent);
893     if (m_selectedEvent == m_stateEvent ||
894         m_nonDefaultsLookupEvent == m_selectedEvent) {
895         fillStateForFrame();
896     } else {
897         m_ui.stateDock->hide();
898     }
899     m_nonDefaultsLookupEvent = 0;
900 }
901
902 void MainWindow::replayThumbnailsFound(const QList<QImage> &thumbnails)
903 {
904     m_ui.callView->setUniformRowHeights(false);
905     m_trace->bindThumbnailsToFrames(thumbnails);
906 }
907
908 void MainWindow::slotGoTo()
909 {
910     m_searchWidget->hide();
911     m_jumpWidget->show();
912 }
913
914 void MainWindow::slotJumpTo(int callNum)
915 {
916     m_trace->findCallIndex(callNum);
917 }
918
919 void MainWindow::createdTrace(const QString &path)
920 {
921     qDebug()<<"Done tracing "<<path;
922     newTraceFile(path);
923 }
924
925 void MainWindow::traceError(const QString &msg)
926 {
927     QMessageBox::warning(
928             this,
929             tr("Tracing Error"),
930             msg);
931 }
932
933 void MainWindow::createdTrim(const QString &path)
934 {
935     qDebug()<<"Done trimming "<<path;
936
937     newTraceFile(path);
938 }
939
940 void MainWindow::trimError(const QString &msg)
941 {
942     QMessageBox::warning(
943             this,
944             tr("Trim Error"),
945             msg);
946 }
947
948 void MainWindow::slotSearch()
949 {
950     m_jumpWidget->hide();
951     m_searchWidget->show();
952 }
953
954 void MainWindow::slotSearchNext(const QString &str,
955                                 Qt::CaseSensitivity sensitivity)
956 {
957     ApiTraceCall *call = currentCall();
958     ApiTraceFrame *frame = currentFrame();
959
960     Q_ASSERT(call || frame);
961     if (!frame) {
962         frame = call->parentFrame();
963     }
964     Q_ASSERT(frame);
965
966     m_trace->findNext(frame, call, str, sensitivity);
967 }
968
969 void MainWindow::slotSearchPrev(const QString &str,
970                                 Qt::CaseSensitivity sensitivity)
971 {
972     ApiTraceCall *call = currentCall();
973     ApiTraceFrame *frame = currentFrame();
974
975     Q_ASSERT(call || frame);
976     if (!frame) {
977         frame = call->parentFrame();
978     }
979     Q_ASSERT(frame);
980
981     m_trace->findPrev(frame, call, str, sensitivity);
982 }
983
984 void MainWindow::fillState(bool nonDefaults)
985 {
986     if (nonDefaults) {
987         ApiTraceState defaultState = m_trace->defaultState();
988         if (defaultState.isEmpty()) {
989             m_ui.nonDefaultsCB->blockSignals(true);
990             m_ui.nonDefaultsCB->setChecked(false);
991             m_ui.nonDefaultsCB->blockSignals(false);
992             ApiTraceFrame *firstFrame =
993                 m_trace->frameAt(0);
994             if (!firstFrame) {
995                 return;
996             }
997             if (!firstFrame->isLoaded()) {
998                 m_trace->loadFrame(firstFrame);
999                 return;
1000             }
1001             ApiTraceCall *firstCall = firstFrame->calls().first();
1002             ApiTraceEvent *oldSelected = m_selectedEvent;
1003             m_nonDefaultsLookupEvent = m_selectedEvent;
1004             m_selectedEvent = firstCall;
1005             lookupState();
1006             m_selectedEvent = oldSelected;
1007         }
1008     }
1009     fillStateForFrame();
1010 }
1011
1012 void MainWindow::customContextMenuRequested(QPoint pos)
1013 {
1014     QModelIndex index = m_ui.callView->indexAt(pos);
1015
1016     callItemSelected(index);
1017     if (!index.isValid()) {
1018         return;
1019     }
1020
1021     ApiTraceEvent *event =
1022         index.data(ApiTraceModel::EventRole).value<ApiTraceEvent*>();
1023     if (!event) {
1024         return;
1025     }
1026
1027     QMenu menu;
1028     menu.addAction(QIcon(":/resources/media-record.png"),
1029                    tr("Lookup state"), this, SLOT(lookupState()));
1030     if (event->type() == ApiTraceEvent::Call) {
1031         menu.addAction(tr("Edit"), this, SLOT(editCall()));
1032     }
1033
1034     menu.exec(QCursor::pos());
1035 }
1036
1037 void MainWindow::editCall()
1038 {
1039     if (m_selectedEvent && m_selectedEvent->type() == ApiTraceEvent::Call) {
1040         ApiTraceCall *call = static_cast<ApiTraceCall*>(m_selectedEvent);
1041         m_argsEditor->setCall(call);
1042         m_argsEditor->show();
1043     }
1044 }
1045
1046 void MainWindow::slotStartedSaving()
1047 {
1048     m_progressBar->show();
1049     statusBar()->showMessage(
1050         tr("Saving to %1").arg(m_trace->fileName()));
1051 }
1052
1053 void MainWindow::slotSaved()
1054 {
1055     statusBar()->showMessage(
1056         tr("Saved to %1").arg(m_trace->fileName()), 2000);
1057     m_progressBar->hide();
1058 }
1059
1060 void MainWindow::slotGoFrameStart()
1061 {
1062     ApiTraceFrame *frame = currentFrame();
1063     ApiTraceCall *call = currentCall();
1064
1065     if (!frame && call) {
1066         frame = call->parentFrame();
1067     }
1068
1069     m_trace->findFrameStart(frame);
1070 }
1071
1072 void MainWindow::slotGoFrameEnd()
1073 {
1074     ApiTraceFrame *frame = currentFrame();
1075     ApiTraceCall *call = currentCall();
1076
1077     if (!frame && call) {
1078         frame = call->parentFrame();
1079     }
1080
1081     m_trace->findFrameEnd(frame);
1082 }
1083
1084 ApiTraceFrame * MainWindow::selectedFrame() const
1085 {
1086     if (m_selectedEvent) {
1087         if (m_selectedEvent->type() == ApiTraceEvent::Frame) {
1088             return static_cast<ApiTraceFrame*>(m_selectedEvent);
1089         } else {
1090             Q_ASSERT(m_selectedEvent->type() == ApiTraceEvent::Call);
1091             ApiTraceCall *call = static_cast<ApiTraceCall*>(m_selectedEvent);
1092             return call->parentFrame();
1093         }
1094     }
1095     return NULL;
1096 }
1097
1098 void MainWindow::slotTraceChanged(ApiTraceEvent *event)
1099 {
1100     Q_ASSERT(event);
1101     if (event == m_selectedEvent) {
1102         if (event->type() == ApiTraceEvent::Call) {
1103             ApiTraceCall *call = static_cast<ApiTraceCall*>(event);
1104             m_ui.detailsWebView->setHtml(call->toHtml());
1105         }
1106     }
1107 }
1108
1109 void MainWindow::slotRetraceErrors(const QList<ApiTraceError> &errors)
1110 {
1111     m_ui.errorsTreeWidget->clear();
1112
1113     foreach(ApiTraceError error, errors) {
1114         m_trace->setCallError(error);
1115
1116         QTreeWidgetItem *item =
1117             new QTreeWidgetItem(m_ui.errorsTreeWidget);
1118         item->setData(0, Qt::DisplayRole, error.callIndex);
1119         item->setData(0, Qt::UserRole, error.callIndex);
1120         QString type = error.type;
1121         type[0] = type[0].toUpper();
1122         item->setData(1, Qt::DisplayRole, type);
1123         item->setData(2, Qt::DisplayRole, error.message);
1124     }
1125 }
1126
1127 void MainWindow::slotErrorSelected(QTreeWidgetItem *current)
1128 {
1129     if (current) {
1130         int callIndex =
1131             current->data(0, Qt::UserRole).toInt();
1132         m_trace->findCallIndex(callIndex);
1133     }
1134 }
1135
1136 ApiTraceCall * MainWindow::selectedCall() const
1137 {
1138     if (m_selectedEvent &&
1139         m_selectedEvent->type() == ApiTraceEvent::Call) {
1140         return static_cast<ApiTraceCall*>(m_selectedEvent);
1141     }
1142     return NULL;
1143 }
1144
1145 void MainWindow::saveSelectedSurface()
1146 {
1147     QTreeWidgetItem *item =
1148         m_ui.surfacesTreeWidget->currentItem();
1149
1150     if (!item || !m_trace) {
1151         return;
1152     }
1153
1154     QVariant var = item->data(0, Qt::UserRole);
1155     QImage img = var.value<QImage>();
1156
1157     QString imageIndex;
1158     if (selectedCall()) {
1159         imageIndex = tr("_call_%1")
1160                      .arg(selectedCall()->index());
1161     } else if (selectedFrame()) {
1162         ApiTraceCall *firstCall = selectedFrame()->call(0);
1163         if (firstCall) {
1164             imageIndex = tr("_frame_%1")
1165                          .arg(firstCall->index());
1166         } else {
1167             qDebug()<<"unknown frame number";
1168             imageIndex = tr("_frame_%1")
1169                          .arg(firstCall->index());
1170         }
1171     }
1172
1173     //which of the surfaces are we saving
1174     QTreeWidgetItem *parent = item->parent();
1175     int parentIndex =
1176         m_ui.surfacesTreeWidget->indexOfTopLevelItem(parent);
1177     if (parentIndex < 0) {
1178         parentIndex = 0;
1179     }
1180     int childIndex = 0;
1181     if (parent) {
1182         childIndex = parent->indexOfChild(item);
1183     } else {
1184         childIndex = m_ui.surfacesTreeWidget->indexOfTopLevelItem(item);
1185     }
1186
1187
1188     QString fileName =
1189         tr("%1%2-%3_%4.png")
1190         .arg(m_trace->fileName())
1191         .arg(imageIndex)
1192         .arg(parentIndex)
1193         .arg(childIndex);
1194     //qDebug()<<"save "<<fileName;
1195     img.save(fileName, "PNG");
1196     statusBar()->showMessage( tr("Saved '%1'").arg(fileName), 5000);
1197 }
1198
1199 void MainWindow::loadProgess(int percent)
1200 {
1201     m_progressBar->setValue(percent);
1202 }
1203
1204 void MainWindow::slotSearchResult(const ApiTrace::SearchRequest &request,
1205                                   ApiTrace::SearchResult result,
1206                                   ApiTraceCall *call)
1207 {
1208     switch (result) {
1209     case ApiTrace::SearchResult_NotFound:
1210         m_searchWidget->setFound(false);
1211         break;
1212     case ApiTrace::SearchResult_Found: {
1213         QModelIndex index = m_proxyModel->indexForCall(call);
1214
1215         if (index.isValid()) {
1216             m_ui.callView->setCurrentIndex(index);
1217             m_searchWidget->setFound(true);
1218         } else {
1219             //call is filtered out, so continue searching but from the
1220             // filtered call
1221             if (!call) {
1222                 qDebug()<<"Error: search success with no call";
1223                 return;
1224             }
1225 //            qDebug()<<"filtered! search from "<<call->searchText()
1226 //                   <<", call idx = "<<call->index();
1227
1228             if (request.direction == ApiTrace::SearchRequest::Next) {
1229                 m_trace->findNext(call->parentFrame(), call,
1230                                   request.text, request.cs);
1231             } else {
1232                 m_trace->findNext(call->parentFrame(), call,
1233                                   request.text, request.cs);
1234             }
1235         }
1236     }
1237         break;
1238     case ApiTrace::SearchResult_Wrapped:
1239         m_searchWidget->setFound(false);
1240         break;
1241     }
1242 }
1243
1244 ApiTraceFrame * MainWindow::currentFrame() const
1245 {
1246     QModelIndex index = m_ui.callView->currentIndex();
1247     ApiTraceEvent *event = 0;
1248
1249     if (!index.isValid()) {
1250         index = m_proxyModel->index(0, 0, QModelIndex());
1251         if (!index.isValid()) {
1252             qDebug()<<"no currently valid index";
1253             return 0;
1254         }
1255     }
1256
1257     event = index.data(ApiTraceModel::EventRole).value<ApiTraceEvent*>();
1258     Q_ASSERT(event);
1259     if (!event) {
1260         return 0;
1261     }
1262
1263     ApiTraceFrame *frame = 0;
1264     if (event->type() == ApiTraceCall::Frame) {
1265         frame = static_cast<ApiTraceFrame*>(event);
1266     }
1267     return frame;
1268 }
1269
1270 ApiTraceCall * MainWindow::currentCall() const
1271 {
1272     QModelIndex index = m_ui.callView->currentIndex();
1273     ApiTraceEvent *event = 0;
1274
1275     if (!index.isValid()) {
1276         index = m_proxyModel->index(0, 0, QModelIndex());
1277         if (!index.isValid()) {
1278             qDebug()<<"no currently valid index";
1279             return 0;
1280         }
1281     }
1282
1283     event = index.data(ApiTraceModel::EventRole).value<ApiTraceEvent*>();
1284     Q_ASSERT(event);
1285     if (!event) {
1286         return 0;
1287     }
1288
1289     ApiTraceCall *call = 0;
1290     if (event->type() == ApiTraceCall::Call) {
1291         call = static_cast<ApiTraceCall*>(event);
1292     }
1293
1294     return call;
1295
1296 }
1297
1298 void MainWindow::slotFoundFrameStart(ApiTraceFrame *frame)
1299 {
1300     Q_ASSERT(frame->isLoaded());
1301     if (!frame || frame->isEmpty()) {
1302         return;
1303     }
1304
1305     QVector<ApiTraceCall*>::const_iterator itr;
1306     QVector<ApiTraceCall*> calls = frame->calls();
1307
1308     itr = calls.constBegin();
1309     while (itr != calls.constEnd()) {
1310         ApiTraceCall *call = *itr;
1311         QModelIndex idx = m_proxyModel->indexForCall(call);
1312         if (idx.isValid()) {
1313             m_ui.callView->setCurrentIndex(idx);
1314             break;
1315         }
1316         ++itr;
1317     }
1318 }
1319
1320 void MainWindow::slotFoundFrameEnd(ApiTraceFrame *frame)
1321 {
1322     Q_ASSERT(frame->isLoaded());
1323     if (!frame || frame->isEmpty()) {
1324         return;
1325     }
1326     QVector<ApiTraceCall*>::const_iterator itr;
1327     QVector<ApiTraceCall*> calls = frame->calls();
1328
1329     itr = calls.constEnd();
1330     do {
1331         --itr;
1332         ApiTraceCall *call = *itr;
1333         QModelIndex idx = m_proxyModel->indexForCall(call);
1334         if (idx.isValid()) {
1335             m_ui.callView->setCurrentIndex(idx);
1336             break;
1337         }
1338     } while (itr != calls.constBegin());
1339 }
1340
1341 void MainWindow::slotJumpToResult(ApiTraceCall *call)
1342 {
1343     QModelIndex index = m_proxyModel->indexForCall(call);
1344     if (index.isValid()) {
1345         m_ui.callView->setCurrentIndex(index);
1346     } else {
1347         statusBar()->showMessage(tr("Call has been filtered out."));
1348     }
1349 }
1350
1351 #include "mainwindow.moc"