1 // SALOME SALOMEGUI : implementation of desktop and GUI kernel
3 // Copyright (C) 2003 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License.
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 GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.opencascade.org/SALOME/ or email : webmaster.salome@opencascade.org
24 // File : PythonConsole_PyEditor.cxx
25 // Author : Nicolas REJNERI
29 #include <PythonConsole_PyEditor.h> // this include must be first (see PyInterp_base.h)!
30 #include <PyInterp_Dispatcher.h>
31 #include <SUIT_Tools.h>
33 #include <qapplication.h>
35 #include <qclipboard.h>
36 #include <qdragobject.h>
38 //#include "utilities.h"
43 //static int MYDEBUG = 1;
45 //static int MYDEBUG = 0;
49 enum { IdCopy, IdPaste, IdClear, IdSelectAll };
52 static QString READY_PROMPT = ">>> ";
53 static QString DOTS_PROMPT = "... ";
54 #define PROMPT_SIZE _currentPrompt.length()
56 class ExecCommand : public PyInterp_LockRequest
59 ExecCommand(PyInterp_base* theInterp, const char* theCommand, PythonConsole_PyEditor* theListener)
60 : PyInterp_LockRequest( theInterp, theListener ), myCommand(theCommand), myState( PyInterp_Event::OK )
64 virtual void execute(){
66 // if(MYDEBUG) MESSAGE("*** ExecCommand::execute() started");
67 int ret = getInterp()->run( myCommand.latin1() );
68 // if(MYDEBUG) MESSAGE("ExecCommand::execute() - myInterp = "<<getInterp()<<"; myCommand = '"<<myCommand.latin1()<<"' - "<<ret);
70 myState = PyInterp_Event::ERROR;
72 myState = PyInterp_Event::INCOMPLETE;
73 myError = getInterp()->getverr().c_str();
74 myOutput = getInterp()->getvout().c_str();
75 // if(MYDEBUG) MESSAGE("*** ExecCommand::execute() finished");
82 virtual QEvent* createEvent() const
84 return new PyInterp_Event( myState, (PyInterp_Request*)this );
100 PythonConsole_PyEditor::PythonConsole_PyEditor(PyInterp_base* theInterp, QWidget *theParent, const char* theName):
101 QTextEdit(theParent,theName),
104 QString fntSet( "" );
105 QFont aFont = SUIT_Tools::stringToFont( fntSet );
107 setTextFormat(QTextEdit::PlainText);
109 _currentPrompt = READY_PROMPT;
112 connect(this,SIGNAL(returnPressed()),this,SLOT(handleReturn()) );
114 // san - This is necessary for troubleless initialization
115 onPyInterpChanged( theInterp );
121 PythonConsole_PyEditor::~PythonConsole_PyEditor()
123 // if(MYDEBUG) MESSAGE("PythonConsole_PyEditor::~PythonConsole_PyEditor()");
127 Called to insert a string s
129 void PythonConsole_PyEditor::setText(QString s)
131 int para=paragraphs()-1;
132 int col=paragraphLength(para);
133 insertAt(s,para,col);
134 int n = paragraphs()-1;
135 setCursorPosition( n, paragraphLength(n));
139 Convenient method for executing a Python command,
140 as if the user typed it manually
142 void PythonConsole_PyEditor::exec( const QString& command )
144 // Some interactive command is being executed in this editor -> do nothing
147 int para=paragraphs()-1;
148 removeParagraph( para );
149 _currentPrompt = READY_PROMPT;
151 _isInHistory = false;
152 setText(_currentPrompt);
153 setText( command + "\n" );
158 Called when an handleReturn
160 void PythonConsole_PyEditor::handleReturn()
162 int para=paragraphs()-2;
163 _buf.append(text(para).remove(0,PROMPT_SIZE));
164 _buf.truncate( _buf.length() - 1 );
166 viewport()->setCursor( waitCursor );
168 // Post a request to execute Python command
169 // Editor will be informed via a custom event that execution has been completed
170 PyInterp_Dispatcher::Get()->Exec( new ExecCommand( myInterp, _buf.latin1(), this ) );
174 Processes drop event: paste dragged text
176 void PythonConsole_PyEditor::contentsDropEvent( QDropEvent* event )
178 event->acceptAction();
180 if ( QTextDrag::decode( event, text ) ) {
182 int endLine = paragraphs() -1;
183 col = charAt( event->pos(), &par );
185 if ( col >= 0 && par >= 0 ) {
186 if ( par != endLine || col < PROMPT_SIZE ) {
188 col = paragraphLength( endLine );
190 setCursorPosition( par, col );
191 insertAt( text, par, col );
198 Processes middle button release event - paste clipboard's contents
200 void PythonConsole_PyEditor::contentsMouseReleaseEvent( QMouseEvent* event )
202 if ( event->button() == LeftButton ) {
203 QTextEdit::contentsMouseReleaseEvent(event);
206 if ( event->button() == MidButton ) {
207 if (QApplication::clipboard()->supportsSelection()) {
209 int endLine = paragraphs() -1;
210 col = charAt( event->pos(), &par );
211 if ( col >= 0 && par >= 0 ) {
212 if ( par != endLine || col < PROMPT_SIZE )
213 setCursorPosition( endLine, paragraphLength( endLine ) );
215 setCursorPosition( par, col );
216 QApplication::clipboard()->setSelectionMode(TRUE);
218 QApplication::clipboard()->setSelectionMode(FALSE);
223 QTextEdit::contentsMouseReleaseEvent(event);
228 Processes own popup menu
230 void PythonConsole_PyEditor::mousePressEvent (QMouseEvent* event)
232 if ( event->button() == RightButton ) {
233 QPopupMenu *popup = new QPopupMenu( this );
234 QMap<int, int> idMap;
236 int para1, col1, para2, col2;
237 getSelection(¶1, &col1, ¶2, &col2);
238 bool allSelected = hasSelectedText() &&
239 para1 == 0 && para2 == paragraphs()-1 && col1 == 0 && para2 == paragraphLength(para2);
241 id = popup->insertItem( tr( "EDIT_COPY_CMD" ) );
242 idMap.insert(IdCopy, id);
243 id = popup->insertItem( tr( "EDIT_PASTE_CMD" ) );
244 idMap.insert(IdPaste, id);
245 id = popup->insertItem( tr( "EDIT_CLEAR_CMD" ) );
246 idMap.insert(IdClear, id);
247 popup->insertSeparator();
248 id = popup->insertItem( tr( "EDIT_SELECTALL_CMD" ) );
249 idMap.insert(IdSelectAll, id);
250 popup->setItemEnabled( idMap[ IdCopy ], hasSelectedText() );
251 popup->setItemEnabled( idMap[ IdPaste ],
252 !isReadOnly() && (bool)QApplication::clipboard()->text().length() );
253 popup->setItemEnabled( idMap[ IdSelectAll ],
254 (bool)text().length() && !allSelected );
256 int r = popup->exec( event->globalPos() );
259 if ( r == idMap[ IdCopy ] ) {
262 else if ( r == idMap[ IdPaste ] ) {
265 else if ( r == idMap[ IdClear ] ) {
268 _currentPrompt = READY_PROMPT;
269 setText(_currentPrompt);
271 else if ( r == idMap[ IdSelectAll ] ) {
276 QTextEdit::mousePressEvent(event);
281 Checks, is the string a command line or not.
284 bool PythonConsole_PyEditor::isCommand( const QString& str) const
286 // prompt may be '>>> ' or for '... '
287 return ( str.find( READY_PROMPT ) == 0 || str.find( DOTS_PROMPT ) == 0 );
292 Called when a keyPress event
294 void PythonConsole_PyEditor::keyPressEvent( QKeyEvent* e )
296 // get cursor position
298 getCursorPosition(&curLine, &curCol);
300 // get last edited line
301 int endLine = paragraphs() -1;
303 // get pressed key code
306 // check if <Ctrl> is pressed
307 bool ctrlPressed = e->state() & ControlButton;
308 // check if <Shift> is pressed
309 bool shftPressed = e->state() & ShiftButton;
310 // check if <Alt> is pressed
311 bool altPressed = e->state() & AltButton;
313 // process <Ctrl>+<C> key-bindings
314 if ( aKey == Key_C && ctrlPressed ) {
317 _currentPrompt = READY_PROMPT;
318 setText(_currentPrompt);
322 // check for printed key
323 aKey = ( aKey < Key_Space || aKey > Key_ydiaeresis ) ? aKey : 0;
329 if ( curLine < endLine || curCol < PROMPT_SIZE )
330 moveCursor( QTextEdit::MoveEnd, false );
331 QTextEdit::keyPressEvent( e );
338 moveCursor( QTextEdit::MoveEnd, false );
339 QTextEdit::keyPressEvent( e );
343 // <Up> arrow key: process as follows:
344 // - without <Ctrl>, <Shift> modifiers: previous command in history
345 // - with <Ctrl> modifier key pressed: move cursor one row up without selection
346 // - with <Shift> modifier key pressed: move cursor one row up with selection
347 // - with <Ctrl>+<Shift> modifier keys pressed: scroll one row up
349 if ( ctrlPressed && shftPressed ) {
350 scrollBy( 0, -QFontMetrics( font() ).lineSpacing() );
352 else if ( shftPressed ) {
354 moveCursor( QTextEdit::MoveUp, true );
356 else if ( ctrlPressed ) {
357 moveCursor( QTextEdit::MoveUp, false );
360 QString histLine = _currentPrompt;
361 if ( ! _isInHistory ) {
363 _currentCommand = text( endLine ).remove( 0, PROMPT_SIZE );
364 _currentCommand.truncate( _currentCommand.length() - 1 );
366 QString previousCommand = myInterp->getPrevious();
367 if ( previousCommand.compare( BEGIN_HISTORY_PY ) != 0 )
369 removeParagraph( endLine );
370 histLine.append( previousCommand );
373 moveCursor( QTextEdit::MoveEnd, false );
378 // <Down> arrow key: process as follows:
379 // - without <Ctrl>, <Shift> modifiers: next command in history
380 // - with <Ctrl> modifier key pressed: move cursor one row down without selection
381 // - with <Shift> modifier key pressed: move cursor one row down with selection
382 // - with <Ctrl>+<Shift> modifier keys pressed: scroll one row down
384 if ( ctrlPressed && shftPressed ) {
385 scrollBy( 0, QFontMetrics( font() ).lineSpacing() );
387 else if ( shftPressed ) {
388 if ( curLine < endLine )
389 moveCursor( QTextEdit::MoveDown, true );
391 else if ( ctrlPressed ) {
392 moveCursor( QTextEdit::MoveDown, false );
395 QString histLine = _currentPrompt;
396 QString nextCommand = myInterp->getNext();
397 if ( nextCommand.compare( TOP_HISTORY_PY ) != 0 ) {
398 removeParagraph( endLine );
399 histLine.append( nextCommand );
404 _isInHistory = false;
405 removeParagraph( endLine );
406 histLine.append( _currentCommand );
410 moveCursor( QTextEdit::MoveEnd, false );
415 // <Left> arrow key: process as follows:
416 // - without <Ctrl>, <Shift> modifiers: move one symbol left (taking into account prompt)
417 // - with <Ctrl> modifier key pressed: move one word left (taking into account prompt)
418 // - with <Shift> modifier key pressed: move one symbol left with selection
419 // - with <Ctrl>+<Shift> modifier keys pressed: move one word left with selection
421 if ( !shftPressed && isCommand( text( curLine ) ) && curCol <= PROMPT_SIZE ) {
422 setCursorPosition( curLine-1, 0 );
423 moveCursor( QTextEdit::MoveLineEnd, false );
426 QTextEdit::keyPressEvent( e );
431 // <Right> arrow key: process as follows:
432 // - without <Ctrl>, <Shift> modifiers: move one symbol right (taking into account prompt)
433 // - with <Ctrl> modifier key pressed: move one word right (taking into account prompt)
434 // - with <Shift> modifier key pressed: move one symbol right with selection
435 // - with <Ctrl>+<Shift> modifier keys pressed: move one word right with selection
437 if ( !shftPressed ) {
438 if ( curCol < paragraphLength( curLine ) ) {
439 if ( isCommand( text( curLine ) ) && curCol < PROMPT_SIZE ) {
440 setCursorPosition( curLine, PROMPT_SIZE );
445 if ( curLine < endLine && isCommand( text( curLine+1 ) ) ) {
446 setCursorPosition( curLine+1, PROMPT_SIZE );
451 QTextEdit::keyPressEvent( e );
455 // <PageUp> key: process as follows:
456 // - without <Ctrl>, <Shift> modifiers: first command in history
457 // - with <Ctrl> modifier key pressed: move cursor one page up without selection
458 // - with <Shift> modifier key pressed: move cursor one page up with selection
459 // - with <Ctrl>+<Shift> modifier keys pressed: scroll one page up
461 if ( ctrlPressed && shftPressed ) {
462 scrollBy( 0, -visibleHeight() );
464 else if ( shftPressed ) {
466 moveCursor( QTextEdit::MovePgUp, true );
468 else if ( ctrlPressed ) {
469 moveCursor( QTextEdit::MovePgUp, false );
472 QString histLine = _currentPrompt;
473 if ( ! _isInHistory ) {
475 _currentCommand = text( endLine ).remove( 0, PROMPT_SIZE );
476 _currentCommand.truncate( _currentCommand.length() - 1 );
478 QString firstCommand = myInterp->getPrevious();
480 while ( ( pcmd = QString( myInterp->getPrevious() ) ).compare( BEGIN_HISTORY_PY ) != 0 )
482 if ( firstCommand.compare( BEGIN_HISTORY_PY ) != 0 ) {
483 removeParagraph( endLine );
484 histLine.append( firstCommand );
485 insertParagraph( histLine, -1 );
487 moveCursor( QTextEdit::MoveEnd, false );
492 // <PageDown> key: process as follows:
493 // - without <Ctrl>, <Shift> modifiers: last command in history
494 // - with <Ctrl> modifier key pressed: move cursor one page down without selection
495 // - with <Shift> modifier key pressed: move cursor one page down with selection
496 // - with <Ctrl>+<Shift> modifier keys pressed: scroll one page down
498 if ( ctrlPressed && shftPressed ) {
499 scrollBy( 0, visibleHeight() );
501 else if ( shftPressed ) {
502 if ( curLine < endLine )
503 moveCursor( QTextEdit::MovePgDown, true );
505 else if ( ctrlPressed ) {
506 moveCursor( QTextEdit::MovePgDown, false );
509 if ( _isInHistory ) {
510 QString histLine = _currentPrompt;
511 while ( QString( myInterp->getNext() ).compare( TOP_HISTORY_PY ) != 0 );
512 _isInHistory = false;
513 removeParagraph( endLine );
514 histLine.append( _currentCommand );
515 insertParagraph( histLine, -1 );
517 moveCursor( QTextEdit::MoveEnd, false );
522 // <Home> key: process as follows:
523 // - without <Ctrl>, <Shift> modifiers: move cursor to the beginning of the current line without selection
524 // - with <Ctrl> modifier key pressed: move cursor to the very first symbol without selection
525 // - with <Shift> modifier key pressed: move cursor to the beginning of the current line with selection
526 // - with <Ctrl>+<Shift> modifier keys pressed: move cursor to the very first symbol with selection
529 moveCursor( QTextEdit::MoveHome, shftPressed );
532 if ( isCommand( text( curLine ) ) ) {
533 int ps1, ps2, cs1, cs2;
534 bool hasSelection = hasSelectedText();
536 getSelection( &ps1, &cs1, &ps2, &cs2 );
538 horizontalScrollBar()->setValue( horizontalScrollBar()->minValue() );
539 if ( curCol > PROMPT_SIZE && shftPressed )
540 setSelection( curLine, PROMPT_SIZE, curLine, ( hasSelection && ps1 == ps2 && ps1 == curLine && cs2 > PROMPT_SIZE ) ? cs2 : curCol );
541 setCursorPosition( curLine, PROMPT_SIZE );
544 moveCursor( QTextEdit::MoveLineStart, shftPressed );
550 // <End> key: process as follows:
551 // - without <Ctrl>, <Shift> modifiers: move cursor to the end of the current line without selection
552 // - with <Ctrl> modifier key pressed: move cursor to the very last symbol without selection
553 // - with <Shift> modifier key pressed: move cursor to the end of the current line with selection
554 // - with <Ctrl>+<Shift> modifier keys pressed: move cursor to the very last symbol with selection
557 moveCursor( QTextEdit::MoveEnd, shftPressed );
560 moveCursor( QTextEdit::MoveLineEnd, shftPressed );
565 // <Backspace> key: process as follows
566 // - without any modifiers : delete symbol before the cursor / selection (taking into account prompt)
567 // - with <Ctrl> modifier key pressed: delete previous word
568 // works only for last (command) line
570 if ( curLine == endLine && ( curCol > PROMPT_SIZE || curCol >= PROMPT_SIZE && hasSelectedText() ) ) {
571 if ( ctrlPressed && !hasSelectedText() ) {
572 QString txt = text( curLine );
574 while ( ind > 0 && txt[ ind ] == ' ' ) ind--;
575 ind = txt.findRev( ' ', ind ) + 1;
576 if ( ind > PROMPT_SIZE-1 ) {
577 setSelection( curLine, ind, curLine, curCol );
578 removeSelectedText();
581 QTextEdit::keyPressEvent( e );
585 QTextEdit::keyPressEvent( e );
591 // <Delete> key: process as follows
592 // - without any modifiers : delete symbol after the cursor / selection (taking into account prompt)
593 // - with <Ctrl> modifier key pressed: delete next word
594 // works only for last (command) line
596 if ( curLine == endLine && curCol > PROMPT_SIZE-1 ) {
597 if ( ctrlPressed && !hasSelectedText() ) {
598 QString txt = text( curLine );
600 while ( ind < txt.length()-1 && txt[ ind ] == ' ' ) ind++;
601 ind = txt.find( ' ', ind );
602 while ( ind < txt.length()-1 && txt[ ind ] == ' ' ) ind++;
603 if ( ind > PROMPT_SIZE-1 ) {
604 setSelection( curLine, curCol, curLine, ind );
605 removeSelectedText();
608 QTextEdit::keyPressEvent( e );
612 QTextEdit::keyPressEvent( e );
618 // <Insert> key: process as follows
619 // - with <Ctrl> modifier key pressed: copy()
620 // - with <Shift> modifier key pressed: paste() to the command line
625 else if ( shftPressed ) {
626 if ( curLine != endLine || curCol < PROMPT_SIZE )
627 moveCursor( QTextEdit::MoveEnd, false );
631 QTextEdit::keyPressEvent( e );
638 Handles notifications coming from Python dispatcher
640 void PythonConsole_PyEditor::customEvent(QCustomEvent* e)
642 switch( e->type() ) {
643 case PyInterp_Event::OK:
644 case PyInterp_Event::ERROR:
646 PyInterp_Event* pe = dynamic_cast<PyInterp_Event*>( e );
648 ExecCommand* ec = dynamic_cast<ExecCommand*>( pe->GetRequest() );
650 // The next line has appeared dangerous in case if
651 // Python command execution has produced very large output.
652 // A more clever approach is needed...
653 setText(ec->myOutput);
654 setText(ec->myError);
658 _currentPrompt = READY_PROMPT;
659 setText(_currentPrompt);
660 viewport()->unsetCursor();
663 case PyInterp_Event::INCOMPLETE:
666 _currentPrompt = DOTS_PROMPT;
667 setText(_currentPrompt);
668 viewport()->unsetCursor();
672 QTextEdit::customEvent( e );
675 setReadOnly( false );
676 _isInHistory = false;
680 Handles Python interpreter change
682 void PythonConsole_PyEditor::onPyInterpChanged( PyInterp_base* interp )
684 if ( myInterp != interp
685 // Force read-only state and wait cursor when myInterp is NULL
689 myBanner = myInterp->getbanner().c_str();
692 setReadOnly( false );
693 _isInHistory = false;
694 setText(_currentPrompt);
695 viewport()->unsetCursor();
700 viewport()->setCursor( waitCursor );