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