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