Debian Codegraph @

codeeditor.cpp

raw symbols SCIP
1 /****************************************************************************
2 ** SASM - simple IDE for assembler development
3 ** Copyright (C) 2013 Dmitriy Manushin
4 ** Contact: site: http://dman95.github.io/SASM/
5 ** e-mail: [email protected]
6 **
7 ** This file is part of SASM.
8 **
9 ** SASM is free software: you can redistribute it and/or modify
10 ** it under the terms of the GNU General Public License as published by
11 ** the Free Software Foundation, either version 3 of the License, or
12 ** (at your option) any later version.
13 **
14 ** SASM is distributed in the hope that it will be useful,
15 ** but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 ** GNU General Public License for more details.
18 **
19 ** You should have received a copy of the GNU General Public License
20 ** along with SASM. If not, see <http://www.gnu.org/licenses/>.
21 **
22 ** Этот файл — часть SASM.
23 **
24 ** SASM - свободная программа: вы можете перераспространять ее и/или
25 ** изменять ее на условиях Стандартной общественной лицензии GNU в том виде,
26 ** в каком она была опубликована Фондом свободного программного обеспечения;
27 ** либо версии 3 лицензии, либо (по вашему выбору) любой более поздней
28 ** версии.
29 **
30 ** SASM распространяется в надежде, что она будет полезной,
31 ** но БЕЗО ВСЯКИХ ГАРАНТИЙ; даже без неявной гарантии ТОВАРНОГО ВИДА
32 ** или ПРИГОДНОСТИ ДЛЯ ОПРЕДЕЛЕННЫХ ЦЕЛЕЙ. Подробнее см. в Стандартной
33 ** общественной лицензии GNU.
34 **
35 ** Вы должны были получить копию Стандартной общественной лицензии GNU
36 ** вместе с этой программой. Если это не так, см.
37 ** <http://www.gnu.org/licenses/>.)
38 **
39 ****************************************************************************/
40
41 #include "codeeditor.h"
42
43 /**
44 * @file codeeditor.cpp
45 * Implements the code editing area
46 */
47
48 CodeEditor::CodeEditor(QWidget *parent, bool withBeakpoints) :
49 RuQPlainTextEdit(parent), debugImage(":/images/debugLine.png"),
50 breakpointImage(":/images/breakpoint.png"),
51 settings("SASM Project", "SASM")
52 {
53 hasBreakpoints = withBeakpoints;
54 prevBlockCount = -1;
55 setDebugMode(false);
56 debugAreaWidth = 3 + debugImage.width() + 1;
57 setWordWrapMode(QTextOption::NoWrap);
58 firstTopMargin = contentOffset().y();
59 lineNumberArea = new LineNumberArea(this);
60 lineNumberPanelColor = settings.value("linenumberpanelcolor", QColor(235, 235, 235)).value<QColor>();
61
62 connect(this, SIGNAL(blockCountChanged(int)), this, SLOT(updateLineNumberAreaWidth(int)));
63 connect(this, SIGNAL(updateRequest(QRect,int)), this, SLOT(updateLineNumberArea(QRect,int)));
64 connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(highlightCurrentLine()));
65 connect(this, SIGNAL(blockCountChanged(int)), this, SLOT(shiftBreakpoints(int)));
66
67 updateLineNumberAreaWidth(0);
68 highlightCurrentLine();
69 currentDebugLine = -1;
70 }
71
72 int CodeEditor::lineNumberAreaWidth()
73 {
74 int digits = 1;
75 int max = qMax(1, blockCount());
76 while (max >= 10) {
77 max /= 10;
78 ++digits;
79 }
80
81 int space = fontMetrics().horizontalAdvance(QLatin1Char('9')) * digits + debugAreaWidth;
82
83 return space;
84 }
85
86 void CodeEditor::updateLineNumberAreaWidth(int /* newBlockCount */)
87 {
88 setViewportMargins(lineNumberAreaWidth(), 0, 0, 0);
89 }
90
91 void CodeEditor::updateLineNumberArea(const QRect &rect, int dy)
92 {
93 if (dy)
94 lineNumberArea->scroll(0, dy);
95 else
96 lineNumberArea->update(0, rect.y(), lineNumberArea->width(), rect.height());
97 //! Indirectly invokes CodeEditor::lineNumberAreaPaintEvent() throw virtual LineNumberArea::paintEvent()
98
99 //! Viewport - visible part of widget
100 if (rect.contains(viewport()->rect()))
101 updateLineNumberAreaWidth(0);
102 }
103
104 void CodeEditor::resizeEvent(QResizeEvent *e)
105 {
106 QPlainTextEdit::resizeEvent(e);
107
108 QRect cr = contentsRect();
109 lineNumberArea->setGeometry(QRect(cr.left(), cr.top(), lineNumberAreaWidth(), cr.height()));
110 }
111
112 void CodeEditor::lineNumberAreaPaintEvent(QPaintEvent *event)
113 {
114 // !Paint on line number area
115 QPainter painter(lineNumberArea);
116 painter.fillRect(event->rect(), lineNumberPanelColor);
117
118 QTextBlock block = firstVisibleBlock();
119 int blockNumber = block.blockNumber();
120 int top = (int) blockBoundingGeometry(block).translated(contentOffset()).top();
121 int bottom = top + (int) blockBoundingRect(block).height();
122
123 while (block.isValid() && top <= event->rect().bottom()) {
124 if (block.isVisible() && bottom >= event->rect().top()) {
125 QString number = QString::number(blockNumber + 1);
126 painter.setPen(settings.value("linenumberfontcolor", QColor(30, 30, 30)).value<QColor>());
127 painter.drawText(0, top, lineNumberArea->width() - debugAreaWidth, fontMetrics().height(),
128 Qt::AlignRight, number);
129
130 if (blockNumber + 1 == currentDebugLine)
131 //! Blocks counting starts with 0, line number is equivalent (block number + 1)
132 //if QTextOption::NoWrap is not set, lines count - visible lines, block count - lines divided by '\n'
133 painter.drawPixmap(lineNumberArea->width() - debugAreaWidth + 3,
134 top + fontMetrics().height() / 2 - debugImage.height() / 2,
135 debugImage.width(), debugImage.height(), debugImage);
136 if (breakpoints.contains(blockNumber + 1) && hasBreakpoints)
137 painter.drawPixmap(lineNumberArea->width() - debugAreaWidth + 3,
138 top + fontMetrics().height() / 2 - breakpointImage.height() / 2,
139 breakpointImage.width(), breakpointImage.height(), breakpointImage);
140 }
141
142 block = block.next();
143 top = bottom;
144 bottom = top + (int) blockBoundingRect(block).height();
145 ++blockNumber;
146 }
147 }
148
149 void CodeEditor::lineNumberAreaMousePressEvent(QMouseEvent *event)
150 {
151 if (hasBreakpoints) {
152 //! If mouse click has been made - add breakpoint
153 //! Counting line number
154 int lineNumber = 0;
155 int sumHeight = 0;
156 QTextBlock block = firstVisibleBlock();
157 while (block.isValid() && event->y() > sumHeight) {
158 sumHeight += blockBoundingGeometry(block).height();
159 block = block.next();
160 lineNumber++;
161 }
162 lineNumber += verticalScrollBar()->value(); //+ invisible lines
163
164 if (lineNumber <= document()->lineCount()) {
165 //blocks counting starts with 0
166 lineNumber = document()->findBlockByLineNumber(lineNumber - 1).blockNumber() + 1; //line number to paint
167
168 //add or remove line number in list
169 if (breakpoints.contains(lineNumber)) {
170 breakpoints.removeOne(lineNumber);
171 emit breakpointsChanged(lineNumber, false);
172 } else {
173 breakpoints.append(lineNumber);
174 emit breakpointsChanged(lineNumber, true);
175 }
176
177 repaintLineNumberArea();
178 }
179 }
180 }
181
182 void CodeEditor::setBreakpointOnCurrentLine()
183 {
184 if (hasBreakpoints) {
185 int lineNumber = textCursor().blockNumber() + 1;
186 if (lineNumber <= document()->lineCount()) {
187 //blocks counting starts with 0
188 lineNumber = document()->findBlockByLineNumber(lineNumber - 1).blockNumber() + 1; //line number to paint
189
190 //add or remove line number in list
191 if (breakpoints.contains(lineNumber)) {
192 breakpoints.removeOne(lineNumber);
193 emit breakpointsChanged(lineNumber, false);
194 } else {
195 breakpoints.append(lineNumber);
196 emit breakpointsChanged(lineNumber, true);
197 }
198
199 repaintLineNumberArea();
200 }
201 }
202 }
203
204 void CodeEditor::repaintLineNumberArea()
205 {
206 //repaint
207 QRect lineNumberAreaRect(lineNumberArea->x(), lineNumberArea->y(),
208 lineNumberArea->width(), lineNumberArea->height());
209 emit updateRequest(lineNumberAreaRect, 0);
210 }
211
212 QList<int> *CodeEditor::getBreakpoints()
213 {
214 return &breakpoints;
215 }
216
217 void CodeEditor::highlightCurrentLine()
218 {
219 if (!debugMode) {
220 if (settings.value("currentlinemode", true).toBool()) {
221 QList<QTextEdit::ExtraSelection> extraSelections;
222
223 if (!isReadOnly()) {
224 QTextEdit::ExtraSelection selection;
225
226 QColor lineColor = settings.value("currentlinecolor", QColor(232, 232, 255)).value<QColor>();
227
228 selection.format.setBackground(lineColor);
229 selection.format.setProperty(QTextFormat::FullWidthSelection, true);
230 selection.cursor = textCursor();
231 selection.cursor.clearSelection();
232 extraSelections.append(selection);
233 }
234
235 setExtraSelections(extraSelections);
236 } else {
237 QList<QTextEdit::ExtraSelection> extraSelections; //empty
238 setExtraSelections(extraSelections);
239 }
240 }
241 }
242
243 void CodeEditor::highlightDebugLine(int lineNumber, bool moveCursor)
244 {
245 if (debugMode) {
246 QList<QTextEdit::ExtraSelection> extraSelections;
247
248 if (!isReadOnly() && lineNumber > 0) {
249 QTextEdit::ExtraSelection selection;
250
251 QColor lineColor = settings.value("debuglinecolor", QColor(235, 200, 40)).value<QColor>();
252
253 selection.format.setBackground(lineColor);
254 selection.format.setProperty(QTextFormat::FullWidthSelection, true);
255 selection.cursor = QTextCursor(document());
256 selection.cursor.movePosition(QTextCursor::NextBlock, QTextCursor::MoveAnchor, lineNumber - 1);
257 selection.cursor.clearSelection();
258 if (moveCursor) {
259 setTextCursor(selection.cursor); //scroll to debugging line
260 }
261 extraSelections.append(selection);
262 }
263
264 setExtraSelections(extraSelections);
265 }
266 }
267
268 void CodeEditor::updateDebugLine(int number)
269 {
270 //number > 0 => highlight line
271 //number == -1 => exit from debug mode
272 //number == -2 => does not highlight any line, but does not exit from debug mode
273 //last case for waiting program stops on next instruction or breakpoint
274 if (number == -1)
275 setDebugMode(false);
276 else
277 setDebugMode(true);
278 if (number != -2)
279 currentDebugLine = number;
280
281 //create rectangle of line number area and highlight debug line throw updateRequest()
282 QRect lineNumberAreaRect(lineNumberArea->x(), lineNumberArea->y(),
283 lineNumberArea->width(), lineNumberArea->height());
284 emit updateRequest(lineNumberAreaRect, 0);
285
286 highlightDebugLine(number, true);
287 highlightCurrentLine();
288 }
289
290 void CodeEditor::setDebugMode(bool mode)
291 {
292 debugMode = mode;
293 }
294
295 void CodeEditor::putTab()
296 {
297 QTextCursor cursor = textCursor();
298 if (cursor.selectionEnd() - cursor.selectionStart() <= 0) {
299 int spacesToAdd = 4 - cursor.columnNumber() % 4;
300 QString insertion(spacesToAdd, ' ');
301 insertPlainText(insertion);
302 } else {
303 QString insertion = " ";
304 QTextBlock firstBlock = document()->findBlock(cursor.selectionStart());
305 QTextBlock lastBlock = document()->findBlock(cursor.selectionEnd() - 1);
306
307 cursor.setPosition(firstBlock.position());
308 cursor.beginEditBlock();
309 do {
310 cursor.insertText(insertion);
311 } while (cursor.movePosition(QTextCursor::NextBlock) && cursor.position() <= lastBlock.position());
312 cursor.endEditBlock();
313 }
314 }
315
316 void CodeEditor::deleteTab()
317 {
318 QTextCursor cursor = textCursor();
319 if (cursor.selectionEnd() - cursor.selectionStart() <= 0) {
320 int spacesToDelete = 4 - (4 - cursor.columnNumber() % 4) % 4;
321 for (int i = 0; i < spacesToDelete; ++i) {
322 if (cursor.columnNumber() != 0 && document()->characterAt(cursor.position() - 1) == ' ') {
323 cursor.movePosition(QTextCursor::Left, QTextCursor::KeepAnchor, 1);
324 } else {
325 break;
326 }
327 }
328 cursor.removeSelectedText();
329 } else {
330 QTextBlock firstBlock = document()->findBlock(cursor.selectionStart());
331 QTextBlock lastBlock = document()->findBlock(cursor.selectionEnd() - 1);
332 cursor.setPosition(firstBlock.position());
333 cursor.beginEditBlock();
334 do {
335 int spacesToDelete = 4;
336 for (int i = 0; i < spacesToDelete; ++i) {
337 if (document()->characterAt(cursor.position()) == ' ') {
338 cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor, 1);
339 } else {
340 break;
341 }
342 }
343 cursor.removeSelectedText();
344 } while (cursor.movePosition(QTextCursor::NextBlock) && cursor.position() <= lastBlock.position());
345 cursor.endEditBlock();
346 }
347 }
348
349 void CodeEditor::keyPressEvent(QKeyEvent *e)
350 {
351 QString curString = textCursor().block().text();
352 int indentWidth = -1;
353 switch (e->key()) {
354 case (Qt::Key_Tab) :
355 if (! (e->modifiers() & Qt::ShiftModifier))
356 putTab();
357 break;
358 case (Qt::Key_Enter) :
359 case (Qt::Key_Return) :
360 while (curString[++indentWidth] == ' ');
361 QPlainTextEdit::keyPressEvent(e);
362 for (int i = 0; i < indentWidth; i++)
363 insertPlainText(" ");
364 break;
365 case (Qt::Key_Q) :
366 if ((e->modifiers() & Qt::ShiftModifier) && (e->modifiers() & Qt::ControlModifier))
367 commentSelectedCode();
368 else
369 QPlainTextEdit::keyPressEvent(e);
370 break;
371 case (Qt::Key_A) :
372 if ((e->modifiers() & Qt::ShiftModifier) && (e->modifiers() & Qt::ControlModifier))
373 uncommentSelectedCode();
374 else
375 QPlainTextEdit::keyPressEvent(e);
376 break;
377 default:
378 QPlainTextEdit::keyPressEvent(e);
379 }
380 }
381
382 void CodeEditor::dragEnterEvent(QDragEnterEvent *event)
383 {
384 if (event->mimeData()->hasUrls()) {
385 event->acceptProposedAction();
386 } else {
387 RuQPlainTextEdit::dragEnterEvent(event);
388 }
389 }
390
391 void CodeEditor::dropEvent(QDropEvent *event)
392 {
393 if (event->mimeData()->hasUrls()) {
394 foreach (const QUrl &url, event->mimeData()->urls())
395 {
396 const QString &fileName = url.toLocalFile();
397
398 if (fileName.isEmpty())
399 continue;
400
401 emit fileOpened(fileName);
402 }
403 event->acceptProposedAction();
404 } else {
405 RuQPlainTextEdit::dropEvent(event);
406 }
407 }
408
409 void CodeEditor::shiftBreakpoints(int blockCount)
410 {
411 if (prevBlockCount == -1) {
412 prevBlockCount = this->blockCount();
413 return;
414 }
415 //remove breakpoints in range
416 int changedLine = textCursor().blockNumber() + 1; //blocks starts from 0
417 if (blockCount < prevBlockCount) {
418 for (int i = changedLine + 1; i <= changedLine + prevBlockCount - blockCount; i++) {
419 breakpoints.removeOne(i);
420 }
421 }
422
423 //shift breakpoints
424 if (blockCount > prevBlockCount) {
425 for (int i = 0; i < breakpoints.size(); i++) {
426 if (breakpoints[i] >= changedLine)
427 breakpoints[i] += blockCount - prevBlockCount;
428 }
429 } else {
430 for (int i = 0; i < breakpoints.size(); i++) {
431 if (breakpoints[i] > changedLine)
432 breakpoints[i] += blockCount - prevBlockCount;
433 }
434 }
435 prevBlockCount = blockCount;
436 repaintLineNumberArea();
437 }
438
439 bool CodeEditor::isMacroOnCurrentDebugLine()
440 {
441 if (currentDebugLine > 0) {
442 QTextBlock block = document()->findBlockByLineNumber(currentDebugLine - 1);
443 QString text = block.text();
444 QStringList macrosPatterns;
445 macrosPatterns << "\\bPRINT_DEC\\b" << "\\bPRINT_HEX\\b" <<
446 "\\bPRINT_CHAR\\b" << "\\bPRINT_STRING\\b" <<
447 "\\bNEWLINE\\b" << "\\bPRINT_UDEC\\b" <<
448 "\\bGET_UDEC\\b" << "\\bGET_DEC\\b" <<
449 "\\bGET_HEX\\b" << "\\bGET_CHAR\\b" <<
450 "\\bGET_STRING\\b" << "\\bCMAIN\\b" << "\\bCEXTERN\\b";
451 foreach (const QString &pattern, macrosPatterns) {
452 QRegExp regExp(pattern, Qt::CaseSensitive);
453 if (text.indexOf(regExp) != -1)
454 return true;
455 }
456 }
457 return false;
458 }
459
460 CodeEditor::~CodeEditor()
461 {
462 delete lineNumberArea;
463 }