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