-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
PythonConsole.cpp
1440 lines (1280 loc) · 48 KB
/
PythonConsole.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***************************************************************************
* Copyright (c) 2004 Werner Mayer <wmayer[at]users.sourceforge.net> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <QApplication>
# include <QClipboard>
# include <QDockWidget>
# include <QGridLayout>
# include <QHBoxLayout>
# include <QKeyEvent>
# include <QMenu>
# include <QMessageBox>
# include <QPushButton>
# include <QSpacerItem>
# include <QTextCursor>
# include <QTextDocumentFragment>
# include <QTextStream>
# include <QUrl>
# include <QMimeData>
#endif
#include "PythonConsole.h"
#include "PythonConsolePy.h"
#include "CallTips.h"
#include "Application.h"
#include "Action.h"
#include "Command.h"
#include "DlgEditorImp.h"
#include "FileDialog.h"
#include "MainWindow.h"
#include <Base/Interpreter.h>
#include <Base/Exception.h>
#include <CXX/Exception.hxx>
using namespace Gui;
namespace Gui
{
static const QChar promptEnd( QLatin1Char(' ') ); //< char for detecting prompt end
inline int promptLength( const QString &lineStr )
{ return lineStr.indexOf( promptEnd ) + 1; }
inline QString stripPromptFrom( const QString &lineStr )
{ return lineStr.mid( promptLength(lineStr) ); }
/**
* cursorBeyond checks if cursor is at a valid position to accept keyEvents.
* @param cursor - cursor to check
* @param limit - cursor that marks the begin of the input region
* @param shift - offset for shifting the limit for non-selection cursors [default: 0]
* @return true if a keyEvent is ok at cursor's position, false otherwise
*/
inline bool cursorBeyond( const QTextCursor &cursor, const QTextCursor &limit, int shift = 0 )
{
int pos = limit.position();
if (cursor.hasSelection())
return (cursor.selectionStart() >= pos && cursor.selectionEnd() >= pos);
else
return cursor.position() >= (pos + shift);
}
struct PythonConsoleP
{
enum Output {Error = 20, Message = 21};
enum CopyType {Normal, History, Command};
CopyType type;
PyObject *_stdoutPy, *_stderrPy, *_stdinPy, *_stdin;
InteractiveInterpreter* interpreter;
CallTipsList* callTipsList;
ConsoleHistory history;
QString output, error, info;
QStringList statements;
bool interactive;
QMap<QString, QColor> colormap; // Color map
PythonConsoleP()
{
type = Normal;
interpreter = 0;
colormap[QLatin1String("Text")] = Qt::black;
colormap[QLatin1String("Bookmark")] = Qt::cyan;
colormap[QLatin1String("Breakpoint")] = Qt::red;
colormap[QLatin1String("Keyword")] = Qt::blue;
colormap[QLatin1String("Comment")] = QColor(0, 170, 0);
colormap[QLatin1String("Block comment")] = QColor(160, 160, 164);
colormap[QLatin1String("Number")] = Qt::blue;
colormap[QLatin1String("String")] = Qt::red;
colormap[QLatin1String("Character")] = Qt::red;
colormap[QLatin1String("Class name")] = QColor(255, 170, 0);
colormap[QLatin1String("Define name")] = QColor(255, 170, 0);
colormap[QLatin1String("Operator")] = QColor(160, 160, 164);
colormap[QLatin1String("Python output")] = QColor(170, 170, 127);
colormap[QLatin1String("Python error")] = Qt::red;
}
};
struct InteractiveInterpreterP
{
PyObject* interpreter;
PyObject* sysmodule;
QStringList buffer;
};
} // namespace Gui
InteractiveInterpreter::InteractiveInterpreter()
{
// import code.py and create an instance of InteractiveInterpreter
Base::PyGILStateLocker lock;
PyObject* module = PyImport_ImportModule("code");
if (!module)
throw Base::PyException();
PyObject* func = PyObject_GetAttrString(module, "InteractiveInterpreter");
PyObject* args = Py_BuildValue("()");
d = new InteractiveInterpreterP;
d->interpreter = PyEval_CallObject(func,args);
Py_DECREF(args);
Py_DECREF(func);
Py_DECREF(module);
setPrompt();
}
InteractiveInterpreter::~InteractiveInterpreter()
{
Base::PyGILStateLocker lock;
Py_XDECREF(d->interpreter);
Py_XDECREF(d->sysmodule);
delete d;
}
/**
* Set the ps1 and ps2 members of the sys module if not yet defined.
*/
void InteractiveInterpreter::setPrompt()
{
// import code.py and create an instance of InteractiveInterpreter
Base::PyGILStateLocker lock;
d->sysmodule = PyImport_ImportModule("sys");
if (!PyObject_HasAttrString(d->sysmodule, "ps1"))
PyObject_SetAttrString(d->sysmodule, "ps1", PyString_FromString(">>> "));
if (!PyObject_HasAttrString(d->sysmodule, "ps2"))
PyObject_SetAttrString(d->sysmodule, "ps2", PyString_FromString("... "));
}
/**
* Compile a command and determine whether it is incomplete.
*
* The source string may contain line feeds and/or carriage returns. \n
* Return value / exceptions raised:
* - Return a code object if the command is complete and valid
* - Return None if the command is incomplete
* - Raise SyntaxError, ValueError or OverflowError if the command is a
* syntax error (OverflowError and ValueError can be produced by
* malformed literals).
*/
PyObject* InteractiveInterpreter::compile(const char* source) const
{
Base::PyGILStateLocker lock;
PyObject* func = PyObject_GetAttrString(d->interpreter, "compile");
PyObject* args = Py_BuildValue("(s)", source);
PyObject* eval = PyEval_CallObject(func,args); // must decref later
Py_DECREF(args);
Py_DECREF(func);
if (eval){
return eval;
} else {
// do not throw Base::PyException as this clears the error indicator
throw Base::Exception();
}
// can never happen
return 0;
}
/**
* Compile a command and determine whether it is incomplete.
*
* The source string may contain line feeds and/or carriage returns. \n
* Return value:
* - Return 1 if the command is incomplete
* - Return 0 if the command is complete and valid
* - Return -1 if the command is a syntax error
* .
* (OverflowError and ValueError can be produced by malformed literals).
*/
int InteractiveInterpreter::compileCommand(const char* source) const
{
Base::PyGILStateLocker lock;
PyObject* func = PyObject_GetAttrString(d->interpreter, "compile");
PyObject* args = Py_BuildValue("(s)", source);
PyObject* eval = PyEval_CallObject(func,args); // must decref later
Py_DECREF(args);
Py_DECREF(func);
int ret = 0;
if (eval){
if (PyObject_TypeCheck(Py_None, eval->ob_type))
ret = 1; // incomplete
else
ret = 0; // complete
Py_DECREF(eval);
} else {
ret = -1; // invalid
}
return ret;
}
/**
* Compile and run some source in the interpreter.
*
* One several things can happen:
*
* - The input is incorrect; compile() raised an exception (SyntaxError or OverflowError).
* A syntax traceback will be printed by calling Python's PyErr_Print() method to the redirected stderr.
*
* - The input is incomplete, and more input is required; compile() returned 'None'.
* Nothing happens.
*
* - The input is complete; compile() returned a code object. The code is executed by calling
* runCode() (which also handles run-time exceptions, except for SystemExit).
* .
* The return value is True if the input is incomplete, False in the other cases (unless
* an exception is raised). The return value can be used to decide whether to use sys.ps1
* or sys.ps2 to prompt the next line.
*/
bool InteractiveInterpreter::runSource(const char* source) const
{
Base::PyGILStateLocker lock;
PyObject* code;
try {
code = compile(source);
} catch (const Base::Exception&) {
// A system, overflow or value error was raised.
// We clear the traceback info as this might be a longly
// message we don't need.
PyObject *errobj, *errdata, *errtraceback;
PyErr_Fetch(&errobj, &errdata, &errtraceback);
PyErr_Restore(errobj, errdata, 0);
// print error message
if (PyErr_Occurred()) PyErr_Print();
return false;
}
// the command is incomplete
if (PyObject_TypeCheck(Py_None, code->ob_type)) {
Py_DECREF(code);
return true;
}
// run the code and return false
runCode((PyCodeObject*)code);
return false;
}
/* Execute a code object.
*
* When an exception occurs, a traceback is displayed.
* All exceptions are caught except SystemExit, which is reraised.
*/
void InteractiveInterpreter::runCode(PyCodeObject* code) const
{
Base::PyGILStateLocker lock;
PyObject *module, *dict, *presult; /* "exec code in d, d" */
module = PyImport_AddModule("__main__"); /* get module, init python */
if (module == NULL)
throw Base::PyException(); /* not incref'd */
dict = PyModule_GetDict(module); /* get dict namespace */
if (dict == NULL)
throw Base::PyException(); /* not incref'd */
// It seems that the return value is always 'None' or Null
presult = PyEval_EvalCode(code, dict, dict); /* run compiled bytecode */
Py_XDECREF(code); /* decref the code object */
if (!presult) {
if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
// throw SystemExit exception
throw Base::SystemExitException();
}
if ( PyErr_Occurred() ) /* get latest python exception information */
PyErr_Print(); /* and print the error to the error output */
} else {
Py_DECREF(presult);
}
}
/**
* Store the line into the internal buffer and compile the total buffer.
* In case it is a complete Python command the buffer is emptied.
*/
bool InteractiveInterpreter::push(const char* line)
{
d->buffer.append(QString::fromAscii(line));
QString source = d->buffer.join(QLatin1String("\n"));
try {
// Source is already UTF-8, so we can use toAscii()
bool more = runSource(source.toAscii());
if (!more)
d->buffer.clear();
return more;
} catch (const Base::SystemExitException&) {
d->buffer.clear();
throw;
} catch (...) {
// indication of unhandled exception
d->buffer.clear();
if (PyErr_Occurred())
PyErr_Print();
throw;
}
return false;
}
bool InteractiveInterpreter::hasPendingInput( void ) const
{
return (!d->buffer.isEmpty());
}
QStringList InteractiveInterpreter::getBuffer() const
{
return d->buffer;
}
void InteractiveInterpreter::setBuffer(const QStringList& buf)
{
d->buffer = buf;
}
void InteractiveInterpreter::clearBuffer()
{
d->buffer.clear();
}
/* TRANSLATOR Gui::PythonConsole */
/**
* Constructs a PythonConsole which is a child of 'parent'.
*/
PythonConsole::PythonConsole(QWidget *parent)
: TextEdit(parent), WindowParameter( "Editor" ), _sourceDrain(NULL)
{
d = new PythonConsoleP();
d->interactive = false;
// create an instance of InteractiveInterpreter
try {
d->interpreter = new InteractiveInterpreter();
} catch (const Base::Exception& e) {
setPlainText(QString::fromAscii(e.what()));
setEnabled(false);
}
// use the console highlighter
pythonSyntax = new PythonConsoleHighlighter(this);
pythonSyntax->setDocument(this->document());
// create the window for call tips
d->callTipsList = new CallTipsList(this);
d->callTipsList->setFrameStyle(QFrame::Box|QFrame::Raised);
d->callTipsList->setLineWidth(2);
installEventFilter(d->callTipsList);
viewport()->installEventFilter(d->callTipsList);
d->callTipsList->setSelectionMode( QAbstractItemView::SingleSelection );
d->callTipsList->hide();
QFont serifFont(QLatin1String("Courier"), 10, QFont::Normal);
setFont(serifFont);
// set colors and font from settings
ParameterGrp::handle hPrefGrp = getWindowParameter();
hPrefGrp->Attach( this );
hPrefGrp->NotifyAll();
// disable undo/redo stuff
setUndoRedoEnabled( false );
setAcceptDrops( true );
// try to override Python's stdout/err
Base::PyGILStateLocker lock;
d->_stdoutPy = new PythonStdout(this);
d->_stderrPy = new PythonStderr(this);
d->_stdinPy = new PythonStdin (this);
d->_stdin = PySys_GetObject("stdin");
PySys_SetObject("stdin", d->_stdinPy);
const char* version = PyString_AsString(PySys_GetObject("version"));
const char* platform = PyString_AsString(PySys_GetObject("platform"));
d->info = QString::fromAscii("Python %1 on %2\n"
"Type 'help', 'copyright', 'credits' or 'license' for more information.")
.arg(QString::fromAscii(version)).arg(QString::fromAscii(platform));
d->output = d->info;
printPrompt(PythonConsole::Complete);
}
/** Destroys the object and frees any allocated resources */
PythonConsole::~PythonConsole()
{
Base::PyGILStateLocker lock;
getWindowParameter()->Detach( this );
delete pythonSyntax;
Py_XDECREF(d->_stdoutPy);
Py_XDECREF(d->_stderrPy);
Py_XDECREF(d->_stdinPy);
delete d->interpreter;
delete d;
}
/** Set new font and colors according to the paramerts. */
void PythonConsole::OnChange( Base::Subject<const char*> &rCaller,const char* sReason )
{
ParameterGrp::handle hPrefGrp = getWindowParameter();
if (strcmp(sReason, "FontSize") == 0 || strcmp(sReason, "Font") == 0) {
int fontSize = hPrefGrp->GetInt("FontSize", 10);
QString fontFamily = QString::fromAscii(hPrefGrp->GetASCII("Font", "Courier").c_str());
QFont font(fontFamily, fontSize);
setFont(font);
QFontMetrics metric(font);
int width = metric.width(QLatin1String("0000"));
setTabStopWidth(width);
} else {
QMap<QString, QColor>::ConstIterator it = d->colormap.find(QString::fromAscii(sReason));
if (it != d->colormap.end()) {
QColor color = it.value();
unsigned long col = (color.red() << 24) | (color.green() << 16) | (color.blue() << 8);
col = hPrefGrp->GetUnsigned( sReason, col);
color.setRgb((col>>24)&0xff, (col>>16)&0xff, (col>>8)&0xff);
pythonSyntax->setColor(QString::fromAscii(sReason), color);
}
}
}
/**
* Checks the input of the console to make the correct indentations.
* After a command is prompted completely the Python interpreter is started.
*/
void PythonConsole::keyPressEvent(QKeyEvent * e)
{
bool restartHistory = true;
QTextCursor cursor = this->textCursor();
QTextCursor inputLineBegin = this->inputBegin();
if (!cursorBeyond( cursor, inputLineBegin ))
{
/**
* The cursor is placed not on the input line (or within the prompt string)
* So we handle key input as follows:
* - don't allow changing previous lines.
* - allow full movement (no prompt restriction)
* - allow copying content (Ctrl+C)
* - "escape" to end of input line
*/
switch (e->key())
{
case Qt::Key_Return:
case Qt::Key_Enter:
case Qt::Key_Escape:
case Qt::Key_Backspace:
this->moveCursor( QTextCursor::End );
break;
default:
if (e->text().isEmpty() ||
e->matches(QKeySequence::Copy) ||
e->matches(QKeySequence::SelectAll)) {
TextEdit::keyPressEvent(e);
}
else if (!e->text().isEmpty() &&
(e->modifiers() == Qt::NoModifier ||
e->modifiers() == Qt::ShiftModifier)) {
this->moveCursor(QTextCursor::End);
TextEdit::keyPressEvent(e);
}
break;
}
}
else
{
/**
* The cursor sits somewhere on the input line (after the prompt)
* Here we handle key input a bit different:
* - restrict cursor movement to input line range (excluding the prompt characters)
* - roam the history by Up/Down keys
* - show call tips on period
*/
QTextBlock inputBlock = inputLineBegin.block(); //< get the last paragraph's text
QString inputLine = inputBlock.text();
QString inputStrg = stripPromptFrom( inputLine );
switch (e->key())
{
case Qt::Key_Escape:
{
// disable current input string - i.e. put it to history but don't execute it.
if (!inputStrg.isEmpty())
{
d->history.append( QLatin1String("# ") + inputStrg ); //< put commented string to history ...
inputLineBegin.insertText( QString::fromAscii("# ") ); //< and comment it on console
setTextCursor( inputLineBegin );
printPrompt(d->interpreter->hasPendingInput() //< print adequate prompt
? PythonConsole::Incomplete
: PythonConsole::Complete);
}
} break;
case Qt::Key_Return:
case Qt::Key_Enter:
{
d->history.append( inputStrg ); //< put statement to history
runSource( inputStrg ); //< commit input string
} break;
case Qt::Key_Period:
{
// In Qt 4.8 there is a strange behaviour because when pressing ":"
// then key is also set to 'Period' instead of 'Colon'. So we have
// to make sure we only handle the period.
if (e->text() == QLatin1String(".")) {
// analyse context and show available call tips
int contextLength = cursor.position() - inputLineBegin.position();
TextEdit::keyPressEvent(e);
d->callTipsList->showTips( inputStrg.left( contextLength ) );
}
else {
TextEdit::keyPressEvent(e);
}
} break;
case Qt::Key_Home:
{
QTextCursor::MoveMode mode = (e->modifiers() & Qt::ShiftModifier)? QTextCursor::KeepAnchor
/* else */ : QTextCursor::MoveAnchor;
cursor.setPosition( inputLineBegin.position(), mode );
setTextCursor( cursor );
ensureCursorVisible();
} break;
case Qt::Key_Up:
{
// if possible, move back in history
if (d->history.prev( inputStrg ))
{ overrideCursor( d->history.value() ); }
restartHistory = false;
} break;
case Qt::Key_Down:
{
// if possible, move forward in history
if (d->history.next())
{ overrideCursor( d->history.value() ); }
restartHistory = false;
} break;
case Qt::Key_Left:
{
if (cursor > inputLineBegin)
{ TextEdit::keyPressEvent(e); }
restartHistory = false;
} break;
case Qt::Key_Right:
{
TextEdit::keyPressEvent(e);
restartHistory = false;
} break;
case Qt::Key_Backspace:
{
if (cursorBeyond( cursor, inputLineBegin, +1 ))
{ TextEdit::keyPressEvent(e); }
} break;
default:
{
TextEdit::keyPressEvent(e);
} break;
}
// This can't be done in CallTipsList::eventFilter() because we must first perform
// the event and afterwards update the list widget
if (d->callTipsList->isVisible())
{ d->callTipsList->validateCursor(); }
// disable history restart if input line changed
restartHistory &= (inputLine != inputBlock.text());
}
// any cursor move resets the history to its latest item.
if (restartHistory)
{ d->history.restart(); }
}
/**
* Insert an output message to the console. This message comes from
* the Python interpreter and is redirected from sys.stdout.
*/
void PythonConsole::insertPythonOutput( const QString& msg )
{
d->output += msg;
}
/**
* Insert an error message to the console. This message comes from
* the Python interpreter and is redirected from sys.stderr.
*/
void PythonConsole::insertPythonError ( const QString& err )
{
d->error += err;
}
void PythonConsole::onFlush()
{
printPrompt(PythonConsole::Flush);
}
/** Prints the ps1 prompt (>>> ) for complete and ps2 prompt (... ) for
* incomplete commands to the console window.
*/
void PythonConsole::printPrompt(PythonConsole::Prompt mode)
{
// write normal messages
if (!d->output.isEmpty()) {
appendOutput(d->output, (int)PythonConsoleP::Message);
d->output = QString::null;
}
// write error messages
if (!d->error.isEmpty()) {
appendOutput(d->error, (int)PythonConsoleP::Error);
d->error = QString::null;
}
// Append the prompt string
QTextCursor cursor = textCursor();
if (mode != PythonConsole::Special)
{
cursor.beginEditBlock();
cursor.movePosition(QTextCursor::End);
QTextBlock block = cursor.block();
// Python's print command appends a trailing '\n' to the system output.
// In this case, however, we should not add a new text block. We force
// the current block to be normal text (user state = 0) to be highlighted
// correctly and append the '>>> ' or '... ' to this block.
if (block.length() > 1)
cursor.insertBlock(cursor.blockFormat(), cursor.charFormat());
else
block.setUserState(0);
switch (mode)
{
case PythonConsole::Incomplete:
cursor.insertText(QString::fromAscii("... "));
break;
case PythonConsole::Complete:
cursor.insertText(QString::fromAscii(">>> "));
break;
default:
break;
}
cursor.endEditBlock();
}
// move cursor to the end
cursor.movePosition(QTextCursor::End);
setTextCursor(cursor);
}
/**
* Appends \a output to the console and set \a state as user state to
* the text block which is needed for the highlighting.
*/
void PythonConsole::appendOutput(const QString& output, int state)
{
QTextCursor cursor = textCursor();
cursor.movePosition(QTextCursor::End);
int pos = cursor.position() + 1;
// delay rehighlighting
cursor.beginEditBlock();
appendPlainText(output);
QTextBlock block = this->document()->findBlock(pos);
while (block.isValid()) {
block.setUserState(state);
block = block.next();
}
cursor.endEditBlock(); // start highlightiong
}
/**
* Builds up the Python command and pass it to the interpreter.
*/
void PythonConsole::runSource(const QString& line)
{
/**
* Check if there's a "source drain", which want's to consume the source in another way then just executing it.
* If so, put the source to the drain and emit a signal to notify the consumer, whoever this may be.
*/
if (this->_sourceDrain)
{
*this->_sourceDrain = line;
Q_EMIT pendingSource();
return;
}
bool incomplete = false;
Base::PyGILStateLocker lock;
PyObject* default_stdout = PySys_GetObject("stdout");
PyObject* default_stderr = PySys_GetObject("stderr");
PySys_SetObject("stdout", d->_stdoutPy);
PySys_SetObject("stderr", d->_stderrPy);
d->interactive = true;
try {
d->history.markScratch(); //< mark current history position ...
// launch the command now
incomplete = d->interpreter->push(line.toUtf8());
if (!incomplete)
{ d->history.doScratch(); } //< ... and scratch history entries that might have been added by executing the line.
setFocus(); // if focus was lost
}
catch (const Base::SystemExitException&) {
ParameterGrp::handle hPrefGrp = getWindowParameter();
bool check = hPrefGrp->GetBool("CheckSystemExit",true);
int ret = QMessageBox::Yes;
if (check) {
ret = QMessageBox::question(this, tr("System exit"),
tr("The application is still running.\nDo you want to exit without saving your data?"),
QMessageBox::Yes, QMessageBox::No|QMessageBox::Escape|QMessageBox::Default);
}
if (ret == QMessageBox::Yes) {
PyErr_Clear();
throw;
}
else {
PyErr_Clear();
}
}
catch (const Py::Exception&) {
QMessageBox::critical(this, tr("Python console"), tr("Unhandled PyCXX exception."));
}
catch (const Base::Exception&) {
QMessageBox::critical(this, tr("Python console"), tr("Unhandled FreeCAD exception."));
}
catch (const std::exception&) {
QMessageBox::critical(this, tr("Python console"), tr("Unhandled std C++ exception."));
}
catch (...) {
QMessageBox::critical(this, tr("Python console"), tr("Unhandled unknown C++ exception."));
}
printPrompt(incomplete ? PythonConsole::Incomplete
: PythonConsole::Complete);
PySys_SetObject("stdout", default_stdout);
PySys_SetObject("stderr", default_stderr);
d->interactive = false;
for (QStringList::Iterator it = d->statements.begin(); it != d->statements.end(); ++it)
printStatement(*it);
d->statements.clear();
}
bool PythonConsole::isComment(const QString& source) const
{
if (source.isEmpty())
return false;
int i=0;
while (i < source.length()) {
QChar ch = source.at(i++);
if (ch.isSpace())
continue;
else if (ch == QLatin1Char('#'))
return true;
else
return false;
}
return false;
}
/**
* Prints the Python statement cmd to the console.
* @note The statement gets only printed and added to the history but not invoked.
*/
void PythonConsole::printStatement( const QString& cmd )
{
// If we are in interactive mode we have to wait until the command is finished,
// afterwards we can print the statements.
if (d->interactive) {
d->statements << cmd;
return;
}
QTextCursor cursor = textCursor();
QStringList statements = cmd.split(QLatin1String("\n"));
for (QStringList::Iterator it = statements.begin(); it != statements.end(); ++it) {
// go to the end before inserting new text
cursor.movePosition(QTextCursor::End);
cursor.insertText( *it );
d->history.append( *it );
printPrompt(PythonConsole::Complete);
}
}
/**
* Shows the Python window and sets the focus to set text cursor.
*/
void PythonConsole::showEvent (QShowEvent * e)
{
TextEdit::showEvent(e);
// set also the text cursor to the edit field
setFocus();
}
void PythonConsole::visibilityChanged (bool visible)
{
if (visible)
setFocus();
}
void PythonConsole::changeEvent(QEvent *e)
{
if (e->type() == QEvent::ParentChange) {
QDockWidget* dw = qobject_cast<QDockWidget*>(this->parentWidget());
if (dw) {
connect(dw, SIGNAL(visibilityChanged(bool)),
this, SLOT(visibilityChanged(bool)));
}
}
else if (e->type() == QEvent::StyleChange) {
QPalette pal = palette();
QColor color = pal.windowText().color();
unsigned long text = (color.red() << 24) | (color.green() << 16) | (color.blue() << 8);
// if this parameter is not already set use the style's window text color
text = getWindowParameter()->GetUnsigned("Text", text);
getWindowParameter()->SetUnsigned("Text", text);
}
TextEdit::changeEvent(e);
}
void PythonConsole::mouseReleaseEvent( QMouseEvent *e )
{
TextEdit::mouseReleaseEvent( e );
if (e->button() == Qt::LeftButton)
{
QTextCursor cursor = this->textCursor();
if (cursor.hasSelection() == false
&& cursor < this->inputBegin())
{
cursor.movePosition( QTextCursor::End );
this->setTextCursor( cursor );
}
}
}
/**
* Drops the event \a e and writes the right Python command.
*/
void PythonConsole::dropEvent (QDropEvent * e)
{
const QMimeData* mimeData = e->mimeData();
if (mimeData->hasFormat(QLatin1String("text/x-action-items"))) {
QByteArray itemData = mimeData->data(QLatin1String("text/x-action-items"));
QDataStream dataStream(&itemData, QIODevice::ReadOnly);
int ctActions; dataStream >> ctActions;
for (int i=0; i<ctActions; i++) {
QString action;
dataStream >> action;
printStatement(QString::fromAscii("Gui.runCommand(\"%1\")").arg(action));
}
e->setDropAction(Qt::CopyAction);
e->accept();
}
else // this will call insertFromMimeData
QPlainTextEdit::dropEvent(e);
}
/** Dragging of action objects is allowed. */
void PythonConsole::dragMoveEvent( QDragMoveEvent *e )
{
const QMimeData* mimeData = e->mimeData();
if (mimeData->hasFormat(QLatin1String("text/x-action-items")))
e->accept();
else // this will call canInsertFromMimeData
QPlainTextEdit::dragMoveEvent(e);
}
/** Dragging of action objects is allowed. */
void PythonConsole::dragEnterEvent (QDragEnterEvent * e)
{
const QMimeData* mimeData = e->mimeData();
if (mimeData->hasFormat(QLatin1String("text/x-action-items")))
e->accept();
else // this will call canInsertFromMimeData
QPlainTextEdit::dragEnterEvent(e);
}
bool PythonConsole::canInsertFromMimeData (const QMimeData * source) const
{
if (source->hasText())
return true;
if (source->hasUrls()) {
QList<QUrl> uri = source->urls();
for (QList<QUrl>::ConstIterator it = uri.begin(); it != uri.end(); ++it) {
QFileInfo info((*it).toLocalFile());
if (info.exists() && info.isFile()) {
QString ext = info.suffix().toLower();
if (ext == QLatin1String("py") || ext == QLatin1String("fcmacro"))
return true;
}
}
}
return false;
}
/**
* Allow to paste plain text or urls of text files.
*/
void PythonConsole::insertFromMimeData (const QMimeData * source)
{
if (!source)
return;
// First check on urls instead of text otherwise it may happen that a url
// is handled as text
if (source->hasUrls()) {
QList<QUrl> uri = source->urls();
for (QList<QUrl>::ConstIterator it = uri.begin(); it != uri.end(); ++it) {
// get the file name and check the extension
QFileInfo info((*it).toLocalFile());
QString ext = info.suffix().toLower();
if (info.exists() && info.isFile() &&
(ext == QLatin1String("py") || ext == QLatin1String("fcmacro"))) {
// load the file and read-in the source code
QFile file(info.absoluteFilePath());
if (file.open(QIODevice::ReadOnly)) {
QTextStream str(&file);
runSourceFromMimeData(str.readAll());
}
file.close();
}
}
return;
}
if (source->hasText()) {
runSourceFromMimeData(source->text());
return;
}
}
QTextCursor PythonConsole::inputBegin( void ) const
{
// construct cursor at begin of input line ...
QTextCursor inputLineBegin( this->textCursor() );
inputLineBegin.movePosition( QTextCursor::End );
inputLineBegin.movePosition( QTextCursor::StartOfLine );
// ... and move cursor right beyond the prompt.
inputLineBegin.movePosition( QTextCursor::Right, QTextCursor::MoveAnchor, promptLength( inputLineBegin.block().text() ) );
return inputLineBegin;
}
QMimeData * PythonConsole::createMimeDataFromSelection () const
{
QMimeData* mime = new QMimeData();
switch (d->type) {
case PythonConsoleP::Normal:
{
const QTextDocumentFragment fragment(textCursor());
mime->setText(fragment.toPlainText());
} break;