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