Debian Codegraph @

src/Gui/PythonEditor.cpp

raw
1 /***************************************************************************
2 * Copyright (c) 2004 Werner Mayer <wmayer[at]users.sourceforge.net> *
3 * *
4 * This file is part of the FreeCAD CAx development system. *
5 * *
6 * This library is free software; you can redistribute it and/or *
7 * modify it under the terms of the GNU Library General Public *
8 * License as published by the Free Software Foundation; either *
9 * version 2 of the License, or (at your option) any later version. *
10 * *
11 * This library is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU Library General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU Library General Public *
17 * License along with this library; see the file COPYING.LIB. If not, *
18 * write to the Free Software Foundation, Inc., 59 Temple Place, *
19 * Suite 330, Boston, MA 02111-1307, USA *
20 * *
21 ***************************************************************************/
22
23
24 #include <QContextMenuEvent>
25 #include <QMenu>
26 #include <QPainter>
27 #include <QRegularExpression>
28 #include <QShortcut>
29 #include <QTextCursor>
30
31
32 #include <Base/Parameter.h>
33 #include <Gui/Command.h>
34
35 #include "PythonEditor.h"
36 #include "Application.h"
37 #include "BitmapFactory.h"
38 #include "Macro.h"
39 #include "PythonDebugger.h"
40
41
42 using namespace Gui;
43
44 namespace Gui
45 {
46 struct PythonEditorP
47 {
48 int debugLine {-1};
49 QRect debugRect;
50 QPixmap breakpoint;
51 QPixmap debugMarker;
52 QString filename;
53 PythonDebugger* debugger;
54 PythonEditorP()
55 : breakpoint(BitmapFactory().iconFromTheme("breakpoint").pixmap(16, 16))
56 , debugMarker(BitmapFactory().iconFromTheme("debug-marker").pixmap(16, 16))
57 {
58 debugger = Application::Instance->macroManager()->debugger();
59 }
60 };
61 } // namespace Gui
62
63 /* TRANSLATOR Gui::PythonEditor */
64
65 /**
66 * Constructs a PythonEditor which is a child of 'parent' and does the
67 * syntax highlighting for the Python language.
68 */
69 PythonEditor::PythonEditor(QWidget* parent)
70 : PythonTextEditor(parent)
71 {
72 d = new PythonEditorP();
73 this->setSyntaxHighlighter(new PythonSyntaxHighlighter(this));
74
75 // set accelerators
76 auto comment = new QShortcut(this);
77 comment->setKey(QKeySequence(QStringLiteral("ALT+C")));
78
79 auto uncomment = new QShortcut(this);
80 uncomment->setKey(QKeySequence(QStringLiteral("ALT+U")));
81
82 auto execInConsole = new QShortcut(this);
83 execInConsole->setKey(QKeySequence(QStringLiteral("ALT+SHIFT+P")));
84
85 connect(comment, &QShortcut::activated, this, &PythonEditor::onComment);
86 connect(uncomment, &QShortcut::activated, this, &PythonEditor::onUncomment);
87 connect(execInConsole, &QShortcut::activated, this, &PythonEditor::onExecuteInConsole);
88 }
89
90 /** Destroys the object and frees any allocated resources */
91 PythonEditor::~PythonEditor()
92 {
93 delete d;
94 }
95
96 void PythonEditor::OnChange(Base::Subject<const char*>& rCaller, const char* sReason)
97 {
98 const auto& rGrp = static_cast<ParameterGrp&>(rCaller);
99
100 if (strcmp(sReason, "EnableBlockCursor") == 0 || strcmp(sReason, "FontSize") == 0
101 || strcmp(sReason, "Font") == 0) {
102 bool block = rGrp.GetBool("EnableBlockCursor", false);
103 if (block) {
104 setCursorWidth(QFontMetrics(font()).averageCharWidth());
105 }
106 else {
107 setCursorWidth(1);
108 }
109 }
110
111 TextEditor::OnChange(rCaller, sReason);
112 }
113
114 void PythonEditor::setFileName(const QString& fn)
115 {
116 d->filename = fn;
117 }
118
119 void PythonEditor::startDebug()
120 {
121 if (d->debugger->start()) {
122 d->debugger->runFile(d->filename);
123 d->debugger->stop();
124 }
125 }
126
127 void PythonEditor::toggleBreakpoint()
128 {
129 QTextCursor cursor = textCursor();
130 int line = cursor.blockNumber() + 1;
131 d->debugger->toggleBreakpoint(line, d->filename);
132 getMarker()->update();
133 }
134
135 void PythonEditor::showDebugMarker(int line)
136 {
137 d->debugLine = line;
138 getMarker()->update();
139 QTextCursor cursor = textCursor();
140 cursor.movePosition(QTextCursor::StartOfBlock);
141 int cur = cursor.blockNumber() + 1;
142 if (cur > line) {
143 for (int i = line; i < cur; i++) {
144 cursor.movePosition(QTextCursor::Up);
145 }
146 }
147 else if (cur < line) {
148 for (int i = cur; i < line; i++) {
149 cursor.movePosition(QTextCursor::Down);
150 }
151 }
152 setTextCursor(cursor);
153 }
154
155 void PythonEditor::hideDebugMarker()
156 {
157 d->debugLine = -1;
158 getMarker()->update();
159 }
160
161 void PythonEditor::drawMarker(int line, int x, int y, QPainter* p)
162 {
163 Breakpoint bp = d->debugger->getBreakpoint(d->filename);
164 if (bp.checkLine(line)) {
165 p->drawPixmap(x, y, d->breakpoint);
166 }
167 if (d->debugLine == line) {
168 p->drawPixmap(x, y + 2, d->debugMarker);
169 d->debugRect = QRect(x, y + 2, d->debugMarker.width(), d->debugMarker.height());
170 }
171 }
172
173 void PythonEditor::contextMenuEvent(QContextMenuEvent* e)
174 {
175 QMenu* menu = createStandardContextMenu();
176 if (!isReadOnly()) {
177 menu->addSeparator();
178 QAction* comment = menu->addAction(tr("Comment"), this, &PythonEditor::onComment);
179 comment->setShortcut(QKeySequence(QStringLiteral("ALT+C")));
180 QAction* uncomment = menu->addAction(tr("Uncomment"), this, &PythonEditor::onUncomment);
181 uncomment->setShortcut(QKeySequence(QStringLiteral("ALT+U")));
182 QAction* execInConsole
183 = menu->addAction(tr("Execute in Console"), this, &PythonEditor::onExecuteInConsole);
184 execInConsole->setShortcut(QKeySequence(QStringLiteral("ALT+Shift+P")));
185 }
186
187 menu->exec(e->globalPos());
188 delete menu;
189 }
190
191 void PythonEditor::keyPressEvent(QKeyEvent* e)
192 {
193 /** When the user presses enter the next line should match the current
194 * indentation unless the line ends in a colon, where the next line
195 * should have an additional indentation. Shift+Enter should dedent
196 * the next block 1 indentation from what it would have been, if possible.
197 */
198 if (e->key() == Qt::Key_Enter || e->key() == Qt::Key_Return) {
199 bool shiftPressed = e->modifiers() & Qt::ShiftModifier;
200 ParameterGrp::handle hPrefGrp = getWindowParameter();
201 int indent = hPrefGrp->GetInt("IndentSize", 4);
202 bool space = hPrefGrp->GetBool("Spaces", true);
203 QString ch = space ? QStringLiteral(" ") : QStringLiteral("\t");
204
205 QTextCursor cursor = textCursor();
206 QString currentLineText = cursor.block().text();
207 bool endsWithColon = currentLineText.endsWith(QLatin1Char(':'));
208 int currentIndentation = 0;
209 // count spaces/tabs at start of current line
210 for (auto c : currentLineText) {
211 if (c == ch) {
212 currentIndentation++;
213 }
214 else {
215 break;
216 }
217 }
218 cursor.insertBlock(); // new line
219 cursor.movePosition(QTextCursor::StartOfBlock); // carriage return
220 // Shift+Enter means dedent, but ensure we are not at column 0
221 if (shiftPressed && currentIndentation >= indent) {
222 currentIndentation -= indent;
223 }
224 // insert appropriate number of spaces/tabs to match current indentation
225 cursor.insertText(QString(currentIndentation, ch[0]));
226 // if the line ended in a colon, then we need to add another tab or multiple spaces
227 if (endsWithColon) {
228 if (space) {
229 cursor.insertText(QString(indent, ch[0])); // 4 more spaces by default
230 }
231 else {
232 cursor.insertText(ch); // 1 more tab
233 }
234 }
235 setTextCursor(cursor);
236 return; // skip default handler
237 }
238 PythonTextEditor::keyPressEvent(e); // wasn't enter key, so let base class handle it
239 }
240
241 void PythonEditor::onComment()
242 {
243 prepend(QStringLiteral("#"));
244 }
245
246 void PythonEditor::onUncomment()
247 {
248 remove(QStringLiteral("#"));
249 }
250
251 void PythonEditor::onExecuteInConsole()
252 {
253 QTextCursor cursor = textCursor();
254 int selStart = cursor.selectionStart();
255 int selEnd = cursor.selectionEnd();
256 QTextBlock block;
257 QString selectedCode;
258
259 for (block = document()->begin(); block.isValid(); block = block.next()) {
260 int pos = block.position();
261 int off = block.length() - 1;
262 if (pos >= selStart || pos + off >= selStart) {
263 if (pos + 1 > selEnd) {
264 break;
265 }
266
267 QString lineText = block.text();
268 selectedCode.append(lineText + QLatin1String("\n"));
269 }
270 }
271
272 if (!selectedCode.isEmpty()) {
273
274 /** Dedent the block of code so that the first selected
275 * line has no indentation, but the remaining lines
276 * keep their indentation relative to that first line.
277 */
278
279 // get the leading whitespace of the first line
280 QStringList lines = selectedCode.split(QLatin1Char('\n'));
281 QString firstLineIndent;
282 for (const QString& line : lines) {
283 if (!line.isEmpty()) {
284 int leadingWhitespace = line.indexOf(QRegularExpression(QLatin1String("\\S")));
285 if (leadingWhitespace > 0) {
286 firstLineIndent = line.left(leadingWhitespace);
287 }
288 break;
289 }
290 }
291
292 // remove that first line whitespace from all the lines
293 for (QString& line : lines) {
294 if (!line.isEmpty() && line.startsWith(firstLineIndent)) {
295 line.remove(0, firstLineIndent.length());
296 }
297 }
298
299 // join the lines into a single QString so we can execute as a single block
300 QString dedentedCode = lines.join(QLatin1Char('\n'));
301
302 if (!dedentedCode.isEmpty()) {
303 try {
304 Gui::Command::doCommand(Gui::Command::Doc, dedentedCode.toStdString().c_str());
305 }
306 catch (const Base::Exception& e) {
307 QString errorMessage = QString::fromStdString(e.what());
308 Base::Console().error(
309 "Error executing Python code:\n%s\n",
310 errorMessage.toUtf8().constData()
311 );
312 }
313 catch (...) {
314 Base::Console().error("An unknown error occurred while executing Python code.\n");
315 }
316 }
317 }
318 }
319
320 // ------------------------------------------------------------------------
321
322 namespace Gui
323 {
324 class PythonSyntaxHighlighterP
325 {
326 public:
327 PythonSyntaxHighlighterP()
328 {
329 keywords << QLatin1String("and") << QLatin1String("as") << QLatin1String("assert")
330 << QLatin1String("break") << QLatin1String("class") << QLatin1String("continue")
331 << QLatin1String("def") << QLatin1String("del") << QLatin1String("elif")
332 << QLatin1String("else") << QLatin1String("except") << QLatin1String("exec")
333 << QLatin1String("False") << QLatin1String("finally") << QLatin1String("for")
334 << QLatin1String("from") << QLatin1String("global") << QLatin1String("if")
335 << QLatin1String("import") << QLatin1String("in") << QLatin1String("is")
336 << QLatin1String("lambda") << QLatin1String("None") << QLatin1String("nonlocal")
337 << QLatin1String("not") << QLatin1String("or") << QLatin1String("pass")
338 << QLatin1String("print") << QLatin1String("raise") << QLatin1String("return")
339 << QLatin1String("True") << QLatin1String("try") << QLatin1String("while")
340 << QLatin1String("with") << QLatin1String("yield");
341 }
342
343 QStringList keywords;
344 };
345 } // namespace Gui
346
347 /**
348 * Constructs a Python syntax highlighter.
349 */
350 PythonSyntaxHighlighter::PythonSyntaxHighlighter(QObject* parent)
351 : SyntaxHighlighter(parent)
352 {
353 d = new PythonSyntaxHighlighterP;
354 }
355
356 /** Destroys this object. */
357 PythonSyntaxHighlighter::~PythonSyntaxHighlighter()
358 {
359 delete d;
360 }
361
362 /**
363 * Detects all kinds of text to highlight them in the correct color.
364 */
365 void PythonSyntaxHighlighter::highlightBlock(const QString& text)
366 {
367 int i = 0;
368 QChar prev, ch;
369
370 const int Standard = 0; // Standard text
371 const int Digit = 1; // Digits
372 const int Comment = 2; // Comment begins with #
373 const int Literal1 = 3; // String literal beginning with "
374 const int Literal2 = 4; // Other string literal beginning with '
375 const int Blockcomment1 = 5; // Block comments beginning and ending with """
376 const int Blockcomment2 = 6; // Other block comments beginning and ending with '''
377 const int ClassName = 7; // Text after the keyword class
378 const int DefineName = 8; // Text after the keyword def
379
380 int endStateOfLastPara = previousBlockState();
381 if (endStateOfLastPara < 0 || endStateOfLastPara > maximumUserState()) {
382 endStateOfLastPara = Standard;
383 }
384
385 while (i < text.length()) {
386 ch = text.at(i);
387
388 switch (endStateOfLastPara) {
389 case Standard: {
390 switch (ch.unicode()) {
391 case '#': {
392 // begin a comment
393 setFormat(i, 1, this->colorByType(SyntaxHighlighter::Comment));
394 endStateOfLastPara = Comment;
395 } break;
396 case '"': {
397 // Begin either string literal or block comment
398 if ((i >= 2) && text.at(i - 1) == QLatin1Char('"')
399 && text.at(i - 2) == QLatin1Char('"')) {
400 setFormat(i - 2, 3, this->colorByType(SyntaxHighlighter::BlockComment));
401 endStateOfLastPara = Blockcomment1;
402 }
403 else {
404 setFormat(i, 1, this->colorByType(SyntaxHighlighter::String));
405 endStateOfLastPara = Literal1;
406 }
407 } break;
408 case '\'': {
409 // Begin either string literal or block comment
410 if ((i >= 2) && text.at(i - 1) == QLatin1Char('\'')
411 && text.at(i - 2) == QLatin1Char('\'')) {
412 setFormat(i - 2, 3, this->colorByType(SyntaxHighlighter::BlockComment));
413 endStateOfLastPara = Blockcomment2;
414 }
415 else {
416 setFormat(i, 1, this->colorByType(SyntaxHighlighter::String));
417 endStateOfLastPara = Literal2;
418 }
419 } break;
420 case ' ':
421 case '\t': {
422 // ignore whitespaces
423 } break;
424 case '(':
425 case ')':
426 case '[':
427 case ']':
428 case '+':
429 case '-':
430 case '*':
431 case '/':
432 case ':':
433 case '%':
434 case '^':
435 case '~':
436 case '!':
437 case '=':
438 case '<':
439 case '>': // possibly two characters
440 {
441 setFormat(i, 1, this->colorByType(SyntaxHighlighter::Operator));
442 endStateOfLastPara = Standard;
443 } break;
444 default: {
445 // Check for normal text
446 if (ch.isLetter() || ch == QLatin1Char('_')) {
447 QString buffer;
448 int j = i;
449 while (ch.isLetterOrNumber() || ch == QLatin1Char('_')) {
450 buffer += ch;
451 ++j;
452 if (j >= text.length()) {
453 break; // end of text
454 }
455 ch = text.at(j);
456 }
457
458 if (d->keywords.contains(buffer) != 0) {
459 if (buffer == QLatin1String("def")) {
460 endStateOfLastPara = DefineName;
461 }
462 else if (buffer == QLatin1String("class")) {
463 endStateOfLastPara = ClassName;
464 }
465
466 QTextCharFormat keywordFormat;
467 keywordFormat.setForeground(
468 this->colorByType(SyntaxHighlighter::Keyword)
469 );
470 keywordFormat.setFontWeight(QFont::Bold);
471 setFormat(i, buffer.length(), keywordFormat);
472 }
473 else {
474 setFormat(i, buffer.length(), this->colorByType(SyntaxHighlighter::Text));
475 }
476
477 // increment i
478 if (!buffer.isEmpty()) {
479 i = j - 1;
480 }
481 }
482 // this is the beginning of a number
483 else if (ch.isDigit()) {
484 setFormat(i, 1, this->colorByType(SyntaxHighlighter::Number));
485 endStateOfLastPara = Digit;
486 }
487 // probably an operator
488 else if (ch.isSymbol() || ch.isPunct()) {
489 setFormat(i, 1, this->colorByType(SyntaxHighlighter::Operator));
490 }
491 }
492 }
493 } break;
494 case Comment: {
495 setFormat(i, 1, this->colorByType(SyntaxHighlighter::Comment));
496 } break;
497 case Literal1: {
498 setFormat(i, 1, this->colorByType(SyntaxHighlighter::String));
499 if (ch == QLatin1Char('"')) {
500 endStateOfLastPara = Standard;
501 }
502 } break;
503 case Literal2: {
504 setFormat(i, 1, this->colorByType(SyntaxHighlighter::String));
505 if (ch == QLatin1Char('\'')) {
506 endStateOfLastPara = Standard;
507 }
508 } break;
509 case Blockcomment1: {
510 setFormat(i, 1, this->colorByType(SyntaxHighlighter::BlockComment));
511 if (i >= 2 && ch == QLatin1Char('"') && text.at(i - 1) == QLatin1Char('"')
512 && text.at(i - 2) == QLatin1Char('"')) {
513 endStateOfLastPara = Standard;
514 }
515 } break;
516 case Blockcomment2: {
517 setFormat(i, 1, this->colorByType(SyntaxHighlighter::BlockComment));
518 if (i >= 2 && ch == QLatin1Char('\'') && text.at(i - 1) == QLatin1Char('\'')
519 && text.at(i - 2) == QLatin1Char('\'')) {
520 endStateOfLastPara = Standard;
521 }
522 } break;
523 case DefineName: {
524 if (ch.isLetterOrNumber() || ch == QLatin1Char(' ') || ch == QLatin1Char('_')) {
525 setFormat(i, 1, this->colorByType(SyntaxHighlighter::Defname));
526 }
527 else {
528 if (ch.isSymbol() || ch.isPunct()) {
529 setFormat(i, 1, this->colorByType(SyntaxHighlighter::Operator));
530 }
531 endStateOfLastPara = Standard;
532 }
533 } break;
534 case ClassName: {
535 if (ch.isLetterOrNumber() || ch == QLatin1Char(' ') || ch == QLatin1Char('_')) {
536 setFormat(i, 1, this->colorByType(SyntaxHighlighter::Classname));
537 }
538 else {
539 if (ch.isSymbol() || ch.isPunct()) {
540 setFormat(i, 1, this->colorByType(SyntaxHighlighter::Operator));
541 }
542 endStateOfLastPara = Standard;
543 }
544 } break;
545 case Digit: {
546 if (ch.isDigit() || ch == QLatin1Char('.')) {
547 setFormat(i, 1, this->colorByType(SyntaxHighlighter::Number));
548 }
549 else {
550 if (ch.isSymbol() || ch.isPunct()) {
551 setFormat(i, 1, this->colorByType(SyntaxHighlighter::Operator));
552 }
553 endStateOfLastPara = Standard;
554 }
555 } break;
556 }
557
558 prev = ch;
559 i++;
560 }
561
562 // only block comments can have several lines
563 if (endStateOfLastPara != Blockcomment1 && endStateOfLastPara != Blockcomment2) {
564 endStateOfLastPara = Standard;
565 }
566
567 setCurrentBlockState(endStateOfLastPara);
568 }
569
570 #include "moc_PythonEditor.cpp"