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