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