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
28 #include <PythonConsole_PyEditor.h> // this include must be first (see PyInterp_base.h)!
30 #include <PyInterp_Dispatcher.h>
32 #include <SUIT_Tools.h>
35 #include <qclipboard.h>
36 #include <qdragobject.h>
37 #include <qapplication.h>
42 //static int MYDEBUG = 1;
44 //static int MYDEBUG = 0;
48 enum { IdCopy, IdPaste, IdClear, IdSelectAll };
51 static QString READY_PROMPT = ">>> ";
52 static QString DOTS_PROMPT = "... ";
53 #define PROMPT_SIZE _currentPrompt.length()
55 class ExecCommand : public PyInterp_LockRequest
58 ExecCommand(PyInterp_base* theInterp, const char* theCommand, PythonConsole_PyEditor* theListener)
59 : PyInterp_LockRequest( theInterp, theListener ), myCommand(theCommand), myState( PyInterp_Event::OK )
63 virtual void execute(){
65 // if(MYDEBUG) MESSAGE("*** ExecCommand::execute() started");
66 int ret = getInterp()->run( myCommand.latin1() );
67 // if(MYDEBUG) MESSAGE("ExecCommand::execute() - myInterp = "<<getInterp()<<"; myCommand = '"<<myCommand.latin1()<<"' - "<<ret);
69 myState = PyInterp_Event::ERROR;
71 myState = PyInterp_Event::INCOMPLETE;
72 myError = getInterp()->getverr().c_str();
73 myOutput = getInterp()->getvout().c_str();
74 // if(MYDEBUG) MESSAGE("*** ExecCommand::execute() finished");
81 virtual QEvent* createEvent() const
83 return new PyInterp_Event( myState, (PyInterp_Request*)this );
99 PythonConsole_PyEditor::PythonConsole_PyEditor(PyInterp_base* theInterp, QWidget *theParent, const char* theName):
100 QTextEdit(theParent,theName),
103 QString fntSet( "" );
104 QFont aFont = SUIT_Tools::stringToFont( fntSet );
106 //setTextFormat(QTextEdit::PlainText);
107 setUndoRedoEnabled( false );
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( "\n" + _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;
311 // process <Ctrl>+<C> key-bindings
312 if ( aKey == Key_C && ctrlPressed ) {
315 _currentPrompt = READY_PROMPT;
316 setText(_currentPrompt);
320 // check for printed key
321 aKey = ( aKey < Key_Space || aKey > Key_ydiaeresis ) ? aKey : 0;
327 if ( curLine < endLine || curCol < PROMPT_SIZE )
328 moveCursor( QTextEdit::MoveEnd, false );
329 QTextEdit::keyPressEvent( e );
336 moveCursor( QTextEdit::MoveEnd, false );
337 QTextEdit::keyPressEvent( e );
341 // <Up> arrow key: process as follows:
342 // - without <Ctrl>, <Shift> modifiers: previous command in history
343 // - with <Ctrl> modifier key pressed: move cursor one row up without selection
344 // - with <Shift> modifier key pressed: move cursor one row up with selection
345 // - with <Ctrl>+<Shift> modifier keys pressed: scroll one row up
347 if ( ctrlPressed && shftPressed ) {
348 scrollBy( 0, -QFontMetrics( font() ).lineSpacing() );
350 else if ( shftPressed ) {
352 moveCursor( QTextEdit::MoveUp, true );
354 else if ( ctrlPressed ) {
355 moveCursor( QTextEdit::MoveUp, false );
358 QString histLine = _currentPrompt;
359 if ( ! _isInHistory ) {
361 _currentCommand = text( endLine ).remove( 0, PROMPT_SIZE );
362 _currentCommand.truncate( _currentCommand.length() - 1 );
364 QString previousCommand = myInterp->getPrevious();
365 if ( previousCommand.compare( BEGIN_HISTORY_PY ) != 0 )
367 removeParagraph( endLine );
368 histLine.append( previousCommand );
371 moveCursor( QTextEdit::MoveEnd, false );
376 // <Down> arrow key: process as follows:
377 // - without <Ctrl>, <Shift> modifiers: next command in history
378 // - with <Ctrl> modifier key pressed: move cursor one row down without selection
379 // - with <Shift> modifier key pressed: move cursor one row down with selection
380 // - with <Ctrl>+<Shift> modifier keys pressed: scroll one row down
382 if ( ctrlPressed && shftPressed ) {
383 scrollBy( 0, QFontMetrics( font() ).lineSpacing() );
385 else if ( shftPressed ) {
386 if ( curLine < endLine )
387 moveCursor( QTextEdit::MoveDown, true );
389 else if ( ctrlPressed ) {
390 moveCursor( QTextEdit::MoveDown, false );
393 QString histLine = _currentPrompt;
394 QString nextCommand = myInterp->getNext();
395 if ( nextCommand.compare( TOP_HISTORY_PY ) != 0 ) {
396 removeParagraph( endLine );
397 histLine.append( nextCommand );
402 _isInHistory = false;
403 removeParagraph( endLine );
404 histLine.append( _currentCommand );
408 moveCursor( QTextEdit::MoveEnd, false );
413 // <Left> arrow key: process as follows:
414 // - without <Ctrl>, <Shift> modifiers: move one symbol left (taking into account prompt)
415 // - with <Ctrl> modifier key pressed: move one word left (taking into account prompt)
416 // - with <Shift> modifier key pressed: move one symbol left with selection
417 // - with <Ctrl>+<Shift> modifier keys pressed: move one word left with selection
419 if ( !shftPressed && isCommand( text( curLine ) ) && curCol <= PROMPT_SIZE ) {
420 setCursorPosition( curLine-1, 0 );
421 moveCursor( QTextEdit::MoveLineEnd, false );
424 QTextEdit::keyPressEvent( e );
429 // <Right> arrow key: process as follows:
430 // - without <Ctrl>, <Shift> modifiers: move one symbol right (taking into account prompt)
431 // - with <Ctrl> modifier key pressed: move one word right (taking into account prompt)
432 // - with <Shift> modifier key pressed: move one symbol right with selection
433 // - with <Ctrl>+<Shift> modifier keys pressed: move one word right with selection
435 if ( !shftPressed ) {
436 if ( curCol < paragraphLength( curLine ) ) {
437 if ( isCommand( text( curLine ) ) && curCol < PROMPT_SIZE ) {
438 setCursorPosition( curLine, PROMPT_SIZE );
443 if ( curLine < endLine && isCommand( text( curLine+1 ) ) ) {
444 setCursorPosition( curLine+1, PROMPT_SIZE );
449 QTextEdit::keyPressEvent( e );
453 // <PageUp> key: process as follows:
454 // - without <Ctrl>, <Shift> modifiers: first command in history
455 // - with <Ctrl> modifier key pressed: move cursor one page up without selection
456 // - with <Shift> modifier key pressed: move cursor one page up with selection
457 // - with <Ctrl>+<Shift> modifier keys pressed: scroll one page up
459 if ( ctrlPressed && shftPressed ) {
460 scrollBy( 0, -visibleHeight() );
462 else if ( shftPressed ) {
464 moveCursor( QTextEdit::MovePgUp, true );
466 else if ( ctrlPressed ) {
467 moveCursor( QTextEdit::MovePgUp, false );
470 QString histLine = _currentPrompt;
471 if ( ! _isInHistory ) {
473 _currentCommand = text( endLine ).remove( 0, PROMPT_SIZE );
474 _currentCommand.truncate( _currentCommand.length() - 1 );
476 QString firstCommand = myInterp->getPrevious();
478 while ( ( pcmd = QString( myInterp->getPrevious() ) ).compare( BEGIN_HISTORY_PY ) != 0 )
480 if ( firstCommand.compare( BEGIN_HISTORY_PY ) != 0 ) {
481 removeParagraph( endLine );
482 histLine.append( firstCommand );
483 insertParagraph( histLine, -1 );
485 moveCursor( QTextEdit::MoveEnd, false );
490 // <PageDown> key: process as follows:
491 // - without <Ctrl>, <Shift> modifiers: last command in history
492 // - with <Ctrl> modifier key pressed: move cursor one page down without selection
493 // - with <Shift> modifier key pressed: move cursor one page down with selection
494 // - with <Ctrl>+<Shift> modifier keys pressed: scroll one page down
496 if ( ctrlPressed && shftPressed ) {
497 scrollBy( 0, visibleHeight() );
499 else if ( shftPressed ) {
500 if ( curLine < endLine )
501 moveCursor( QTextEdit::MovePgDown, true );
503 else if ( ctrlPressed ) {
504 moveCursor( QTextEdit::MovePgDown, false );
507 if ( _isInHistory ) {
508 QString histLine = _currentPrompt;
509 while ( QString( myInterp->getNext() ).compare( TOP_HISTORY_PY ) != 0 );
510 _isInHistory = false;
511 removeParagraph( endLine );
512 histLine.append( _currentCommand );
513 insertParagraph( histLine, -1 );
515 moveCursor( QTextEdit::MoveEnd, false );
520 // <Home> key: process as follows:
521 // - without <Ctrl>, <Shift> modifiers: move cursor to the beginning of the current line without selection
522 // - with <Ctrl> modifier key pressed: move cursor to the very first symbol without selection
523 // - with <Shift> modifier key pressed: move cursor to the beginning of the current line with selection
524 // - with <Ctrl>+<Shift> modifier keys pressed: move cursor to the very first symbol with selection
527 moveCursor( QTextEdit::MoveHome, shftPressed );
530 if ( isCommand( text( curLine ) ) ) {
531 int ps1, ps2, cs1, cs2;
532 bool hasSelection = hasSelectedText();
534 getSelection( &ps1, &cs1, &ps2, &cs2 );
536 horizontalScrollBar()->setValue( horizontalScrollBar()->minValue() );
537 if ( curCol > PROMPT_SIZE && shftPressed )
538 setSelection( curLine, PROMPT_SIZE, curLine, ( hasSelection && ps1 == ps2 && ps1 == curLine && cs2 > PROMPT_SIZE ) ? cs2 : curCol );
539 setCursorPosition( curLine, PROMPT_SIZE );
542 moveCursor( QTextEdit::MoveLineStart, shftPressed );
548 // <End> key: process as follows:
549 // - without <Ctrl>, <Shift> modifiers: move cursor to the end of the current line without selection
550 // - with <Ctrl> modifier key pressed: move cursor to the very last symbol without selection
551 // - with <Shift> modifier key pressed: move cursor to the end of the current line with selection
552 // - with <Ctrl>+<Shift> modifier keys pressed: move cursor to the very last symbol with selection
555 moveCursor( QTextEdit::MoveEnd, shftPressed );
558 moveCursor( QTextEdit::MoveLineEnd, shftPressed );
563 // <Backspace> key: process as follows
564 // - without any modifiers : delete symbol before the cursor / selection (taking into account prompt)
565 // - with <Ctrl> modifier key pressed: delete previous word
566 // works only for last (command) line
568 if ( curLine == endLine && ( curCol > PROMPT_SIZE || curCol >= PROMPT_SIZE && hasSelectedText() ) ) {
569 if ( ctrlPressed && !hasSelectedText() ) {
570 QString txt = text( curLine );
572 while ( ind > 0 && txt[ ind ] == ' ' ) ind--;
573 ind = txt.findRev( ' ', ind ) + 1;
574 if ( ind > PROMPT_SIZE-1 ) {
575 setSelection( curLine, ind, curLine, curCol );
576 removeSelectedText();
579 QTextEdit::keyPressEvent( e );
583 QTextEdit::keyPressEvent( e );
589 // <Delete> key: process as follows
590 // - without any modifiers : delete symbol after the cursor / selection (taking into account prompt)
591 // - with <Ctrl> modifier key pressed: delete next word
592 // works only for last (command) line
594 if ( curLine == endLine && curCol > PROMPT_SIZE-1 ) {
595 if ( ctrlPressed && !hasSelectedText() ) {
596 QString txt = text( curLine );
598 while ( ind < txt.length()-1 && txt[ ind ] == ' ' ) ind++;
599 ind = txt.find( ' ', ind );
600 while ( ind < txt.length()-1 && txt[ ind ] == ' ' ) ind++;
601 if ( ind > PROMPT_SIZE-1 ) {
602 setSelection( curLine, curCol, curLine, ind );
603 removeSelectedText();
606 QTextEdit::keyPressEvent( e );
610 QTextEdit::keyPressEvent( e );
616 // <Insert> key: process as follows
617 // - with <Ctrl> modifier key pressed: copy()
618 // - with <Shift> modifier key pressed: paste() to the command line
623 else if ( shftPressed ) {
624 if ( curLine != endLine || curCol < PROMPT_SIZE )
625 moveCursor( QTextEdit::MoveEnd, false );
629 QTextEdit::keyPressEvent( e );
636 Handles notifications coming from Python dispatcher
638 void PythonConsole_PyEditor::customEvent(QCustomEvent* e)
640 switch( e->type() ) {
641 case PyInterp_Event::OK:
642 case PyInterp_Event::ERROR:
644 PyInterp_Event* pe = dynamic_cast<PyInterp_Event*>( e );
646 ExecCommand* ec = dynamic_cast<ExecCommand*>( pe->GetRequest() );
648 // The next line has appeared dangerous in case if
649 // Python command execution has produced very large output.
650 // A more clever approach is needed...
651 setText(ec->myOutput);
652 setText(ec->myError);
656 _currentPrompt = READY_PROMPT;
657 setText(_currentPrompt);
658 viewport()->unsetCursor();
661 case PyInterp_Event::INCOMPLETE:
664 _currentPrompt = DOTS_PROMPT;
665 setText(_currentPrompt);
666 viewport()->unsetCursor();
670 QTextEdit::customEvent( e );
673 setReadOnly( false );
674 _isInHistory = false;
678 Handles Python interpreter change
680 void PythonConsole_PyEditor::onPyInterpChanged( PyInterp_base* interp )
682 if ( myInterp != interp
683 // Force read-only state and wait cursor when myInterp is NULL
687 myBanner = myInterp->getbanner().c_str();
690 setReadOnly( false );
691 _isInHistory = false;
692 setText(_currentPrompt);
693 viewport()->unsetCursor();
698 viewport()->setCursor( waitCursor );
703 QPopupMenu* PythonConsole_PyEditor::createPopupMenu( const QPoint& pos )
705 QPopupMenu* popup = QTextEdit::createPopupMenu( pos );
708 for ( int i = 0; popup && i < popup->count(); i++ )
710 if ( !popup->isItemEnabled( popup->idAt( i ) ) )
711 ids.append( popup->idAt( i ) );
714 for ( QValueList<int>::const_iterator it = ids.begin(); it != ids.end(); ++it )
715 popup->removeItem( *it );
717 SUIT_Tools::simplifySeparators( popup );
719 if ( !popup->count() )