+#include "BasicBlockWidget.hxx"
+#include "CFGScene.hxx"
+#include "gui/Mainwindow.hxx"
+#include "gui/dialogs/SimpleStringDialog.hxx"
+#include "core/BasicBlock.hxx"
+#include "core/Function.hxx"
+#include "core/Comment.hxx"
+#include "disassembler/Instruction.hxx"
+#include "core/InformationManager.hxx"
+#include "core/events/RenameFunctionEvent.hxx"
+#include "core/events/ChangeCommentEvent.hxx"
+#include <algorithm>
+class CustomQGraphicsTextItem : public QObject, public QGraphicsTextItem {
+public:
+ CustomQGraphicsTextItem(const QString& text, BasicBlockWidget* parent)
+ : QGraphicsTextItem(text, parent), parent(parent) {}
+ void contextMenuEvent(QGraphicsSceneContextMenuEvent*);
+private:
+ void addComment(int row, bool global);
+ BasicBlockWidget* parent;
+};
+
+void CustomQGraphicsTextItem::addComment(int row, bool global) {
+ SimpleStringDialog dialog(global ? "Global comment" : "Local comment");
+ int result = dialog.exec();
+ uint64_t address = parent->instructions[row].getAddress();
+ if (QDialog::Accepted == result) {
+ Comment* comment;
+ if (global) {
+ comment = parent->block->getManager()->newGlobalComment(address);
+ } else {
+ /* TODO: 0x23 as we currently don't have the function here
+ * and setting it to null will make the comment appear
+ * global. Also means local comments are largely still
+ * broken.
+ */
+ comment = parent->block->getManager()->newLocalComment(address, (Function*)0x23);
+ }
+ comment->setText(dialog.result().toStdString());
+ parent->block->getManager()->finishComment(comment);
+ } else {
+ LOG4CXX_DEBUG(parent->logger, "addComment aborted");
+ }
+}
+
+void CustomQGraphicsTextItem::contextMenuEvent(QGraphicsSceneContextMenuEvent* event) {
+ QTextCursor c = textCursor();
+ c.setPosition(document()->documentLayout()->hitTest(event->pos(), Qt::FuzzyHit));
+ c.select(QTextCursor::WordUnderCursor);
+
+ QMenu menu;
+ bool ok;
+ uint64_t address = c.selectedText().toLongLong(&ok, 16);
+ QTextTable* table = c.currentTable();
+ if (ok) {
+ QAction* act = menu.addAction(c.selectedText() + " is a Function");
+ QObject::connect(act, &QAction::triggered,
+ [=]() {
+ parent->mainwindow->requestNewFunctionByAddress(address);
+ if (NULL == table) return;
+ int row = table->cellAt(c).row();
+ uint64_t insAddress = parent->instructions[row].getAddress();
+ Comment* comment = parent->block->getManager()->newLocalComment(insAddress, (Function*)0x23);
+ comment->setText("#F<" + c.selectedText().toStdString() + ">");
+ parent->block->getManager()->finishComment(comment);
+ });
+ }
+
+ if (NULL != table) {
+ int row = table->cellAt(c).row();
+ QAction* globalComment = menu.addAction("Add global Comment");
+ QAction* localComment = menu.addAction("Add local Comment");
+
+ QObject::connect(globalComment, &QAction::triggered,
+ [=]() { addComment(row, true); });
+ QObject::connect(localComment, &QAction::triggered,
+ [=]() { addComment(row, false); });
+ }
+
+ menu.exec(event->screenPos());
+}
+
+BasicBlockWidget::BasicBlockWidget(const QString& name, BasicBlock * block,
+ Mainwindow * mainwindow)
+ : width(200), height(45), name(name)
+ , currentColor(defaultColor), _table(NULL)
+ , block(block), mainwindow(mainwindow)
+ , logger(log4cxx::Logger::getLogger("gui.BasicBlockWidget." + name.toStdString())) {
+ next[0] = NULL; next[1] = NULL;
+
+ QObject::connect(block->getManager(), &InformationManager::renameFunctionEvent,
+ [=](RenameFunctionEvent* event) {updateFunctionName(event);});
+
+ _widget.reset(new CustomQGraphicsTextItem("", this));
+ _widget->setPos(5, 20);
+ _widget->setTextInteractionFlags(Qt::TextSelectableByMouse|
+ Qt::LinksAccessibleByMouse);
+
+ if (width < 250) width = 250;
+
+ QObject::connect(_widget.get(), &QGraphicsTextItem::linkActivated,
+ [=](QString str) {
+ if (str.startsWith("function:")) {
+ QString address = str.remove("function:");
+ mainwindow->switchMainPlaneToAddress(address.toInt(NULL, 16));
+ } else if (str.startsWith("block:")) {
+ QString address = str.remove("block:");
+
+ /* next[0] is always the jumptarget. On a
+ * conditional jump, next[1] also
+ * contains the following instruction
+ *
+ * TODO: Verify we're switching to the
+ * right block -- the target
+ * address matches the next blocks
+ * start address
+ */
+ LOG4CXX_TRACE(logger, "Highlighting block at Address " << address.toStdString()
+ << " BasicBlockWidget " << std::hex << next[0]);
+ ((CFGScene*)this->scene())->highlightBlock(next[0]);
+ }
+ });
+ instructions = block->getInstructions();
+ populateWidget();
+ QObject::connect(block->getManager(), &InformationManager::changeCommentEvent,
+ [=](ChangeCommentEvent* e) {changeCommentHandler(e);});
+}
+
+void BasicBlockWidget::updateFunctionName(RenameFunctionEvent *event) {
+ QString search = QString("function:") + QString::number(event->address, 16);
+ QTextDocument *document = _widget->document();
+ QTextBlock b = document->begin();
+ while (b.isValid()) {
+ for (QTextBlock::iterator i = b.begin(); !i.atEnd(); ++i) {
+ QTextCharFormat format = i.fragment().charFormat();
+ bool isLink = format.isAnchor();
+ if (isLink)
+ {
+ if (search == format.anchorHref()) {
+ LOG4CXX_DEBUG(logger, i.fragment().text().toStdString() << " ---> "
+ << format.anchorHref().toStdString());
+
+ /* This should select the function name. It stars
+ * by selecting the whole link fragment from back
+ * to front and then moves one word to the back
+ * again deselecting whatever mnemonic is used for
+ * the call instruction.
+ */
+ QTextCursor c(b);
+ c.setPosition(i.fragment().position());
+ c.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor, i.fragment().length());
+ c.movePosition(QTextCursor::Left, QTextCursor::KeepAnchor, i.fragment().length());
+ c.movePosition(QTextCursor::WordRight, QTextCursor::KeepAnchor);
+ c.insertText(event->new_name.c_str());
+
+ QGraphicsTextItem* item = _widget.get();
+ item->adjustSize();
+ }
+ }
+ }
+ b = b.next();
+ }
+}
+
+void BasicBlockWidget::changeCommentHandler(ChangeCommentEvent* event) {
+ auto inst_it = std::find_if(instructions.begin(), instructions.end(),
+ [=](Instruction& inst) {
+ return inst.getAddress() == event->address;
+ });
+ if (inst_it != instructions.end()) {
+ if (std::find(inst_it->comments().begin(),
+ inst_it->comments().begin(),
+ event->comment) == inst_it->comments().end()) {
+ LOG4CXX_DEBUG(logger, "Change Comment Event -- New Comment!");
+ inst_it->comments().push_back(event->comment);
+ }
+ int row = inst_it - instructions.begin();
+ LOG4CXX_DEBUG(logger, "Inserting comment for instruction at row " << std::hex << row);
+ QTextCursor cursor = _table->cellAt(row, 2).lastCursorPosition();
+ while (cursor != _table->cellAt(row, 2).firstCursorPosition()) {
+ cursor.movePosition(QTextCursor::Left, QTextCursor::KeepAnchor, 1);
+ }
+ cursor.removeSelectedText();
+ cursor.insertHtml(formatComments(&*inst_it));
+ QGraphicsTextItem* item = _widget.get();
+ item->adjustSize();
+ }
+}
+
+void BasicBlockWidget::populateWidget() {
+ int row;
+ QTextTableFormat format;
+ QTextDocument* document = new QTextDocument();
+ format.setBorderStyle(QTextFrameFormat::BorderStyle_None);
+ format.setBorder(0);
+
+ for (Instruction& inst : instructions) {
+ if (_table) {
+ row = _table->rows();
+ _table->appendRows(1);
+ } else {
+ row = 0;
+ _table = QTextCursor(document).insertTable(1, 3, format);
+ }
+ QString bytestring;
+ for (uint8_t byte : inst.getBytes()) {
+ const char * hexdigits = "0123456789ABCDEF";
+ bytestring += hexdigits[(byte >> 4) & 0xF];
+ bytestring += hexdigits[byte & 0xF];
+ bytestring += ' ';
+ }
+ _table->cellAt(row, 0).firstCursorPosition().insertHtml("<nobr>" + bytestring + "</nobr>");
+
+ QString line = inst.getText().c_str();
+ line = line.replace('\t', ' ').toHtmlEscaped();
+ if (inst.getReference() != "") {
+ QString href = inst.getReference().c_str();
+ QStringList list = href.split(":");
+ if (list[0] == "function") {
+ uint64_t address = href.split(":")[1].toLongLong(NULL, 16);
+ Function* fun = block->getManager()->getFunction(address);
+
+ if (fun) {
+ line = line.split(" ")[0] + " " + QString(fun->getName().c_str()).toHtmlEscaped();
+ LOG4CXX_DEBUG(logger, "Naming function at " << address << " " << fun->getName());
+ }
+ }
+ line = "<a href=\"" + href + "\">" + line + "</a>";
+ }
+ _table->cellAt(row, 1).firstCursorPosition().insertHtml("<nobr>" + line + "</nobr>");
+ _table->cellAt(row, 2).firstCursorPosition().insertHtml(formatComments(&inst));
+ }
+ QGraphicsTextItem* item = _widget.get();
+ item->setDocument(document);
+ item->adjustSize();
+ updateSize();
+}
+
+QString BasicBlockWidget::formatComments(Instruction* inst) {
+ QStringList comments;
+ for (Comment* c: inst->comments()) {
+ comments << QString(c->getText().c_str()).toHtmlEscaped();
+ }
+ return (comments.empty() ? "" : ";; ") + comments.join("<br />").trimmed();
+}
+
+void BasicBlockWidget::updateSize() {
+ prepareGeometryChange();
+ width = 10 + _widget->boundingRect().width();
+ height = 25 + _widget->boundingRect().height();
+ if (width < 250) width = 250;
+}
+
+void BasicBlockWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem*,
+ QWidget*) {
+ updateSize();
+
+ painter->fillRect(0, 0, width, height, currentColor);
+ painter->setPen(QColor(0x00, 0x00, 0xff, 0xff));
+ painter->drawRect(0, 0, width, height);
+ painter->drawText(5, 15, name);
+}
+
+QRectF BasicBlockWidget::boundingRect() const {
+ qreal penWidth = 1;
+ QRectF result(- penWidth / 2, - penWidth / 2,
+ width + penWidth, height + penWidth);
+ return result;
+}
+
+std::array<QPointF, 3> BasicBlockWidget::getExits() const {
+ return { { mapToScene(QPointF( width/3, height)),
+ mapToScene(QPointF( width/2, height)),
+ mapToScene(QPointF(2*width/3, height)) } };
+}