Debian Codegraph @

src/Gui/PythonConsole.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 <QApplication>
25 #include <QClipboard>
26 #include <QDockWidget>
27 #include <QKeyEvent>
28 #include <QMenu>
29 #include <QMessageBox>
30 #include <QMimeData>
31 #include <QTextCursor>
32 #include <QTextDocumentFragment>
33 #include <QTextStream>
34 #include <QTime>
35 #include <QUrl>
36
37
38 #include <Base/Interpreter.h>
39 #include <Base/Color.h>
40
41 #include "PythonConsole.h"
42 #include "PythonConsolePy.h"
43 #include "PythonTracing.h"
44 #include "Application.h"
45 #include "FileDialog.h"
46 #include "MainWindow.h"
47 #include "Tools.h"
48
49
50 using namespace Gui;
51
52 namespace Gui
53 {
54
55 static const QChar promptEnd(QLatin1Char(' ')); //< char for detecting prompt end
56
57 inline int promptLength(const QString& lineStr)
58 {
59 return lineStr.indexOf(promptEnd) + 1;
60 }
61
62 inline QString stripPromptFrom(const QString& lineStr)
63 {
64 return lineStr.mid(promptLength(lineStr));
65 }
66
67 /**
68 * cursorBeyond checks if cursor is at a valid position to accept keyEvents.
69 * @param cursor - cursor to check
70 * @param limit - cursor that marks the begin of the input region
71 * @param shift - offset for shifting the limit for non-selection cursors [default: 0]
72 * @return true if a keyEvent is ok at cursor's position, false otherwise
73 */
74 inline bool cursorBeyond(const QTextCursor& cursor, const QTextCursor& limit, int shift = 0)
75 {
76 int pos = limit.position();
77 if (cursor.hasSelection()) {
78 return (cursor.selectionStart() >= pos && cursor.selectionEnd() >= pos);
79 }
80
81 return cursor.position() >= (pos + shift);
82 }
83
84 struct PythonConsoleP
85 {
86 enum Output
87 {
88 Error = 20,
89 Message = 21
90 };
91 enum CopyType
92 {
93 Normal,
94 History,
95 Command
96 };
97 CopyType type;
98 PyObject *_stdoutPy = nullptr, *_stderrPy = nullptr, *_stdinPy = nullptr, *_stdin = nullptr;
99 InteractiveInterpreter* interpreter = nullptr;
100 ConsoleHistory history;
101 QString output, error, info, historyFile;
102 QStringList statements;
103 bool interactive;
104 ParameterGrp::handle hGrpSettings;
105 PythonConsoleP()
106 {
107 type = Normal;
108 interactive = false;
109 historyFile = QString::fromUtf8(
110 (App::Application::getUserAppDataDir() + "PythonHistory.log").c_str()
111 );
112 }
113 };
114
115 struct InteractiveInterpreterP
116 {
117 PyObject* interpreter {nullptr};
118 PyObject* sysmodule {nullptr};
119 QStringList buffer;
120 PythonTracing trace;
121 };
122
123 } // namespace Gui
124
125 InteractiveInterpreter::InteractiveInterpreter()
126 {
127 // import code.py and create an instance of InteractiveInterpreter
128 Base::PyGILStateLocker lock;
129 PyObject* module = PyImport_ImportModule("code");
130 if (!module) {
131 throw Base::PyException();
132 }
133 PyObject* func = PyObject_GetAttrString(module, "InteractiveInterpreter");
134 PyObject* args = Py_BuildValue("()");
135 d = new InteractiveInterpreterP;
136 d->interpreter = PyObject_CallObject(func, args);
137 Py_DECREF(args);
138 Py_DECREF(func);
139 Py_DECREF(module);
140
141 setPrompt();
142 }
143
144 InteractiveInterpreter::~InteractiveInterpreter()
145 {
146 Base::PyGILStateLocker lock;
147 Py_XDECREF(d->interpreter);
148 Py_XDECREF(d->sysmodule);
149 delete d;
150 }
151
152 /**
153 * Set the ps1 and ps2 members of the sys module if not yet defined.
154 */
155 void InteractiveInterpreter::setPrompt()
156 {
157 // import code.py and create an instance of InteractiveInterpreter
158 Base::PyGILStateLocker lock;
159 d->sysmodule = PyImport_ImportModule("sys");
160 if (!PyObject_HasAttrString(d->sysmodule, "ps1")) {
161 PyObject_SetAttrString(d->sysmodule, "ps1", PyUnicode_FromString(">>> "));
162 }
163 if (!PyObject_HasAttrString(d->sysmodule, "ps2")) {
164 PyObject_SetAttrString(d->sysmodule, "ps2", PyUnicode_FromString("... "));
165 }
166 }
167
168 /**
169 * Compile a command and determine whether it is incomplete.
170 *
171 * The source string may contain line feeds and/or carriage returns. \n
172 * Return value / exceptions raised:
173 * - Return a code object if the command is complete and valid
174 * - Return None if the command is incomplete
175 * - Raise SyntaxError, ValueError or OverflowError if the command is a
176 * syntax error (OverflowError and ValueError can be produced by
177 * malformed literals).
178 */
179 PyObject* InteractiveInterpreter::compile(const char* source) const
180 {
181 Base::PyGILStateLocker lock;
182 PyObject* func = PyObject_GetAttrString(d->interpreter, "compile");
183 PyObject* args = Py_BuildValue("(s)", source);
184 PyObject* eval = PyObject_CallObject(func, args); // must decref later
185
186 Py_XDECREF(args);
187 Py_XDECREF(func);
188
189 if (eval) {
190 return eval;
191 }
192 else {
193 // do not throw Base::PyException as this clears the error indicator
194 throw Base::RuntimeError("Code evaluation failed");
195 }
196
197 // can never happen
198 return nullptr;
199 }
200
201 /**
202 * Compile a command and determine whether it is incomplete.
203 *
204 * The source string may contain line feeds and/or carriage returns. \n
205 * Return value:
206 * - Return 1 if the command is incomplete
207 * - Return 0 if the command is complete and valid
208 * - Return -1 if the command is a syntax error
209 * .
210 * (OverflowError and ValueError can be produced by malformed literals).
211 */
212 int InteractiveInterpreter::compileCommand(const char* source) const
213 {
214 Base::PyGILStateLocker lock;
215 PyObject* func = PyObject_GetAttrString(d->interpreter, "compile");
216 PyObject* args = Py_BuildValue("(s)", source);
217 PyObject* eval = PyObject_CallObject(func, args); // must decref later
218
219 Py_DECREF(args);
220 Py_DECREF(func);
221
222 int ret = 0;
223 if (eval) {
224 if (PyObject_TypeCheck(Py_None, eval->ob_type)) {
225 ret = 1; // incomplete
226 }
227 else {
228 ret = 0; // complete
229 }
230 Py_DECREF(eval);
231 }
232 else {
233 ret = -1; // invalid
234 }
235
236 return ret;
237 }
238
239 /**
240 * Compile and run some source in the interpreter.
241 *
242 * One several things can happen:
243 *
244 * - The input is incorrect; compile() raised an exception (SyntaxError or OverflowError).
245 * A syntax traceback will be printed by calling Python's PyErr_Print() method to the redirected
246 * stderr.
247 *
248 * - The input is incomplete, and more input is required; compile() returned 'None'.
249 * Nothing happens.
250 *
251 * - The input is complete; compile() returned a code object. The code is executed by calling
252 * runCode() (which also handles run-time exceptions, except for SystemExit).
253 * .
254 * The return value is True if the input is incomplete, False in the other cases (unless
255 * an exception is raised). The return value can be used to decide whether to use sys.ps1
256 * or sys.ps2 to prompt the next line.
257 */
258 bool InteractiveInterpreter::runSource(const char* source) const
259 {
260 Base::PyGILStateLocker lock;
261 PyObject* code;
262 try {
263 code = compile(source);
264 }
265 catch (const Base::Exception&) {
266 // A system, overflow or value error was raised.
267 // We clear the traceback info as this might be a longly
268 // message we don't need.
269 PyObject *errobj, *errdata, *errtraceback;
270 PyErr_Fetch(&errobj, &errdata, &errtraceback);
271 PyErr_Restore(errobj, errdata, nullptr);
272 // print error message
273 if (PyErr_Occurred()) {
274 PyErr_Print();
275 }
276 return false;
277 }
278
279 // the command is incomplete
280 if (PyObject_TypeCheck(Py_None, code->ob_type)) {
281 Py_DECREF(code);
282 return true;
283 }
284
285 // run the code and return false
286 runCode((PyCodeObject*)code);
287 return false;
288 }
289
290 bool InteractiveInterpreter::isOccupied() const
291 {
292 return d->trace.isActive();
293 }
294
295 bool InteractiveInterpreter::interrupt() const
296 {
297 return d->trace.interrupt();
298 }
299
300 /* Execute a code object.
301 *
302 * When an exception occurs, a traceback is displayed.
303 * All exceptions are caught except SystemExit, which is reraised.
304 */
305 void InteractiveInterpreter::runCode(PyCodeObject* code) const
306 {
307 if (isOccupied()) {
308 return;
309 }
310
311 d->trace.fetchFromSettings();
312 PythonTracingLocker tracelock(d->trace);
313
314 Base::PyGILStateLocker lock;
315 PyObject *module, *dict, *presult; /* "exec code in d, d" */
316 module = PyImport_AddModule("__main__"); /* get module, init python */
317 if (!module) {
318 throw Base::PyException(); /* not incref'd */
319 }
320 dict = PyModule_GetDict(module); /* get dict namespace */
321 if (!dict) {
322 throw Base::PyException(); /* not incref'd */
323 }
324
325 // It seems that the return value is always 'None' or Null
326 presult = PyEval_EvalCode((PyObject*)code, dict, dict); /* run compiled bytecode */
327 Py_XDECREF(code); /* decref the code object */
328 if (!presult) {
329 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
330 // throw SystemExit exception
331 throw Base::SystemExitException();
332 }
333 if (PyErr_Occurred()) { /* get latest python exception information */
334 PyObject *errobj, *errdata, *errtraceback;
335 PyErr_Fetch(&errobj, &errdata, &errtraceback);
336 // the error message can be empty so errdata will be null
337 if (errdata && PyDict_Check(errdata)) {
338 PyObject* value = PyDict_GetItemString(errdata, "swhat");
339 if (value) {
340 Base::RuntimeError e;
341 e.setPyObject(errdata);
342 Py_DECREF(errdata);
343
344 std::stringstream str;
345 str << e.what();
346 if (!e.getFunction().empty()) {
347 str << " In " << e.getFunction();
348 }
349 if (!e.getFile().empty() && e.getLine() > 0) {
350 std::string file = e.getFile();
351 std::size_t pos = file.find("src");
352 if (pos != std::string::npos) {
353 file = file.substr(pos);
354 }
355 str << " in " << file << ":" << e.getLine();
356 }
357
358 std::string err = str.str();
359 errdata = PyUnicode_FromString(err.c_str());
360 }
361 }
362 PyErr_Restore(errobj, errdata, errtraceback);
363 PyErr_Print(); /* and print the error to the error output */
364 }
365 }
366 else {
367 Py_DECREF(presult);
368 }
369 }
370
371 /**
372 * Store the line into the internal buffer and compile the total buffer.
373 * In case it is a complete Python command the buffer is emptied.
374 */
375 bool InteractiveInterpreter::push(const char* line)
376 {
377 d->buffer.append(QString::fromUtf8(line));
378 QString source = d->buffer.join(QLatin1String("\n"));
379 try {
380 bool more = runSource(source.toUtf8());
381 if (!more) {
382 d->buffer.clear();
383 }
384 return more;
385 }
386 catch (const Base::SystemExitException&) {
387 d->buffer.clear();
388 throw;
389 }
390 catch (...) {
391 // indication of unhandled exception
392 d->buffer.clear();
393 if (PyErr_Occurred()) {
394 PyErr_Print();
395 }
396 throw;
397 }
398
399 return false;
400 }
401
402 bool InteractiveInterpreter::hasPendingInput() const
403 {
404 return (!d->buffer.isEmpty());
405 }
406
407 QStringList InteractiveInterpreter::getBuffer() const
408 {
409 return d->buffer;
410 }
411
412 void InteractiveInterpreter::setBuffer(const QStringList& buf)
413 {
414 d->buffer = buf;
415 }
416
417 void InteractiveInterpreter::clearBuffer()
418 {
419 d->buffer.clear();
420 }
421
422 /* TRANSLATOR Gui::PythonConsole */
423
424 /**
425 * Constructs a PythonConsole which is a child of 'parent'.
426 */
427 PythonConsole::PythonConsole(QWidget* parent)
428 : PythonTextEditor(parent)
429 , _sourceDrain(nullptr)
430 {
431 d = new PythonConsoleP();
432 d->interactive = false;
433
434 // create an instance of InteractiveInterpreter
435 try {
436 d->interpreter = new InteractiveInterpreter();
437 }
438 catch (const Base::Exception& e) {
439 setPlainText(QString::fromLatin1(e.what()));
440 setEnabled(false);
441 }
442
443 // use the console highlighter
444 pythonSyntax = new PythonConsoleHighlighter(this);
445 setSyntaxHighlighter(pythonSyntax);
446
447 setVisibleLineNumbers(false);
448 setEnabledHighlightCurrentLine(false);
449 QFont serifFont = QFontDatabase::systemFont(QFontDatabase::FixedFont);
450 serifFont.setPointSize(10);
451 setFont(serifFont);
452
453 // set colors and font from settings
454 ParameterGrp::handle hPrefGrp = getWindowParameter();
455 hPrefGrp->NotifyAll();
456
457 d->hGrpSettings = WindowParameter::getDefaultParameter()->GetGroup("PythonConsole");
458 d->hGrpSettings->Attach(this);
459 d->hGrpSettings->NotifyAll();
460
461 // disable undo/redo stuff
462 setUndoRedoEnabled(false);
463 setAcceptDrops(true);
464
465 // try to override Python's stdout/err
466 Base::PyGILStateLocker lock;
467 d->_stdoutPy = new PythonStdout(this);
468 d->_stderrPy = new PythonStderr(this);
469 d->_stdinPy = new PythonStdin(this);
470 d->_stdin = PySys_GetObject("stdin");
471
472 // Don't override stdin when running FreeCAD as Python module
473 auto& cfg = App::Application::Config();
474 auto overrideStdIn = cfg.find("DontOverrideStdIn");
475 if (overrideStdIn == cfg.end()) {
476 PySys_SetObject("stdin", d->_stdinPy);
477 }
478
479 const char* version = PyUnicode_AsUTF8(PySys_GetObject("version"));
480 const char* platform = PyUnicode_AsUTF8(PySys_GetObject("platform"));
481 d->info = QStringLiteral(
482 "Python %1 on %2\n"
483 "Type 'help', 'copyright', 'credits' or 'license' for more information."
484 )
485 .arg(QString::fromLatin1(version), QString::fromLatin1(platform));
486 d->output = d->info;
487 printPrompt(PythonConsole::Complete);
488 loadHistory();
489
490 flusher = new QTimer(this);
491 connect(flusher, &QTimer::timeout, this, &PythonConsole::flushOutput);
492 flusher->start(100);
493 }
494
495 /** Destroys the object and frees any allocated resources */
496 PythonConsole::~PythonConsole()
497 {
498 saveHistory();
499 Base::PyGILStateLocker lock;
500 d->hGrpSettings->Detach(this);
501 Py_XDECREF(d->_stdoutPy);
502 Py_XDECREF(d->_stderrPy);
503 Py_XDECREF(d->_stdinPy);
504 delete d->interpreter;
505 delete d;
506 }
507
508 /** Set new font and colors according to the parameters. */
509 void PythonConsole::OnChange(Base::Subject<const char*>& rCaller, const char* sReason)
510 {
511 const auto& rGrp = static_cast<ParameterGrp&>(rCaller);
512
513 if (strcmp(sReason, "PythonWordWrap") == 0) {
514 bool pythonWordWrap = rGrp.GetBool("PythonWordWrap", true);
515 if (pythonWordWrap) {
516 setWordWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
517 }
518 else {
519 setWordWrapMode(QTextOption::NoWrap);
520 }
521 }
522
523 if (strcmp(sReason, "PythonBlockCursor") == 0) {
524 bool block = rGrp.GetBool("PythonBlockCursor", false);
525 if (block) {
526 setCursorWidth(QFontMetrics(font()).averageCharWidth());
527 }
528 else {
529 setCursorWidth(1);
530 }
531 }
532
533 if (strcmp(sReason, "EnableLineNumber") != 0) {
534 TextEditor::OnChange(rCaller, sReason);
535 }
536 }
537
538 int PythonConsole::getInputStringPosition()
539 {
540 QString rawLine = textCursor().block().text();
541 return textCursor().positionInBlock() - promptLength(rawLine);
542 }
543
544 QString PythonConsole::getInputString()
545 {
546 QString rawLine = textCursor().block().text();
547 return stripPromptFrom(rawLine);
548 }
549
550 /**
551 * Checks the input of the console to make the correct indentations.
552 * After a command is prompted completely the Python interpreter is started.
553 */
554 void PythonConsole::keyPressEvent(QKeyEvent* e)
555 {
556 bool restartHistory = true;
557 QTextCursor cursor = this->textCursor();
558 QTextCursor inputLineBegin = this->inputBegin();
559
560 if (e->key() == Qt::Key_C && e->modifiers() == Qt::ControlModifier) {
561 if (d->interpreter->interrupt()) {
562 return;
563 }
564 }
565
566 if (!cursorBeyond(cursor, inputLineBegin)) {
567 /**
568 * The cursor is placed not on the input line (or within the prompt string)
569 * So we handle key input as follows:
570 * - don't allow changing previous lines.
571 * - allow full movement (no prompt restriction)
572 * - allow copying content (Ctrl+C)
573 * - "escape" to end of input line
574 */
575 switch (e->key()) {
576 case Qt::Key_Return:
577 case Qt::Key_Enter:
578 case Qt::Key_Escape:
579 case Qt::Key_Backspace:
580 this->moveCursor(QTextCursor::End);
581 break;
582
583 default:
584 if (e->text().isEmpty() || e->matches(QKeySequence::Copy)
585 || e->matches(QKeySequence::SelectAll)) {
586 PythonTextEditor::keyPressEvent(e);
587 }
588 else if (!e->text().isEmpty()
589 && (e->modifiers() == Qt::NoModifier || e->modifiers() == Qt::ShiftModifier)) {
590 this->moveCursor(QTextCursor::End);
591 PythonTextEditor::keyPressEvent(e);
592 }
593 break;
594 }
595 }
596 else {
597 /**
598 * The cursor sits somewhere on the input line (after the prompt)
599 * Here we handle key input a bit different:
600 * - restrict cursor movement to input line range (excluding the prompt characters)
601 * - roam the history by Up/Down keys
602 * - show call tips on period
603 */
604 QTextBlock inputBlock = inputLineBegin.block(); //< get the last paragraph's text
605 QString inputLine = inputBlock.text();
606 QString inputStrg = stripPromptFrom(inputLine);
607 if (this->_sourceDrain && !this->_sourceDrain->isEmpty()) {
608 inputStrg = inputLine.mid(this->_sourceDrain->length());
609 }
610
611 switch (e->key()) {
612 case Qt::Key_Escape: {
613 // disable current input string - i.e. put it to history but don't execute it.
614 if (!inputStrg.isEmpty()) {
615 d->history.append(QLatin1String("# ") + inputStrg); //< put commented string to
616 // history ...
617 inputLineBegin.insertText(QStringLiteral("# ")); //< and comment it on console
618 setTextCursor(inputLineBegin);
619 printPrompt(
620 d->interpreter->hasPendingInput() //< print adequate prompt
621 ? PythonConsole::Incomplete
622 : PythonConsole::Complete
623 );
624 }
625 } break;
626
627 case Qt::Key_Return:
628 case Qt::Key_Enter: {
629 d->history.append(inputStrg); //< put statement to history
630 runSource(inputStrg); //< commit input string
631 } break;
632
633 case Qt::Key_Home: {
634 QTextCursor::MoveMode mode = (e->modifiers() & Qt::ShiftModifier)
635 ? QTextCursor::KeepAnchor
636 /* else */
637 : QTextCursor::MoveAnchor;
638 cursor.setPosition(inputLineBegin.position(), mode);
639 setTextCursor(cursor);
640 ensureCursorVisible();
641 } break;
642
643 case Qt::Key_Up: {
644 // if possible, move back in history
645 if (d->history.prev(inputStrg)) {
646 overrideCursor(d->history.value());
647 }
648 restartHistory = false;
649 } break;
650
651 case Qt::Key_Down: {
652 // if possible, move forward in history
653 if (d->history.next()) {
654 overrideCursor(d->history.value());
655 }
656 restartHistory = false;
657 } break;
658
659 case Qt::Key_Left: {
660 if (cursor > inputLineBegin) {
661 PythonTextEditor::keyPressEvent(e);
662 }
663 restartHistory = false;
664 } break;
665
666 case Qt::Key_Right: {
667 PythonTextEditor::keyPressEvent(e);
668 restartHistory = false;
669 } break;
670
671 case Qt::Key_Backspace: {
672 if (cursorBeyond(cursor, inputLineBegin, +1)) {
673 PythonTextEditor::keyPressEvent(e);
674 }
675 } break;
676
677 default: {
678 PythonTextEditor::keyPressEvent(e);
679 } break;
680 }
681
682 // disable history restart if input line changed
683 restartHistory &= (inputLine != inputBlock.text());
684 }
685 // any cursor move resets the history to its latest item.
686 if (restartHistory) {
687 d->history.restart();
688 }
689 }
690
691 /**
692 * Insert an output message to the console. This message comes from
693 * the Python interpreter and is redirected from sys.stdout.
694 */
695 void PythonConsole::insertPythonOutput(const QString& msg)
696 {
697 d->output += msg;
698 }
699
700 /**
701 * Insert an error message to the console. This message comes from
702 * the Python interpreter and is redirected from sys.stderr.
703 */
704 void PythonConsole::insertPythonError(const QString& err)
705 {
706 d->error += err;
707 }
708
709 void PythonConsole::onFlush()
710 {
711 printPrompt(PythonConsole::Flush);
712 }
713
714 void PythonConsole::flushOutput()
715 {
716 if (d->interpreter->isOccupied()) {
717 if (d->output.length() > 0 || d->error.length() > 0) {
718 printPrompt(PythonConsole::Complete);
719 }
720 }
721 }
722
723 /** Prints the ps1 prompt (>>> ) for complete and ps2 prompt (... ) for
724 * incomplete commands to the console window.
725 */
726 void PythonConsole::printPrompt(PythonConsole::Prompt mode)
727 {
728 // write normal messages
729 if (!d->output.isEmpty()) {
730 appendOutput(d->output, (int)PythonConsoleP::Message);
731 d->output.clear();
732 }
733
734 // write error messages
735 if (!d->error.isEmpty()) {
736 appendOutput(d->error, (int)PythonConsoleP::Error);
737 d->error.clear();
738 }
739
740 // Append the prompt string
741 QTextCursor cursor = textCursor();
742
743 if (mode != PythonConsole::Special) {
744 cursor.beginEditBlock();
745 cursor.movePosition(QTextCursor::End);
746 QTextBlock block = cursor.block();
747
748 // Python's print command appends a trailing '\n' to the system output.
749 // In this case, however, we should not add a new text block. We force
750 // the current block to be normal text (user state = 0) to be highlighted
751 // correctly and append the '>>> ' or '... ' to this block.
752 if (block.length() > 1) {
753 cursor.insertBlock(cursor.blockFormat(), cursor.charFormat());
754 }
755 else {
756 block.setUserState(0);
757 }
758
759 switch (mode) {
760 case PythonConsole::Incomplete:
761 cursor.insertText(QStringLiteral("... "));
762 break;
763 case PythonConsole::Complete:
764 cursor.insertText(QStringLiteral(">>> "));
765 break;
766 default:
767 break;
768 }
769 cursor.endEditBlock();
770 }
771 // move cursor to the end
772 cursor.movePosition(QTextCursor::End);
773 setTextCursor(cursor);
774 }
775
776 /**
777 * Appends \a output to the console and set \a state as user state to
778 * the text block which is needed for the highlighting.
779 */
780 void PythonConsole::appendOutput(const QString& output, int state)
781 {
782 QTextCursor cursor = textCursor();
783 cursor.movePosition(QTextCursor::End);
784 int pos = cursor.position() + 1;
785
786 // delay rehighlighting
787 cursor.beginEditBlock();
788 appendPlainText(output);
789
790 QTextBlock block = this->document()->findBlock(pos);
791 while (block.isValid()) {
792 block.setUserState(state);
793 block = block.next();
794 }
795 cursor.endEditBlock(); // start highlightiong
796 }
797
798 /**
799 * Builds up the Python command and pass it to the interpreter.
800 */
801 void PythonConsole::runSource(const QString& line)
802 {
803 /**
804 * Check if there's a "source drain", which wants to consume the source in another way then just
805 * executing it. If so, put the source to the drain and emit a signal to notify the consumer,
806 * whomever this may be.
807 */
808 if (this->_sourceDrain) {
809 *this->_sourceDrain = line;
810 Q_EMIT pendingSource();
811 return;
812 }
813
814 if (d->interpreter->isOccupied()) {
815 insertPythonError(QStringLiteral("Previous command still running!"));
816 return;
817 }
818
819 bool incomplete = false;
820 Base::PyGILStateLocker lock;
821 PyObject* default_stdout = PySys_GetObject("stdout");
822 PyObject* default_stderr = PySys_GetObject("stderr");
823 PySys_SetObject("stdout", d->_stdoutPy);
824 PySys_SetObject("stderr", d->_stderrPy);
825 d->interactive = true;
826
827 try {
828 d->history.markScratch(); //< mark current history position ...
829 // launch the command now
830 incomplete = d->interpreter->push(line.toUtf8());
831 if (!incomplete) {
832 d->history.doScratch();
833 } //< ... and scratch history entries that might have been added by executing the line.
834 setFocus(); // if focus was lost
835 }
836 catch (const Base::SystemExitException&) {
837 // In Python the exception must be cleared because when the message box below appears
838 // callable Python objects can be invoked and due to a failing assert the application
839 // will be aborted.
840 PyErr_Clear();
841
842 ParameterGrp::handle hPrefGrp = getWindowParameter();
843 bool check = hPrefGrp->GetBool("CheckSystemExit", true);
844 int ret = QMessageBox::Yes;
845 if (check) {
846 ret = QMessageBox::question(
847 this,
848 tr("System exit"),
849 tr("The application is still running.\nExit without saving all data?"),
850 QMessageBox::Yes | QMessageBox::No,
851 QMessageBox::No
852 );
853 }
854 if (ret == QMessageBox::Yes) {
855 PyErr_Clear();
856 throw;
857 }
858 else {
859 PyErr_Clear();
860 }
861 }
862 catch (const Py::Exception&) {
863 QMessageBox::critical(this, tr("Python Console"), tr("Unhandled PyCXX exception."));
864 }
865 catch (const Base::Exception&) {
866 QMessageBox::critical(this, tr("Python Console"), tr("Unhandled FreeCAD exception."));
867 }
868 catch (const std::exception&) {
869 QMessageBox::critical(this, tr("Python Console"), tr("Unhandled std C++ exception."));
870 }
871 catch (...) {
872 QMessageBox::critical(this, tr("Python Console"), tr("Unhandled unknown C++ exception."));
873 }
874
875 printPrompt(incomplete ? PythonConsole::Incomplete : PythonConsole::Complete);
876 PySys_SetObject("stdout", default_stdout);
877 PySys_SetObject("stderr", default_stderr);
878 d->interactive = false;
879 for (const auto& it : d->statements) {
880 printStatement(it);
881 }
882 d->statements.clear();
883 }
884
885 bool PythonConsole::isComment(const QString& source) const
886 {
887 if (source.isEmpty()) {
888 return false;
889 }
890 int i = 0;
891 while (i < source.length()) {
892 QChar ch = source.at(i++);
893 if (ch.isSpace()) {
894 continue;
895 }
896 else if (ch == QLatin1Char('#')) {
897 return true;
898 }
899 else {
900 return false;
901 }
902 }
903
904 return false;
905 }
906
907 /**
908 * Prints the Python statement cmd to the console.
909 * @note The statement gets only printed and added to the history but not invoked.
910 */
911 void PythonConsole::printStatement(const QString& cmd)
912 {
913 // If we are in interactive mode we have to wait until the command is finished,
914 // afterwards we can print the statements.
915 if (d->interactive) {
916 d->statements << cmd;
917 return;
918 }
919
920 QTextCursor cursor = textCursor();
921 QStringList statements = cmd.split(QLatin1String("\n"));
922 for (const auto& statement : statements) {
923 // go to the end before inserting new text
924 cursor.movePosition(QTextCursor::End);
925 cursor.insertText(statement);
926 d->history.append(statement);
927 printPrompt(PythonConsole::Complete);
928 }
929 }
930
931 /**
932 * Shows the Python window and sets the focus to set text cursor.
933 */
934 void PythonConsole::showEvent(QShowEvent* e)
935 {
936 TextEdit::showEvent(e);
937 // set also the text cursor to the edit field
938 setFocus();
939 }
940
941 void PythonConsole::visibilityChanged(bool visible)
942 {
943 if (visible) {
944 setFocus();
945 }
946 }
947
948 void PythonConsole::changeEvent(QEvent* e)
949 {
950 if (e->type() == QEvent::ParentChange) {
951 auto dw = qobject_cast<QDockWidget*>(this->parentWidget());
952 if (dw) {
953 connect(dw, &QDockWidget::visibilityChanged, this, &PythonConsole::visibilityChanged);
954 }
955 }
956 else if (e->type() == QEvent::StyleChange) {
957 QPalette pal = qApp->palette();
958 QColor color = pal.windowText().color();
959 unsigned int text = Base::Color::asPackedRGB<QColor>(color);
960 auto value = static_cast<unsigned long>(text);
961 // if this parameter is not already set use the style's window text color
962 value = getWindowParameter()->GetUnsigned("Text", value);
963 getWindowParameter()->SetUnsigned("Text", value);
964 }
965 TextEdit::changeEvent(e);
966 }
967
968 void PythonConsole::mouseReleaseEvent(QMouseEvent* e)
969 {
970 if (e->button() == Qt::MiddleButton && e->spontaneous()) {
971 // on Linux-like systems the middle mouse button is typically connected to a paste operation
972 // which will insert some text at the mouse position
973 QTextCursor cursor = this->textCursor();
974 if (cursor < this->inputBegin()) {
975 cursor.movePosition(QTextCursor::End);
976 this->setTextCursor(cursor);
977 }
978 // the text will be pasted at the cursor position (as for Ctrl-V operation)
979 QRect newPos = this->cursorRect();
980
981 // Now we must amend the received event and pass forward. As e->setLocalPos() is only
982 // available in Qt>=5.8, let's stop the original event propagation and generate a fake event
983 // with corrected pointer position (inside the prompt line of the widget)
984 #if QT_VERSION < QT_VERSION_CHECK(6, 4, 0)
985 QMouseEvent newEv(
986 e->type(),
987 QPoint(newPos.x(), newPos.y()),
988 e->button(),
989 e->buttons(),
990 e->modifiers()
991 );
992 #else
993 QMouseEvent newEv(
994 e->type(),
995 QPoint(newPos.x(), newPos.y()),
996 e->globalPosition(),
997 e->button(),
998 e->buttons(),
999 e->modifiers()
1000 );
1001 #endif
1002 e->accept();
1003 QCoreApplication::sendEvent(this->viewport(), &newEv);
1004 return;
1005 }
1006 TextEdit::mouseReleaseEvent(e);
1007 }
1008
1009 /**
1010 * Drops the event \a e and writes the right Python command.
1011 */
1012 void PythonConsole::dropEvent(QDropEvent* e)
1013 {
1014 const QMimeData* mimeData = e->mimeData();
1015 if (mimeData->hasFormat(QLatin1String("text/x-action-items"))) {
1016 QByteArray itemData = mimeData->data(QLatin1String("text/x-action-items"));
1017 QDataStream dataStream(&itemData, QIODevice::ReadOnly);
1018
1019 int ctActions;
1020 dataStream >> ctActions;
1021 for (int i = 0; i < ctActions; i++) {
1022 QString action;
1023 dataStream >> action;
1024 printStatement(QStringLiteral("Gui.runCommand(\"%1\")").arg(action));
1025 }
1026
1027 e->setDropAction(Qt::CopyAction);
1028 e->accept();
1029 }
1030 else {
1031 // always copy text when doing drag and drop
1032 if (mimeData->hasText()) {
1033 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
1034 QTextCursor cursor = this->cursorForPosition(e->pos());
1035 #else
1036 QTextCursor cursor = this->cursorForPosition(e->position().toPoint());
1037 #endif
1038 QTextCursor inputLineBegin = this->inputBegin();
1039
1040 if (!cursorBeyond(cursor, inputLineBegin)) {
1041 this->moveCursor(QTextCursor::End);
1042
1043 QRect newPos = this->cursorRect();
1044
1045 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
1046 QDropEvent newEv(
1047 QPoint(newPos.x(), newPos.y()),
1048 Qt::CopyAction,
1049 mimeData,
1050 e->mouseButtons(),
1051 e->keyboardModifiers()
1052 );
1053 #else
1054 QDropEvent newEv(
1055 QPoint(newPos.x(), newPos.y()),
1056 Qt::CopyAction,
1057 mimeData,
1058 e->buttons(),
1059 e->modifiers()
1060 );
1061 #endif
1062 e->accept();
1063 QPlainTextEdit::dropEvent(&newEv);
1064 }
1065 else {
1066 e->setDropAction(Qt::CopyAction);
1067 QPlainTextEdit::dropEvent(e);
1068 }
1069 }
1070 else {
1071 // this will call insertFromMimeData
1072 QPlainTextEdit::dropEvent(e);
1073 }
1074 }
1075 }
1076
1077 /** Dragging of action objects is allowed. */
1078 void PythonConsole::dragMoveEvent(QDragMoveEvent* e)
1079 {
1080 const QMimeData* mimeData = e->mimeData();
1081 if (mimeData->hasFormat(QLatin1String("text/x-action-items"))) {
1082 e->accept();
1083 }
1084 else {
1085 // this will call canInsertFromMimeData
1086 QPlainTextEdit::dragMoveEvent(e);
1087 }
1088 }
1089
1090 /** Dragging of action objects is allowed. */
1091 void PythonConsole::dragEnterEvent(QDragEnterEvent* e)
1092 {
1093 const QMimeData* mimeData = e->mimeData();
1094 if (mimeData->hasFormat(QLatin1String("text/x-action-items"))) {
1095 e->accept();
1096 }
1097 else {
1098 // this will call canInsertFromMimeData
1099 QPlainTextEdit::dragEnterEvent(e);
1100 }
1101 }
1102
1103 bool PythonConsole::canInsertFromMimeData(const QMimeData* source) const
1104 {
1105 if (source->hasText()) {
1106 return true;
1107 }
1108 if (source->hasUrls()) {
1109 QList<QUrl> uri = source->urls();
1110 for (const auto& it : uri) {
1111 QFileInfo info(it.toLocalFile());
1112 if (info.exists() && info.isFile()) {
1113 QString ext = info.suffix().toLower();
1114 if (ext == QLatin1String("py") || ext == QLatin1String("fcmacro")) {
1115 return true;
1116 }
1117 }
1118 }
1119 }
1120
1121 return false;
1122 }
1123
1124 /**
1125 * Allow one to paste plain text or urls of text files.
1126 */
1127 void PythonConsole::insertFromMimeData(const QMimeData* source)
1128 {
1129 if (!source) {
1130 return;
1131 }
1132 // First check on urls instead of text otherwise it may happen that a url
1133 // is handled as text
1134 bool existingFile = false;
1135 if (source->hasUrls()) {
1136 QList<QUrl> uri = source->urls();
1137 for (const auto& it : uri) {
1138 // get the file name and check the extension
1139 QFileInfo info(it.toLocalFile());
1140 QString ext = info.suffix().toLower();
1141 if (info.exists()) {
1142 existingFile = true;
1143 if (info.isFile() && (ext == QLatin1String("py") || ext == QLatin1String("fcmacro"))) {
1144 // load the file and read-in the source code
1145 QFile file(info.absoluteFilePath());
1146 if (file.open(QIODevice::ReadOnly)) {
1147 QTextStream str(&file);
1148 runSourceFromMimeData(str.readAll());
1149 }
1150 file.close();
1151 }
1152 }
1153 }
1154 }
1155
1156 // Some applications copy text into the clipboard with the formats
1157 // 'text/plain' and 'text/uri-list'. In case the url is not an existing
1158 // file we can handle it as normal text, then. See forum thread:
1159 // https://forum.freecad.org/viewtopic.php?f=3&t=34618
1160 if (source->hasText() && !existingFile) {
1161 runSourceFromMimeData(source->text());
1162 }
1163 }
1164
1165 QTextCursor PythonConsole::inputBegin() const
1166 {
1167 // construct cursor at begin of input line ...
1168 QTextCursor inputLineBegin(this->textCursor());
1169 inputLineBegin.movePosition(QTextCursor::End);
1170 inputLineBegin.movePosition(QTextCursor::StartOfBlock);
1171 // ... and move cursor right beyond the prompt.
1172 int prompt = promptLength(inputLineBegin.block().text());
1173 if (this->_sourceDrain && !this->_sourceDrain->isEmpty()) {
1174 prompt = this->_sourceDrain->length();
1175 }
1176 inputLineBegin.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor, prompt);
1177 return inputLineBegin;
1178 }
1179
1180 QMimeData* PythonConsole::createMimeDataFromSelection() const
1181 {
1182 auto mime = new QMimeData();
1183
1184 switch (d->type) {
1185 case PythonConsoleP::Normal: {
1186 const QTextDocumentFragment fragment(textCursor());
1187 mime->setText(fragment.toPlainText());
1188 } break;
1189 case PythonConsoleP::Command: {
1190 QTextCursor cursor = textCursor();
1191 int s = cursor.selectionStart();
1192 int e = cursor.selectionEnd();
1193 QTextBlock b;
1194 QStringList lines;
1195 for (b = document()->begin(); b.isValid(); b = b.next()) {
1196 int pos = b.position();
1197 if (pos >= s && pos <= e) {
1198 if (b.userState() > -1 && b.userState() < pythonSyntax->maximumUserState()) {
1199 lines << stripPromptFrom(b.text());
1200 }
1201 }
1202 }
1203
1204 QString text = lines.join(QLatin1String("\n"));
1205 mime->setText(text);
1206 } break;
1207 case PythonConsoleP::History: {
1208 const QStringList& hist = d->history.values();
1209 QString text = hist.join(QLatin1String("\n"));
1210 mime->setText(text);
1211 } break;
1212 }
1213
1214 return mime;
1215 }
1216
1217 void PythonConsole::runSourceFromMimeData(const QString& source)
1218 {
1219 // When inserting a big text block we must break it down into several command
1220 // blocks instead of processing the text block as a whole or each single line.
1221 // If we processed the complete block as a whole only the first valid Python
1222 // command would be executed and the rest would be ignored. However, if we
1223 // processed each line separately the interpreter might be confused that a block
1224 // is complete but it might be not. This is for instance, if a class or method
1225 // definition contains several empty lines which leads to error messages (almost
1226 // indentation errors) later on.
1227 QString text = source;
1228 if (text.isNull()) {
1229 return;
1230 }
1231
1232 #if defined(Q_OS_LINUX)
1233 // Need to convert CRLF to LF
1234 text.replace(QLatin1String("\r\n"), QLatin1String("\n"));
1235 #elif defined(Q_OS_WIN32)
1236 // Need to convert CRLF to LF
1237 text.replace(QLatin1String("\r\n"), QLatin1String("\n"));
1238 #elif defined(Q_OS_MACOS)
1239 // need to convert CR to LF
1240 text.replace(QLatin1Char('\r'), QLatin1Char('\n'));
1241 #endif
1242
1243 // separate the lines and get the last one
1244 QStringList lines = text.split(QLatin1Char('\n'));
1245 QString last = lines.back();
1246 lines.pop_back();
1247
1248 QTextCursor cursor = textCursor();
1249 QStringList buffer = d->interpreter->getBuffer();
1250 d->interpreter->clearBuffer();
1251
1252 int countNewlines = lines.count(), i = 0;
1253 for (QStringList::Iterator it = lines.begin(); it != lines.end(); ++it, ++i) {
1254 QString line = *it;
1255
1256 // insert the text to the current cursor position
1257 cursor.insertText(*it);
1258
1259 // for the very first line get the complete block
1260 // because it may differ from the inserted text
1261 if (i == 0) {
1262 // get the text from the current cursor position to the end, remove it
1263 // and add it to the last line
1264 cursor.movePosition(QTextCursor::End, QTextCursor::KeepAnchor);
1265 QString select = cursor.selectedText();
1266 cursor.removeSelectedText();
1267 last = last + select;
1268 line = stripPromptFrom(cursor.block().text());
1269 }
1270
1271 // put statement to the history
1272 d->history.append(line);
1273
1274 buffer.append(line);
1275 int ret = d->interpreter->compileCommand(buffer.join(QLatin1String("\n")).toUtf8());
1276 if (ret == 1) { // incomplete
1277 printPrompt(PythonConsole::Incomplete);
1278 }
1279 else if (ret == 0) { // complete
1280 // check if the following lines belong to the previous block
1281 int k = i + 1;
1282 QString nextline;
1283 while ((nextline.isEmpty() || isComment(nextline)) && k < countNewlines) {
1284 nextline = lines[k];
1285 k++;
1286 }
1287
1288 int ret = d->interpreter->compileCommand(nextline.toUtf8());
1289
1290 // If the line is valid, i.e. complete or incomplete the previous block
1291 // is finished
1292 if (ret == -1) {
1293 // the command is not finished yet
1294 printPrompt(PythonConsole::Incomplete);
1295 }
1296 else {
1297 runSource(buffer.join(QLatin1String("\n")));
1298 buffer.clear();
1299 }
1300 }
1301 else { // invalid
1302 runSource(buffer.join(QLatin1String("\n")));
1303 ensureCursorVisible();
1304 return; // exit the method on error
1305 }
1306 }
1307
1308 // set the incomplete block to the interpreter and insert the last line
1309 d->interpreter->setBuffer(buffer);
1310 cursor.insertText(last);
1311 ensureCursorVisible();
1312 }
1313
1314 /**
1315 * Overwrites the text of the cursor.
1316 */
1317 void PythonConsole::overrideCursor(const QString& txt)
1318 {
1319 // Go to the last line and the fourth position, right after the prompt
1320 QTextCursor cursor = this->inputBegin();
1321 int blockLength = this->textCursor().block().text().length();
1322
1323 cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor, blockLength); //<< select text
1324 // to override
1325 cursor.removeSelectedText();
1326 cursor.insertText(txt);
1327 // move cursor to the end
1328 cursor.movePosition(QTextCursor::End);
1329 setTextCursor(cursor);
1330 }
1331
1332 void PythonConsole::contextMenuEvent(QContextMenuEvent* e)
1333 {
1334 QMenu menu(this);
1335 QAction* a;
1336 bool mayPasteHere = cursorBeyond(this->textCursor(), this->inputBegin());
1337
1338 a = menu.addAction(tr("&Copy"), this, &PythonConsole::copy);
1339 a->setShortcut(QKeySequence(QStringLiteral("CTRL+C")));
1340 a->setEnabled(textCursor().hasSelection());
1341
1342 a = menu.addAction(tr("&Copy Command"), this, &PythonConsole::onCopyCommand);
1343 a->setEnabled(textCursor().hasSelection());
1344
1345 a = menu.addAction(tr("&Copy History"), this, &PythonConsole::onCopyHistory);
1346 a->setEnabled(!d->history.isEmpty());
1347
1348 a = menu.addAction(tr("Save History As…"), this, &PythonConsole::onSaveHistoryAs);
1349 a->setEnabled(!d->history.isEmpty());
1350
1351 QAction* saveh = menu.addAction(tr("Save History"));
1352 saveh->setToolTip(tr("Saves Python history across %1 sessions").arg(qApp->applicationName()));
1353 saveh->setCheckable(true);
1354 saveh->setChecked(d->hGrpSettings->GetBool("SavePythonHistory", false));
1355
1356 menu.addSeparator();
1357
1358 a = menu.addAction(tr("&Paste"), this, &PythonConsole::paste);
1359 a->setShortcut(QKeySequence(QStringLiteral("CTRL+V")));
1360 const QMimeData* md = QApplication::clipboard()->mimeData();
1361 a->setEnabled(mayPasteHere && md && canInsertFromMimeData(md));
1362
1363 a = menu.addAction(tr("Select All"), this, &PythonConsole::selectAll);
1364 a->setShortcut(QKeySequence(QStringLiteral("CTRL+A")));
1365 a->setEnabled(!document()->isEmpty());
1366
1367 a = menu.addAction(tr("Clear Console"), this, &PythonConsole::onClearConsole);
1368 a->setEnabled(!document()->isEmpty());
1369
1370 menu.addSeparator();
1371 menu.addAction(tr("Insert File Name…"), this, &PythonConsole::onInsertFileName);
1372 menu.addSeparator();
1373
1374 QAction* wrap = menu.addAction(tr("Word Wrap"));
1375 wrap->setCheckable(true);
1376
1377 wrap->setChecked(d->hGrpSettings->GetBool("PythonWordWrap", true));
1378 QAction* exec = menu.exec(e->globalPos());
1379 if (exec == wrap) {
1380 d->hGrpSettings->SetBool("PythonWordWrap", wrap->isChecked());
1381 }
1382 else if (exec == saveh) {
1383 d->hGrpSettings->SetBool("SavePythonHistory", saveh->isChecked());
1384 }
1385 }
1386
1387 void PythonConsole::onClearConsole()
1388 {
1389 clear();
1390 d->output = d->info;
1391 printPrompt(PythonConsole::Complete);
1392 }
1393
1394 void PythonConsole::onSaveHistoryAs()
1395 {
1396 QString cMacroPath = QString::fromUtf8(
1397 getDefaultParameter()
1398 ->GetGroup("Macro")
1399 ->GetASCII("MacroPath", App::Application::getUserMacroDir().c_str())
1400 .c_str()
1401 );
1402 QString fn = FileDialog::getSaveFileName(
1403 this,
1404 tr("Save History"),
1405 cMacroPath,
1406 QStringLiteral("%1 (*.FCMacro *.py)").arg(tr("Macro Files"))
1407 );
1408 if (!fn.isEmpty()) {
1409 int dot = fn.indexOf(QLatin1Char('.'));
1410 if (dot != -1) {
1411 QFile f(fn);
1412 if (f.open(QIODevice::WriteOnly)) {
1413 QTextStream t(&f);
1414 const QStringList& hist = d->history.values();
1415 for (const auto& it : hist) {
1416 t << it << "\n";
1417 }
1418 f.close();
1419 }
1420 }
1421 }
1422 }
1423
1424 void PythonConsole::onInsertFileName()
1425 {
1426 QString fn = Gui::FileDialog::getOpenFileName(
1427 Gui::getMainWindow(),
1428 tr("Insert file name"),
1429 QString(),
1430 QStringLiteral("%1 (*.*)").arg(tr("All Files"))
1431 );
1432 if (!fn.isEmpty()) {
1433 insertPlainText(fn);
1434 }
1435 }
1436
1437 /**
1438 * Copy the history of the console into the clipboard.
1439 */
1440 void PythonConsole::onCopyHistory()
1441 {
1442 if (d->history.isEmpty()) {
1443 return;
1444 }
1445 d->type = PythonConsoleP::History;
1446 QMimeData* data = createMimeDataFromSelection();
1447 QApplication::clipboard()->setMimeData(data);
1448 d->type = PythonConsoleP::Normal;
1449 }
1450
1451 /**
1452 * Copy the selected commands into the clipboard. This is a subset of the history.
1453 */
1454 void PythonConsole::onCopyCommand()
1455 {
1456 d->type = PythonConsoleP::Command;
1457 copy();
1458 d->type = PythonConsoleP::Normal;
1459 }
1460
1461 QString PythonConsole::readline()
1462 {
1463 QEventLoop loop;
1464 // output is set to the current prompt which we need to extract
1465 // the actual user input
1466 QString inputBuffer = d->output;
1467
1468 printPrompt(PythonConsole::Special);
1469 this->_sourceDrain = &inputBuffer; //< enable source drain ...
1470 // ... and wait until we get notified about pendingSource
1471 QObject::connect(this, &PythonConsole::pendingSource, &loop, &QEventLoop::quit);
1472 // application is about to quit
1473 if (loop.exec() != 0) {
1474 PyErr_SetInterrupt();
1475 } //< send SIGINT to python
1476 this->_sourceDrain = nullptr; //< disable source drain
1477 return inputBuffer.append(QChar::fromLatin1('\n')); //< pass a newline here, since the
1478 // readline-caller may need it!
1479 }
1480
1481 /**
1482 * loads history contents from the default history file
1483 */
1484 void PythonConsole::loadHistory() const
1485 {
1486 // only load contents if history is empty, to not overwrite anything
1487 if (!d->history.isEmpty()) {
1488 return;
1489 }
1490
1491 if (!d->hGrpSettings->GetBool("SavePythonHistory", false)) {
1492 return;
1493 }
1494 QFile f(d->historyFile);
1495 if (f.open(QIODevice::ReadOnly | QIODevice::Text)) {
1496 QString l;
1497 while (!f.atEnd()) {
1498 l = QString::fromUtf8(f.readLine());
1499 if (!l.isEmpty()) {
1500 l.chop(1); // removes the last \n
1501 d->history.append(l);
1502 }
1503 }
1504 f.close();
1505 }
1506 }
1507
1508 /**
1509 * saves the current history to the default history file
1510 */
1511 void PythonConsole::saveHistory() const
1512 {
1513 if (d->history.isEmpty()) {
1514 return;
1515 }
1516 if (!d->hGrpSettings->GetBool("SavePythonHistory", false)) {
1517 return;
1518 }
1519 QFile f(d->historyFile);
1520 if (f.open(QIODevice::WriteOnly)) {
1521 QTextStream t(&f);
1522 QStringList hist = d->history.values();
1523 // only save last 100 entries so we don't inflate forever...
1524 if (hist.length() > 100) {
1525 hist = hist.mid(hist.length() - 100);
1526 }
1527 for (const auto& it : hist) {
1528 t << it << "\n";
1529 }
1530 f.close();
1531 }
1532 }
1533
1534 // ---------------------------------------------------------------------
1535
1536 PythonConsoleHighlighter::PythonConsoleHighlighter(QObject* parent)
1537 : PythonSyntaxHighlighter(parent)
1538 {}
1539
1540 PythonConsoleHighlighter::~PythonConsoleHighlighter() = default;
1541
1542 void PythonConsoleHighlighter::highlightBlock(const QString& text)
1543 {
1544 const int ErrorOutput = (int)PythonConsoleP::Error;
1545 const int MessageOutput = (int)PythonConsoleP::Message;
1546
1547 // Get user state to re-highlight the blocks in the appropriate format
1548 int stateOfPara = currentBlockState();
1549
1550 switch (stateOfPara) {
1551 case ErrorOutput: {
1552 // Error output
1553 QTextCharFormat errorFormat;
1554 errorFormat.setForeground(color(QLatin1String("Python error")));
1555 errorFormat.setFontItalic(true);
1556 setFormat(0, text.length(), errorFormat);
1557 } break;
1558 case MessageOutput: {
1559 // Normal output
1560 QTextCharFormat outputFormat;
1561 outputFormat.setForeground(color(QLatin1String("Python output")));
1562 setFormat(0, text.length(), outputFormat);
1563 } break;
1564 default: {
1565 PythonSyntaxHighlighter::highlightBlock(text);
1566 } break;
1567 }
1568 }
1569
1570 void PythonConsoleHighlighter::colorChanged(const QString& type, const QColor& col)
1571 {
1572 Q_UNUSED(type);
1573 Q_UNUSED(col);
1574 }
1575
1576 // ---------------------------------------------------------------------
1577
1578 ConsoleHistory::ConsoleHistory()
1579 : _scratchBegin(0)
1580 {
1581 _it = _history.cend();
1582 }
1583
1584 ConsoleHistory::~ConsoleHistory() = default;
1585
1586 void ConsoleHistory::first()
1587 {
1588 _it = _history.cbegin();
1589 }
1590
1591 bool ConsoleHistory::more()
1592 {
1593 return (_it != _history.cend());
1594 }
1595
1596 /**
1597 * next switches the history pointer to the next item.
1598 * While searching the next item, the routine respects the search prefix set by prev().
1599 * @return true if the pointer was switched to a later item, false otherwise.
1600 */
1601 bool ConsoleHistory::next()
1602 {
1603 bool wentNext = false;
1604
1605 // if we didn't reach history's end ...
1606 if (_it != _history.cend()) {
1607 // we go forward until we find an item matching the prefix.
1608 for (++_it; _it != _history.cend(); ++_it) {
1609 if (!_it->isEmpty() && _it->startsWith(_prefix)) {
1610 break;
1611 }
1612 }
1613 // we did a step - no matter of a matching prefix.
1614 wentNext = true;
1615 }
1616 return wentNext;
1617 }
1618
1619 /**
1620 * prev switches the history pointer to the previous item.
1621 * The optional parameter prefix allows one to search the history selectively for commands that
1622 * start with a certain character sequence.
1623 * @param prefix - prefix string for searching backwards in history, empty string by default
1624 * @return true if the pointer was switched to an earlier item, false otherwise.
1625 */
1626 bool ConsoleHistory::prev(const QString& prefix)
1627 {
1628 bool wentPrev = false;
1629
1630 // store prefix if it's the first history access
1631 if (_it == _history.cend()) {
1632 _prefix = prefix;
1633 }
1634
1635 // while we didn't go back or reach history's begin ...
1636 while (!wentPrev && _it != _history.cbegin()) {
1637 // go back in history and check if item matches prefix
1638 // Skip empty items
1639 --_it;
1640 wentPrev = (!_it->isEmpty() && _it->startsWith(_prefix));
1641 }
1642 return wentPrev;
1643 }
1644
1645 bool ConsoleHistory::isEmpty() const
1646 {
1647 return _history.isEmpty();
1648 }
1649
1650 const QString& ConsoleHistory::value() const
1651 {
1652 return (
1653 (_it != _history.end()) ? *_it
1654 /* else */
1655 : _prefix
1656 );
1657 }
1658
1659 void ConsoleHistory::append(const QString& item)
1660 {
1661 _history.append(item);
1662 // reset iterator to make the next history
1663 // access begin with the latest item.
1664 _it = _history.cend();
1665 }
1666
1667 const QStringList& ConsoleHistory::values() const
1668 {
1669 return this->_history;
1670 }
1671
1672 /**
1673 * restart resets the history access to the latest item.
1674 */
1675 void ConsoleHistory::restart()
1676 {
1677 _it = _history.cend();
1678 }
1679
1680 /**
1681 * markScratch stores the current end index of the history list.
1682 * Note: with simply remembering a start index, it does not work to nest scratch regions.
1683 * However, just replace the index keeping by a stack - in case this is be a concern.
1684 */
1685 void ConsoleHistory::markScratch()
1686 {
1687 _scratchBegin = _history.length();
1688 }
1689
1690 /**
1691 * doScratch removes the tail of the history list, starting from the index marked lately.
1692 */
1693 void ConsoleHistory::doScratch()
1694 {
1695 if (_scratchBegin < _history.length()) {
1696 _history.erase(_history.begin() + _scratchBegin, _history.end());
1697 this->restart();
1698 }
1699 }
1700
1701 // -----------------------------------------------------
1702
1703 #include "moc_PythonConsole.cpp"