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