]> git.cworth.org Git - apitrace/blob - gui/mainwindow.cpp
Various cleanups.
[apitrace] / gui / mainwindow.cpp
1 #include "mainwindow.h"
2
3 #include "apitrace.h"
4 #include "apitracecall.h"
5 #include "apicalldelegate.h"
6 #include "apitracemodel.h"
7 #include "apitracefilter.h"
8 #include "argumentseditor.h"
9 #include "imageviewer.h"
10 #include "jumpwidget.h"
11 #include "retracer.h"
12 #include "searchwidget.h"
13 #include "settingsdialog.h"
14 #include "shaderssourcewidget.h"
15 #include "tracedialog.h"
16 #include "traceprocess.h"
17 #include "ui_retracerdialog.h"
18 #include "vertexdatainterpreter.h"
19
20 #include <QAction>
21 #include <QDebug>
22 #include <QDesktopServices>
23 #include <QDir>
24 #include <QFileDialog>
25 #include <QLineEdit>
26 #include <QMessageBox>
27 #include <QProgressBar>
28 #include <QToolBar>
29 #include <QUrl>
30 #include <QVBoxLayout>
31 #include <QWebPage>
32 #include <QWebView>
33
34
35 MainWindow::MainWindow()
36     : QMainWindow(),
37       m_selectedEvent(0),
38       m_stateEvent(0)
39 {
40     m_ui.setupUi(this);
41     initObjects();
42     initConnections();
43 }
44
45 void MainWindow::createTrace()
46 {
47     TraceDialog dialog;
48
49     if (!m_traceProcess->canTrace()) {
50         QMessageBox::warning(
51             this,
52             tr("Unsupported"),
53             tr("Current configuration doesn't support tracing."));
54         return;
55     }
56
57     if (dialog.exec() == QDialog::Accepted) {
58         qDebug()<< "App : " <<dialog.applicationPath();
59         qDebug()<< "  Arguments: "<<dialog.arguments();
60         m_traceProcess->setExecutablePath(dialog.applicationPath());
61         m_traceProcess->setArguments(dialog.arguments());
62         m_traceProcess->start();
63     }
64 }
65
66 void MainWindow::openTrace()
67 {
68     QString fileName =
69         QFileDialog::getOpenFileName(
70             this,
71             tr("Open Trace"),
72             QDir::homePath(),
73             tr("Trace Files (*.trace)"));
74
75     qDebug()<< "File name : " <<fileName;
76
77     newTraceFile(fileName);
78 }
79
80 void MainWindow::loadTrace(const QString &fileName)
81 {
82     if (!QFile::exists(fileName)) {
83         QMessageBox::warning(this, tr("File Missing"),
84                              tr("File '%1' doesn't exist.").arg(fileName));
85         return;
86     }
87     qDebug()<< "Loading  : " <<fileName;
88
89     m_progressBar->setValue(0);
90     newTraceFile(fileName);
91 }
92
93 void MainWindow::callItemSelected(const QModelIndex &index)
94 {
95     ApiTraceEvent *event =
96         index.data(ApiTraceModel::EventRole).value<ApiTraceEvent*>();
97
98     if (event && event->type() == ApiTraceEvent::Call) {
99         ApiTraceCall *call = static_cast<ApiTraceCall*>(event);
100         m_ui.detailsWebView->setHtml(call->toHtml());
101         m_ui.detailsDock->show();
102         if (call->hasBinaryData()) {
103             QByteArray data =
104                 call->arguments()[call->binaryDataIndex()].toByteArray();
105             m_vdataInterpreter->setData(data);
106             QVariantList args = call->arguments();
107
108             for (int i = 0; i < call->argNames().count(); ++i) {
109                 QString name = call->argNames()[i];
110                 if (name == QLatin1String("stride")) {
111                     int stride = args[i].toInt();
112                     m_ui.vertexStrideSB->setValue(stride);
113                 } else if (name == QLatin1String("size")) {
114                     int components = args[i].toInt();
115                     m_ui.vertexComponentsSB->setValue(components);
116                 } else if (name == QLatin1String("type")) {
117                     QString val = args[i].toString();
118                     int textIndex = m_ui.vertexTypeCB->findText(val);
119                     if (textIndex >= 0)
120                         m_ui.vertexTypeCB->setCurrentIndex(textIndex);
121                 }
122             }
123         }
124         m_ui.vertexDataDock->setVisible(call->hasBinaryData());
125         m_selectedEvent = call;
126     } else {
127         if (event && event->type() == ApiTraceEvent::Frame) {
128             m_selectedEvent = static_cast<ApiTraceFrame*>(event);
129         } else
130             m_selectedEvent = 0;
131         m_ui.detailsDock->hide();
132         m_ui.vertexDataDock->hide();
133     }
134     if (m_selectedEvent && !m_selectedEvent->state().isEmpty()) {
135         fillStateForFrame();
136     } else
137         m_ui.stateDock->hide();
138 }
139
140 void MainWindow::replayStart()
141 {
142     if (m_trace->isSaving()) {
143         QMessageBox::warning(
144             this,
145             tr("Trace Saving"),
146             tr("QApiTrace is currently saving the edited trace file. "
147                "Please wait until it finishes and try again."));
148         return;
149     }
150     QDialog dlg;
151     Ui_RetracerDialog dlgUi;
152     dlgUi.setupUi(&dlg);
153
154     dlgUi.doubleBufferingCB->setChecked(
155         m_retracer->isDoubleBuffered());
156     dlgUi.errorCheckCB->setChecked(
157         !m_retracer->isBenchmarking());
158
159     if (dlg.exec() == QDialog::Accepted) {
160         m_retracer->setDoubleBuffered(
161             dlgUi.doubleBufferingCB->isChecked());
162         m_retracer->setBenchmarking(
163             !dlgUi.errorCheckCB->isChecked());
164         replayTrace(false);
165     }
166 }
167
168 void MainWindow::replayStop()
169 {
170     m_retracer->quit();
171     m_ui.actionStop->setEnabled(false);
172     m_ui.actionReplay->setEnabled(true);
173     m_ui.actionLookupState->setEnabled(true);
174 }
175
176 void MainWindow::newTraceFile(const QString &fileName)
177 {
178     m_trace->setFileName(fileName);
179
180     if (fileName.isEmpty()) {
181         m_ui.actionReplay->setEnabled(false);
182         m_ui.actionLookupState->setEnabled(false);
183         setWindowTitle(tr("QApiTrace"));
184     } else {
185         QFileInfo info(fileName);
186         m_ui.actionReplay->setEnabled(true);
187         m_ui.actionLookupState->setEnabled(true);
188         setWindowTitle(
189             tr("QApiTrace - %1").arg(info.fileName()));
190     }
191 }
192
193 void MainWindow::replayFinished(const QString &output)
194 {
195     m_ui.actionStop->setEnabled(false);
196     m_ui.actionReplay->setEnabled(true);
197     m_ui.actionLookupState->setEnabled(true);
198
199     m_progressBar->hide();
200     if (output.length() < 80) {
201         statusBar()->showMessage(output);
202     }
203     m_stateEvent = 0;
204     m_ui.actionShowErrorsDock->setEnabled(m_trace->hasErrors());
205     m_ui.errorsDock->setVisible(m_trace->hasErrors());
206     if (!m_trace->hasErrors())
207         m_ui.errorsTreeWidget->clear();
208
209     statusBar()->showMessage(
210         tr("Replaying finished!"), 2000);
211 }
212
213 void MainWindow::replayError(const QString &message)
214 {
215     m_ui.actionStop->setEnabled(false);
216     m_ui.actionReplay->setEnabled(true);
217     m_ui.actionLookupState->setEnabled(true);
218     m_stateEvent = 0;
219
220     m_progressBar->hide();
221     statusBar()->showMessage(
222         tr("Replaying unsuccessful."), 2000);
223     QMessageBox::warning(
224         this, tr("Replay Failed"), message);
225 }
226
227 void MainWindow::startedLoadingTrace()
228 {
229     Q_ASSERT(m_trace);
230     m_progressBar->show();
231     QFileInfo info(m_trace->fileName());
232     statusBar()->showMessage(
233         tr("Loading %1...").arg(info.fileName()));
234 }
235
236 void MainWindow::finishedLoadingTrace()
237 {
238     m_progressBar->hide();
239     if (!m_trace) {
240         return;
241     }
242     QFileInfo info(m_trace->fileName());
243     statusBar()->showMessage(
244         tr("Loaded %1").arg(info.fileName()), 3000);
245 }
246
247 void MainWindow::replayTrace(bool dumpState)
248 {
249     if (m_trace->fileName().isEmpty())
250         return;
251
252     m_retracer->setFileName(m_trace->fileName());
253     m_retracer->setCaptureState(dumpState);
254     if (m_retracer->captureState() && m_selectedEvent) {
255         int index = 0;
256         if (m_selectedEvent->type() == ApiTraceEvent::Call) {
257             index = static_cast<ApiTraceCall*>(m_selectedEvent)->index();
258         } else if (m_selectedEvent->type() == ApiTraceEvent::Frame) {
259             ApiTraceFrame *frame =
260                 static_cast<ApiTraceFrame*>(m_selectedEvent);
261             if (frame->calls.isEmpty()) {
262                 //XXX i guess we could still get the current state
263                 qDebug()<<"tried to get a state for an empty frame";
264                 return;
265             }
266             index = frame->calls.first()->index();
267         } else {
268             qDebug()<<"Unknown event type";
269             return;
270         }
271         m_retracer->setCaptureAtCallNumber(index);
272     }
273     m_retracer->start();
274
275     m_ui.actionStop->setEnabled(true);
276     m_progressBar->show();
277     if (dumpState)
278         statusBar()->showMessage(
279             tr("Looking up the state..."));
280     else
281         statusBar()->showMessage(
282             tr("Replaying the trace file..."));
283 }
284
285 void MainWindow::lookupState()
286 {
287     if (!m_selectedEvent) {
288         QMessageBox::warning(
289             this, tr("Unknown Event"),
290             tr("To inspect the state select an event in the event list."));
291         return;
292     }
293     if (m_trace->isSaving()) {
294         QMessageBox::warning(
295             this,
296             tr("Trace Saving"),
297             tr("QApiTrace is currently saving the edited trace file. "
298                "Please wait until it finishes and try again."));
299         return;
300     }
301     m_stateEvent = m_selectedEvent;
302     replayTrace(true);
303 }
304
305 MainWindow::~MainWindow()
306 {
307 }
308
309 static void
310 variantToString(const QVariant &var, QString &str)
311 {
312     if (var.type() == QVariant::List) {
313         QVariantList lst = var.toList();
314         str += QLatin1String("[");
315         for (int i = 0; i < lst.count(); ++i) {
316             QVariant val = lst[i];
317             variantToString(val, str);
318             if (i < lst.count() - 1)
319                 str += QLatin1String(", ");
320         }
321         str += QLatin1String("]");
322     } else if (var.type() == QVariant::Map) {
323         Q_ASSERT(!"unsupported state type");
324     } else if (var.type() == QVariant::Hash) {
325         Q_ASSERT(!"unsupported state type");
326     } else {
327         str += var.toString();
328     }
329 }
330
331 static QTreeWidgetItem *
332 variantToItem(const QString &key, const QVariant &var, const QVariant &defaultVar);
333
334 static void
335 variantMapToItems(const QVariantMap &map, const QVariantMap &defaultMap, QList<QTreeWidgetItem *> &items)
336 {
337     QVariantMap::const_iterator itr;
338     for (itr = map.constBegin(); itr != map.constEnd(); ++itr) {
339         QString key = itr.key();
340         QVariant var = itr.value();
341         QVariant defaultVar = defaultMap[key];
342
343         QTreeWidgetItem *item = variantToItem(key, var, defaultVar);
344         if (item) {
345             items.append(item);
346         }
347     }
348 }
349
350 static void
351 variantListToItems(const QVariantList &lst, const QVariantList &defaultLst, QList<QTreeWidgetItem *> &items)
352 {
353     for (int i = 0; i < lst.count(); ++i) {
354         QString key = QString::number(i);
355         QVariant var = lst[i];
356         QVariant defaultVar;
357         
358         if (i < defaultLst.count()) {
359             defaultVar = defaultLst[i];
360         }
361
362         QTreeWidgetItem *item = variantToItem(key, var, defaultVar);
363         if (item) {
364             items.append(item);
365         }
366     }
367 }
368
369 static bool
370 isVariantDeep(const QVariant &var)
371 {
372     if (var.type() == QVariant::List) {
373         QVariantList lst = var.toList();
374         for (int i = 0; i < lst.count(); ++i) {
375             if (isVariantDeep(lst[i])) {
376                 return true;
377             }
378         }
379         return false;
380     } else if (var.type() == QVariant::Map) {
381         return true;
382     } else if (var.type() == QVariant::Hash) {
383         return true;
384     } else {
385         return false;
386     }
387 }
388
389 static QTreeWidgetItem *
390 variantToItem(const QString &key, const QVariant &var, const QVariant &defaultVar)
391 {
392     if (var == defaultVar) {
393         return NULL;
394     }
395
396     QString val;
397
398     bool deep = isVariantDeep(var);
399     if (!deep) {
400         variantToString(var, val);
401     }
402
403     //qDebug()<<"key = "<<key;
404     //qDebug()<<"val = "<<val;
405     QStringList lst;
406     lst += key;
407     lst += val;
408
409     QTreeWidgetItem *item = new QTreeWidgetItem((QTreeWidgetItem *)0, lst);
410
411     if (deep) {
412         QList<QTreeWidgetItem *> children;
413         if (var.type() == QVariant::Map) {
414             QVariantMap map = var.toMap();
415             QVariantMap defaultMap = defaultVar.toMap();
416             variantMapToItems(map, defaultMap, children);
417         }
418         if (var.type() == QVariant::List) {
419             QVariantList lst = var.toList();
420             QVariantList defaultLst = defaultVar.toList();
421             variantListToItems(lst, defaultLst, children);
422         }
423         item->addChildren(children);
424     }
425
426     return item;
427 }
428
429 void MainWindow::fillStateForFrame()
430 {
431     QVariantMap params;
432
433     if (!m_selectedEvent || m_selectedEvent->state().isEmpty())
434         return;
435
436     bool nonDefaults = m_ui.nonDefaultsCB->isChecked();
437     QVariantMap defaultParams;
438     if (nonDefaults) {
439         ApiTraceState defaultState = m_trace->defaultState();
440         defaultParams = defaultState.parameters();
441     }
442
443     const ApiTraceState &state = m_selectedEvent->state();
444     m_ui.stateTreeWidget->clear();
445     params = state.parameters();
446     QList<QTreeWidgetItem *> items;
447     variantMapToItems(params, defaultParams, items);
448     m_ui.stateTreeWidget->insertTopLevelItems(0, items);
449
450     QMap<QString, QString> shaderSources = state.shaderSources();
451     if (shaderSources.isEmpty()) {
452         m_sourcesWidget->setShaders(shaderSources);
453     } else {
454         m_sourcesWidget->setShaders(shaderSources);
455     }
456
457     const QList<ApiTexture> &textures =
458         state.textures();
459     const QList<ApiFramebuffer> &fbos =
460         state.framebuffers();
461
462     m_ui.surfacesTreeWidget->clear();
463     if (textures.isEmpty() && fbos.isEmpty()) {
464         m_ui.surfacesTab->setDisabled(false);
465     } else {
466         m_ui.surfacesTreeWidget->setIconSize(QSize(64, 64));
467         if (!textures.isEmpty()) {
468             QTreeWidgetItem *textureItem =
469                 new QTreeWidgetItem(m_ui.surfacesTreeWidget);
470             textureItem->setText(0, tr("Textures"));
471             if (textures.count() <= 6)
472                 textureItem->setExpanded(true);
473
474             for (int i = 0; i < textures.count(); ++i) {
475                 const ApiTexture &texture =
476                     textures[i];
477                 QIcon icon(QPixmap::fromImage(texture.thumb()));
478                 QTreeWidgetItem *item = new QTreeWidgetItem(textureItem);
479                 item->setIcon(0, icon);
480                 int width = texture.size().width();
481                 int height = texture.size().height();
482                 QString descr =
483                     QString::fromLatin1("%1, %2 x %3")
484                     .arg(texture.target())
485                     .arg(width)
486                     .arg(height);
487                 item->setText(1, descr);
488
489                 item->setData(0, Qt::UserRole,
490                               texture.image());
491             }
492         }
493         if (!fbos.isEmpty()) {
494             QTreeWidgetItem *fboItem =
495                 new QTreeWidgetItem(m_ui.surfacesTreeWidget);
496             fboItem->setText(0, tr("Framebuffers"));
497             if (fbos.count() <= 6)
498                 fboItem->setExpanded(true);
499
500             for (int i = 0; i < fbos.count(); ++i) {
501                 const ApiFramebuffer &fbo =
502                     fbos[i];
503                 QIcon icon(QPixmap::fromImage(fbo.thumb()));
504                 QTreeWidgetItem *item = new QTreeWidgetItem(fboItem);
505                 item->setIcon(0, icon);
506                 int width = fbo.size().width();
507                 int height = fbo.size().height();
508                 QString descr =
509                     QString::fromLatin1("%1, %2 x %3")
510                     .arg(fbo.type())
511                     .arg(width)
512                     .arg(height);
513                 item->setText(1, descr);
514
515                 item->setData(0, Qt::UserRole,
516                               fbo.image());
517             }
518         }
519         m_ui.surfacesTab->setEnabled(true);
520     }
521     m_ui.stateDock->show();
522 }
523
524 void MainWindow::showSettings()
525 {
526     SettingsDialog dialog;
527     dialog.setFilterModel(m_proxyModel);
528
529     dialog.exec();
530 }
531
532 void MainWindow::openHelp(const QUrl &url)
533 {
534     QDesktopServices::openUrl(url);
535 }
536
537 void MainWindow::showSurfacesMenu(const QPoint &pos)
538 {
539     QTreeWidget *tree = m_ui.surfacesTreeWidget;
540     QTreeWidgetItem *item = tree->itemAt(pos);
541     if (!item)
542         return;
543
544     QMenu menu(tr("Surfaces"), this);
545     //add needed actions
546     QAction *act = menu.addAction(tr("View Image"));
547     act->setStatusTip(tr("View the currently selected surface"));
548     connect(act, SIGNAL(triggered()),
549             SLOT(showSelectedSurface()));
550
551     menu.exec(tree->viewport()->mapToGlobal(pos));
552 }
553
554 void MainWindow::showSelectedSurface()
555 {
556     QTreeWidgetItem *item =
557         m_ui.surfacesTreeWidget->currentItem();
558
559     if (!item)
560         return;
561
562     QVariant var = item->data(0, Qt::UserRole);
563     m_imageViewer->setImage(var.value<QImage>());
564     m_imageViewer->show();
565     m_imageViewer->raise();
566     m_imageViewer->activateWindow();
567 }
568
569 void MainWindow::initObjects()
570 {
571     m_ui.stateTreeWidget->sortByColumn(0, Qt::AscendingOrder);
572
573     m_sourcesWidget = new ShadersSourceWidget(m_ui.shadersTab);
574     QVBoxLayout *layout = new QVBoxLayout;
575     layout->addWidget(m_sourcesWidget);
576     m_ui.shadersTab->setLayout(layout);
577
578     m_trace = new ApiTrace();
579     m_retracer = new Retracer(this);
580
581     m_vdataInterpreter = new VertexDataInterpreter(this);
582     m_vdataInterpreter->setListWidget(m_ui.vertexDataListWidget);
583     m_vdataInterpreter->setStride(
584         m_ui.vertexStrideSB->value());
585     m_vdataInterpreter->setComponents(
586         m_ui.vertexComponentsSB->value());
587     m_vdataInterpreter->setStartingOffset(
588         m_ui.startingOffsetSB->value());
589     m_vdataInterpreter->setTypeFromString(
590         m_ui.vertexTypeCB->currentText());
591
592     m_imageViewer = new ImageViewer(this);
593
594     m_model = new ApiTraceModel();
595     m_model->setApiTrace(m_trace);
596     m_proxyModel = new ApiTraceFilter();
597     m_proxyModel->setSourceModel(m_model);
598     m_ui.callView->setModel(m_proxyModel);
599     m_ui.callView->setItemDelegate(new ApiCallDelegate);
600     m_ui.callView->resizeColumnToContents(0);
601     m_ui.callView->header()->swapSections(0, 1);
602     m_ui.callView->setColumnWidth(1, 42);
603     m_ui.callView->setContextMenuPolicy(Qt::CustomContextMenu);
604
605     m_progressBar = new QProgressBar();
606     m_progressBar->setRange(0, 0);
607     statusBar()->addPermanentWidget(m_progressBar);
608     m_progressBar->hide();
609
610     m_argsEditor = new ArgumentsEditor(this);
611
612     m_ui.detailsDock->hide();
613     m_ui.errorsDock->hide();
614     m_ui.vertexDataDock->hide();
615     m_ui.stateDock->hide();
616     setDockOptions(dockOptions() | QMainWindow::ForceTabbedDocks);
617
618     tabifyDockWidget(m_ui.stateDock, m_ui.vertexDataDock);
619     tabifyDockWidget(m_ui.detailsDock, m_ui.errorsDock);
620
621     m_ui.surfacesTreeWidget->setContextMenuPolicy(Qt::CustomContextMenu);
622
623     m_ui.detailsWebView->page()->setLinkDelegationPolicy(
624         QWebPage::DelegateExternalLinks);
625
626     m_jumpWidget = new JumpWidget(this);
627     m_ui.centralLayout->addWidget(m_jumpWidget);
628     m_jumpWidget->hide();
629
630     m_searchWidget = new SearchWidget(this);
631     m_ui.centralLayout->addWidget(m_searchWidget);
632     m_searchWidget->hide();
633
634     m_traceProcess = new TraceProcess(this);
635 }
636
637 void MainWindow::initConnections()
638 {
639     connect(m_trace, SIGNAL(startedLoadingTrace()),
640             this, SLOT(startedLoadingTrace()));
641     connect(m_trace, SIGNAL(finishedLoadingTrace()),
642             this, SLOT(finishedLoadingTrace()));
643     connect(m_trace, SIGNAL(startedSaving()),
644             this, SLOT(slotStartedSaving()));
645     connect(m_trace, SIGNAL(saved()),
646             this, SLOT(slotSaved()));
647     connect(m_trace, SIGNAL(changed(ApiTraceCall*)),
648             this, SLOT(slotTraceChanged(ApiTraceCall*)));
649
650     connect(m_retracer, SIGNAL(finished(const QString&)),
651             this, SLOT(replayFinished(const QString&)));
652     connect(m_retracer, SIGNAL(error(const QString&)),
653             this, SLOT(replayError(const QString&)));
654     connect(m_retracer, SIGNAL(foundState(const ApiTraceState&)),
655             this, SLOT(replayStateFound(const ApiTraceState&)));
656     connect(m_retracer, SIGNAL(retraceErrors(const QList<RetraceError>&)),
657             this, SLOT(slotRetraceErrors(const QList<RetraceError>&)));
658
659     connect(m_ui.vertexInterpretButton, SIGNAL(clicked()),
660             m_vdataInterpreter, SLOT(interpretData()));
661     connect(m_ui.vertexTypeCB, SIGNAL(currentIndexChanged(const QString&)),
662             m_vdataInterpreter, SLOT(setTypeFromString(const QString&)));
663     connect(m_ui.vertexStrideSB, SIGNAL(valueChanged(int)),
664             m_vdataInterpreter, SLOT(setStride(int)));
665     connect(m_ui.vertexComponentsSB, SIGNAL(valueChanged(int)),
666             m_vdataInterpreter, SLOT(setComponents(int)));
667     connect(m_ui.startingOffsetSB, SIGNAL(valueChanged(int)),
668             m_vdataInterpreter, SLOT(setStartingOffset(int)));
669
670
671     connect(m_ui.actionNew, SIGNAL(triggered()),
672             this, SLOT(createTrace()));
673     connect(m_ui.actionOpen, SIGNAL(triggered()),
674             this, SLOT(openTrace()));
675     connect(m_ui.actionQuit, SIGNAL(triggered()),
676             this, SLOT(close()));
677
678     connect(m_ui.actionFind, SIGNAL(triggered()),
679             this, SLOT(slotSearch()));
680     connect(m_ui.actionGo, SIGNAL(triggered()),
681             this, SLOT(slotGoTo()));
682     connect(m_ui.actionGoFrameStart, SIGNAL(triggered()),
683             this, SLOT(slotGoFrameStart()));
684     connect(m_ui.actionGoFrameEnd, SIGNAL(triggered()),
685             this, SLOT(slotGoFrameEnd()));
686
687     connect(m_ui.actionReplay, SIGNAL(triggered()),
688             this, SLOT(replayStart()));
689     connect(m_ui.actionStop, SIGNAL(triggered()),
690             this, SLOT(replayStop()));
691     connect(m_ui.actionLookupState, SIGNAL(triggered()),
692             this, SLOT(lookupState()));
693     connect(m_ui.actionOptions, SIGNAL(triggered()),
694             this, SLOT(showSettings()));
695
696     connect(m_ui.callView, SIGNAL(activated(const QModelIndex &)),
697             this, SLOT(callItemSelected(const QModelIndex &)));
698     connect(m_ui.callView, SIGNAL(customContextMenuRequested(QPoint)),
699             this, SLOT(customContextMenuRequested(QPoint)));
700
701     connect(m_ui.surfacesTreeWidget,
702             SIGNAL(customContextMenuRequested(const QPoint &)),
703             SLOT(showSurfacesMenu(const QPoint &)));
704     connect(m_ui.surfacesTreeWidget,
705             SIGNAL(itemDoubleClicked(QTreeWidgetItem *, int)),
706             SLOT(showSelectedSurface()));
707
708     connect(m_ui.detailsWebView, SIGNAL(linkClicked(const QUrl&)),
709             this, SLOT(openHelp(const QUrl&)));
710
711     connect(m_ui.nonDefaultsCB, SIGNAL(toggled(bool)),
712             this, SLOT(fillState(bool)));
713
714     connect(m_jumpWidget, SIGNAL(jumpTo(int)),
715             SLOT(slotJumpTo(int)));
716
717     connect(m_searchWidget,
718             SIGNAL(searchNext(const QString&, Qt::CaseSensitivity)),
719             SLOT(slotSearchNext(const QString&, Qt::CaseSensitivity)));
720     connect(m_searchWidget,
721             SIGNAL(searchPrev(const QString&, Qt::CaseSensitivity)),
722             SLOT(slotSearchPrev(const QString&, Qt::CaseSensitivity)));
723
724     connect(m_traceProcess, SIGNAL(tracedFile(const QString&)),
725             SLOT(createdTrace(const QString&)));
726     connect(m_traceProcess, SIGNAL(error(const QString&)),
727             SLOT(traceError(const QString&)));
728
729     connect(m_ui.errorsDock, SIGNAL(visibilityChanged(bool)),
730             m_ui.actionShowErrorsDock, SLOT(setChecked(bool)));
731     connect(m_ui.actionShowErrorsDock, SIGNAL(triggered(bool)),
732             m_ui.errorsDock, SLOT(setVisible(bool)));
733     connect(m_ui.errorsTreeWidget, SIGNAL(currentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*)),
734             this, SLOT(slotErrorSelected(QTreeWidgetItem*)));
735 }
736
737 void MainWindow::replayStateFound(const ApiTraceState &state)
738 {
739     m_stateEvent->setState(state);
740     m_model->stateSetOnEvent(m_stateEvent);
741     if (m_selectedEvent == m_stateEvent) {
742         fillStateForFrame();
743     } else {
744         m_ui.stateDock->hide();
745     }
746 }
747
748 void MainWindow::slotGoTo()
749 {
750     m_searchWidget->hide();
751     m_jumpWidget->show();
752 }
753
754 void MainWindow::slotJumpTo(int callNum)
755 {
756     QModelIndex index = m_proxyModel->callIndex(callNum);
757     if (index.isValid()) {
758         m_ui.callView->setCurrentIndex(index);
759     }
760 }
761
762 void MainWindow::createdTrace(const QString &path)
763 {
764     qDebug()<<"Done tracing "<<path;
765     newTraceFile(path);
766 }
767
768 void MainWindow::traceError(const QString &msg)
769 {
770     QMessageBox::warning(
771             this,
772             tr("Tracing Error"),
773             msg);
774 }
775
776 void MainWindow::slotSearch()
777 {
778     m_jumpWidget->hide();
779     m_searchWidget->show();
780 }
781
782 void MainWindow::slotSearchNext(const QString &str, Qt::CaseSensitivity sensitivity)
783 {
784     QModelIndex index = m_ui.callView->currentIndex();
785     ApiTraceEvent *event = 0;
786
787
788     if (!index.isValid()) {
789         index = m_proxyModel->index(0, 0, QModelIndex());
790         if (!index.isValid()) {
791             qDebug()<<"no currently valid index";
792             m_searchWidget->setFound(false);
793             return;
794         }
795     }
796
797     event = index.data(ApiTraceModel::EventRole).value<ApiTraceEvent*>();
798     ApiTraceCall *call = 0;
799
800     if (event->type() == ApiTraceCall::Call)
801         call = static_cast<ApiTraceCall*>(event);
802     else {
803         Q_ASSERT(event->type() == ApiTraceCall::Frame);
804         ApiTraceFrame *frame = static_cast<ApiTraceFrame*>(event);
805         call = frame->calls.value(0);
806     }
807
808     if (!call) {
809         m_searchWidget->setFound(false);
810         return;
811     }
812     const QList<ApiTraceCall*> &calls = m_trace->calls();
813     int callNum = calls.indexOf(call);
814
815     for (int i = callNum + 1; i < calls.count(); ++i) {
816         ApiTraceCall *testCall = calls[i];
817         QString txt = testCall->filterText();
818         if (txt.contains(str, sensitivity)) {
819             QModelIndex index = m_proxyModel->indexForCall(testCall);
820             /* if it's not valid it means that the proxy model has already
821              * filtered it out */
822             if (index.isValid()) {
823                 m_ui.callView->setCurrentIndex(index);
824                 m_searchWidget->setFound(true);
825                 return;
826             }
827         }
828     }
829     m_searchWidget->setFound(false);
830 }
831
832 void MainWindow::slotSearchPrev(const QString &str, Qt::CaseSensitivity sensitivity)
833 {
834     QModelIndex index = m_ui.callView->currentIndex();
835     ApiTraceEvent *event = 0;
836
837
838     if (!index.isValid()) {
839         index = m_proxyModel->index(0, 0, QModelIndex());
840         if (!index.isValid()) {
841             qDebug()<<"no currently valid index";
842             m_searchWidget->setFound(false);
843             return;
844         }
845     }
846
847     event = index.data(ApiTraceModel::EventRole).value<ApiTraceEvent*>();
848     ApiTraceCall *call = 0;
849
850     if (event->type() == ApiTraceCall::Call)
851         call = static_cast<ApiTraceCall*>(event);
852     else {
853         Q_ASSERT(event->type() == ApiTraceCall::Frame);
854         ApiTraceFrame *frame = static_cast<ApiTraceFrame*>(event);
855         call = frame->calls.value(0);
856     }
857
858     if (!call) {
859         m_searchWidget->setFound(false);
860         return;
861     }
862     const QList<ApiTraceCall*> &calls = m_trace->calls();
863     int callNum = calls.indexOf(call);
864
865     for (int i = callNum - 1; i >= 0; --i) {
866         ApiTraceCall *testCall = calls[i];
867         QString txt = testCall->filterText();
868         if (txt.contains(str, sensitivity)) {
869             QModelIndex index = m_proxyModel->indexForCall(testCall);
870             /* if it's not valid it means that the proxy model has already
871              * filtered it out */
872             if (index.isValid()) {
873                 m_ui.callView->setCurrentIndex(index);
874                 m_searchWidget->setFound(true);
875                 return;
876             }
877         }
878     }
879     m_searchWidget->setFound(false);
880 }
881
882 void MainWindow::fillState(bool nonDefaults)
883 {
884     if (nonDefaults) {
885         ApiTraceState defaultState = m_trace->defaultState();
886         if (defaultState.isEmpty()) {
887             m_ui.nonDefaultsCB->blockSignals(true);
888             m_ui.nonDefaultsCB->setChecked(false);
889             m_ui.nonDefaultsCB->blockSignals(false);
890             int ret = QMessageBox::question(
891                 this, tr("Empty Default State"),
892                 tr("The applcation needs to figure out the "
893                    "default state for the current trace. "
894                    "This only has to be done once and "
895                    "afterwards you will be able to enable "
896                    "displaying of non default state for all calls."
897                    "\nDo you want to lookup the default state now?"),
898                 QMessageBox::Yes | QMessageBox::No);
899             if (ret != QMessageBox::Yes)
900                 return;
901             ApiTraceFrame *firstFrame =
902                 m_trace->frameAt(0);
903             ApiTraceEvent *oldSelected = m_selectedEvent;
904             if (!firstFrame)
905                 return;
906             m_selectedEvent = firstFrame;
907             lookupState();
908             m_selectedEvent = oldSelected;
909         }
910     }
911     fillStateForFrame();
912 }
913
914 void MainWindow::customContextMenuRequested(QPoint pos)
915 {
916     QMenu menu;
917     QModelIndex index = m_ui.callView->indexAt(pos);
918
919     callItemSelected(index);
920     if (!index.isValid())
921         return;
922
923     ApiTraceEvent *event =
924         index.data(ApiTraceModel::EventRole).value<ApiTraceEvent*>();
925     if (!event || event->type() != ApiTraceEvent::Call)
926         return;
927
928     menu.addAction(QIcon(":/resources/media-record.png"),
929                    tr("Lookup state"), this, SLOT(lookupState()));
930     menu.addAction(tr("Edit"), this, SLOT(editCall()));
931
932     menu.exec(QCursor::pos());
933 }
934
935 void MainWindow::editCall()
936 {
937     if (m_selectedEvent && m_selectedEvent->type() == ApiTraceEvent::Call) {
938         ApiTraceCall *call = static_cast<ApiTraceCall*>(m_selectedEvent);
939         m_argsEditor->setCall(call);
940         m_argsEditor->show();
941     }
942 }
943
944 void MainWindow::slotStartedSaving()
945 {
946     m_progressBar->show();
947     statusBar()->showMessage(
948         tr("Saving to %1").arg(m_trace->fileName()));
949 }
950
951 void MainWindow::slotSaved()
952 {
953     statusBar()->showMessage(
954         tr("Saved to %1").arg(m_trace->fileName()), 2000);
955     m_progressBar->hide();
956 }
957
958 void MainWindow::slotGoFrameStart()
959 {
960     ApiTraceFrame *frame = currentFrame();
961     if (!frame || frame->calls.isEmpty()) {
962         return;
963     }
964
965     QList<ApiTraceCall*>::const_iterator itr;
966
967     itr = frame->calls.constBegin();
968     while (itr != frame->calls.constEnd()) {
969         ApiTraceCall *call = *itr;
970         QModelIndex idx = m_proxyModel->indexForCall(call);
971         if (idx.isValid()) {
972             m_ui.callView->setCurrentIndex(idx);
973             break;
974         }
975         ++itr;
976     }
977 }
978
979 void MainWindow::slotGoFrameEnd()
980 {
981     ApiTraceFrame *frame = currentFrame();
982     if (!frame || frame->calls.isEmpty()) {
983         return;
984     }
985     QList<ApiTraceCall*>::const_iterator itr;
986
987     itr = frame->calls.constEnd();
988     do {
989         --itr;
990         ApiTraceCall *call = *itr;
991         QModelIndex idx = m_proxyModel->indexForCall(call);
992         if (idx.isValid()) {
993             m_ui.callView->setCurrentIndex(idx);
994             break;
995         }
996     } while (itr != frame->calls.constBegin());
997 }
998
999 ApiTraceFrame * MainWindow::currentFrame() const
1000 {
1001     if (m_selectedEvent) {
1002         if (m_selectedEvent->type() == ApiTraceEvent::Frame) {
1003             return static_cast<ApiTraceFrame*>(m_selectedEvent);
1004         } else {
1005             Q_ASSERT(m_selectedEvent->type() == ApiTraceEvent::Call);
1006             ApiTraceCall *call = static_cast<ApiTraceCall*>(m_selectedEvent);
1007             return call->parentFrame();
1008         }
1009     }
1010     return NULL;
1011 }
1012
1013 void MainWindow::slotTraceChanged(ApiTraceCall *call)
1014 {
1015     Q_ASSERT(call);
1016     if (call == m_selectedEvent) {
1017         m_ui.detailsWebView->setHtml(call->toHtml());
1018     }
1019 }
1020
1021 void MainWindow::slotRetraceErrors(const QList<RetraceError> &errors)
1022 {
1023     m_ui.errorsTreeWidget->clear();
1024
1025     foreach(RetraceError error, errors) {
1026         ApiTraceCall *call = m_trace->callWithIndex(error.callIndex);
1027         if (!call)
1028             continue;
1029         call->setError(error.message);
1030
1031         QTreeWidgetItem *item =
1032             new QTreeWidgetItem(m_ui.errorsTreeWidget);
1033         item->setData(0, Qt::DisplayRole, error.callIndex);
1034         item->setData(0, Qt::UserRole, QVariant::fromValue(call));
1035         QString type = error.type;
1036         type[0] = type[0].toUpper();
1037         item->setData(1, Qt::DisplayRole, type);
1038         item->setData(2, Qt::DisplayRole, error.message);
1039     }
1040 }
1041
1042 void MainWindow::slotErrorSelected(QTreeWidgetItem *current)
1043 {
1044     if (current) {
1045         ApiTraceCall *call =
1046             current->data(0, Qt::UserRole).value<ApiTraceCall*>();
1047         Q_ASSERT(call);
1048         QModelIndex index = m_proxyModel->indexForCall(call);
1049         if (index.isValid()) {
1050             m_ui.callView->setCurrentIndex(index);
1051         } else {
1052             statusBar()->showMessage(tr("Call has been filtered out."));
1053         }
1054     }
1055 }
1056
1057 #include "mainwindow.moc"