Make GUI Widget move Comments through the backend properly
[frida/frida.git] / src / gui / widgets / BasicBlockWidget.cxx
1 #include "BasicBlockWidget.hxx"
2 #include "gui/Mainwindow.hxx"
3 #include "gui/dialogs/SimpleStringDialog.hxx"
4 #include "core/BasicBlock.hxx"
5 #include "core/Function.hxx"
6 #include "core/Comment.hxx"
7 #include "disassembler/Instruction.hxx"
8 #include "core/InformationManager.hxx"
9 #include "core/events/RenameFunctionEvent.hxx"
10 #include "core/events/ChangeCommentEvent.hxx"
11 #include <algorithm>
12
13 class CustomQGraphicsTextItem : public QObject, public QGraphicsTextItem {
14 public:
15 CustomQGraphicsTextItem(const QString& text, BasicBlockWidget* parent)
16 : QGraphicsTextItem(text, parent), parent(parent) {}
17 void contextMenuEvent(QGraphicsSceneContextMenuEvent*);
18 private:
19 void addComment(int row, bool global);
20
21 BasicBlockWidget* parent;
22 };
23
24 void CustomQGraphicsTextItem::addComment(int row, bool global) {
25 SimpleStringDialog dialog(global ? "Global comment" : "Local comment");
26 int result = dialog.exec();
27 uint64_t address = parent->instructions[row].getAddress();
28 if (QDialog::Accepted == result) {
29 Comment* comment;
30 if (global) {
31 comment = parent->block->getManager()->newGlobalComment(address);
32 } else {
33 comment = parent->block->getManager()->newLocalComment(address, NULL);
34 }
35 comment->setText(dialog.result().toStdString());
36 parent->block->getManager()->finishComment(comment);
37
38 // cell.firstCursorPosition().insertHtml(QString(";; ") + dialog.result());
39 } else {
40 LOG4CXX_DEBUG(parent->logger, "addComment aborted");
41 }
42 }
43
44 void CustomQGraphicsTextItem::contextMenuEvent(QGraphicsSceneContextMenuEvent* event) {
45 QTextCursor c = textCursor();
46 c.setPosition(document()->documentLayout()->hitTest(event->pos(), Qt::FuzzyHit));
47 c.select(QTextCursor::WordUnderCursor);
48
49 QMenu menu;
50 bool ok;
51 uint64_t address = c.selectedText().toLongLong(&ok, 16);
52 if (ok) {
53 QAction* act = menu.addAction(c.selectedText() + " is a Function");
54 QObject::connect(act, &QAction::triggered,
55 [=]() {parent->mainwindow->requestNewFunctionByAddress(address);});
56 }
57
58 QTextTable* table = c.currentTable();
59 if (NULL != table) {
60 int row = table->cellAt(c).row();
61 QAction* globalComment = menu.addAction("Add global Comment");
62 QAction* localComment = menu.addAction("Add local Comment");
63
64 QObject::connect(globalComment, &QAction::triggered,
65 [=]() { addComment(row, true); });
66 QObject::connect(localComment, &QAction::triggered,
67 [=]() { addComment(row, false); });
68 }
69
70 menu.exec(event->screenPos());
71 }
72
73 BasicBlockWidget::BasicBlockWidget(const QString& name, BasicBlock * block,
74 Mainwindow * mainwindow)
75 : width(270), height(45), name(name)
76 , _table(NULL)
77 , block(block), mainwindow(mainwindow)
78 , logger(log4cxx::Logger::getLogger("gui.BasicBlockWidget." + name.toStdString())) {
79 next[0] = NULL; next[1] = NULL;
80
81 block->getManager()->registerRenameFunctionEvent([=](RenameFunctionEvent* event) {updateFunctionName(event);});
82
83 _widget.reset(new CustomQGraphicsTextItem("", this));
84 _widget->setPos(5, 20);
85 _widget->setTextInteractionFlags(Qt::TextSelectableByMouse|
86 Qt::LinksAccessibleByMouse);
87
88 if (width < 250) width = 250;
89
90 QObject::connect(_widget.get(), &QGraphicsTextItem::linkActivated,
91 [=](QString str) {
92 if (str.startsWith("function:")) {
93 QString address = str.remove("function:");
94 mainwindow->switchMainPlaneToAddress(address.toInt(NULL, 16));
95 }
96 });
97 instructions = block->getInstructions();
98 populateWidget();
99 block->getManager()->registerChangeCommentEvent([=](ChangeCommentEvent* e) {changeCommentHandler(e);});
100 }
101
102 void BasicBlockWidget::updateFunctionName(RenameFunctionEvent *event) {
103 QString search = QString("function:") + QString::number(event->address, 16);
104 QTextDocument *document = _widget->document();
105 QTextBlock b = document->begin();
106 while (b.isValid()) {
107 for (QTextBlock::iterator i = b.begin(); !i.atEnd(); ++i) {
108 QTextCharFormat format = i.fragment().charFormat();
109 bool isLink = format.isAnchor();
110 if (isLink)
111 {
112 if (search == format.anchorHref()) {
113 LOG4CXX_DEBUG(logger, i.fragment().text().toStdString() << " ---> " << format.anchorHref().toStdString());
114 QTextCursor c(b);
115 c.setPosition(i.fragment().position());
116 c.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor, i.fragment().length());
117 c.movePosition(QTextCursor::Left, QTextCursor::KeepAnchor, i.fragment().length());
118 c.movePosition(QTextCursor::WordRight, QTextCursor::KeepAnchor);
119 c.insertText(event->new_name.c_str());
120 }
121 }
122 }
123 b = b.next();
124 }
125 }
126
127 void BasicBlockWidget::changeCommentHandler(ChangeCommentEvent* event) {
128 auto inst_it = std::find_if(instructions.begin(), instructions.end(),
129 [=](Instruction& inst) {
130 return inst.getAddress() == event->address;
131 });
132 if (inst_it != instructions.end()) {
133 if (std::find(inst_it->comments().begin(),
134 inst_it->comments().begin(),
135 event->comment) == inst_it->comments().end()) {
136 LOG4CXX_DEBUG(logger, "Change Comment Event -- New Comment!");
137 inst_it->comments().push_back(event->comment);
138 }
139 int row = inst_it - instructions.begin();
140 LOG4CXX_DEBUG(logger, "Inserting comment for instruction at row " << std::hex << row);
141 QTextCursor cursor = _table->cellAt(row, 2).lastCursorPosition();
142 while (cursor != _table->cellAt(row, 2).firstCursorPosition()) {
143 cursor.movePosition(QTextCursor::Left, QTextCursor::KeepAnchor, 1);
144 }
145 cursor.removeSelectedText();
146 cursor.insertHtml(formatComments(&*inst_it));
147 }
148 }
149
150 void BasicBlockWidget::populateWidget() {
151 int row;
152 QTextTableFormat format;
153 format.setBorderStyle(QTextFrameFormat::BorderStyle_None);
154 format.setBorder(0);
155
156 for (Instruction& inst : instructions) {
157 if (_table) {
158 row = _table->rows();
159 _table->appendRows(1);
160 } else {
161 row = 0;
162 _table = _widget->textCursor().insertTable(1, 3, format);
163 }
164 QString bytestring;
165 for (uint8_t byte : inst.getBytes()) {
166 const char * hexdigits = "0123456789ABCDEF";
167 bytestring += hexdigits[(byte >> 4) & 0xF];
168 bytestring += hexdigits[byte & 0xF];
169 bytestring += ' ';
170 }
171 _table->cellAt(row, 0).firstCursorPosition().insertText(bytestring);
172
173 QString line = inst.getText().c_str();
174 line = line.replace('\t', ' ').toHtmlEscaped();
175 if (inst.getReference() != "") {
176 QString href = inst.getReference().c_str();
177 QStringList list = href.split(":");
178 if (list[0] == "function") {
179 uint64_t address = href.split(":")[1].toLongLong(NULL, 16);
180 Function* fun = block->getManager()->getFunction(address);
181
182 if (fun) {
183 line = line.split(" ")[0] + " " + QString(fun->getName().c_str()).toHtmlEscaped();
184 LOG4CXX_DEBUG(logger, "Naming function at " << address << " " << fun->getName());
185 }
186 }
187 line = "<a href=\"" + href + "\">" + line + "</a>";
188 }
189 _table->cellAt(row, 1).firstCursorPosition().insertHtml(line);
190 _table->cellAt(row, 2).firstCursorPosition().insertHtml(formatComments(&inst));
191 }
192 }
193
194 QString BasicBlockWidget::formatComments(Instruction* inst) {
195 QString comments;
196 for (Comment* c: inst->comments()) {
197 comments += "<br />";
198 comments += c->getText().c_str();
199 }
200 return (comments == "" ? "" : ";; ") + comments.trimmed();
201 }
202
203 void BasicBlockWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem*,
204 QWidget*) {
205 _widget->adjustSize();
206 width = 10 + _widget->boundingRect().width();
207 height = 25 + _widget->boundingRect().height();
208 if (width < 250) width = 250;
209
210 painter->fillRect(0, 0, width, height, QColor(0xcc, 0xcc, 0xff, 0xff));
211 painter->setPen(QColor(0x00, 0x00, 0xff, 0xff));
212 painter->drawRect(0, 0, width, height);
213 painter->drawText(5, 15, name);
214 }
215
216 QRectF BasicBlockWidget::boundingRect() const {
217 qreal penWidth = 1;
218 QRectF result(- penWidth / 2, - penWidth / 2,
219 width + penWidth, height + penWidth);
220 return result;
221 }
222
223 std::array<QPointF, 3> BasicBlockWidget::getExits() const {
224 return { { mapToScene(QPointF( width/3, height)),
225 mapToScene(QPointF( width/2, height)),
226 mapToScene(QPointF(2*width/3, height)) } };
227 }
228