kmail

kmedit.cpp

00001 // -*- mode: C++; c-file-style: "gnu" -*-
00002 // kmcomposewin.cpp
00003 // Author: Markus Wuebben <markus.wuebben@kde.org>
00004 // This code is published under the GPL.
00005 
00006 #include <config.h>
00007 
00008 #include "kmedit.h"
00009 #include "kmlineeditspell.h"
00010 
00011 #define REALLY_WANT_KMCOMPOSEWIN_H
00012 #include "kmcomposewin.h"
00013 #undef REALLY_WANT_KMCOMPOSEWIN_H
00014 #include "kmmsgdict.h"
00015 #include "kmfolder.h"
00016 #include "kmcommands.h"
00017 
00018 #include <maillistdrag.h>
00019 using KPIM::MailListDrag;
00020 
00021 #include <libkdepim/kfileio.h>
00022 #include <libemailfunctions/email.h>
00023 
00024 #include <kcursor.h>
00025 #include <kprocess.h>
00026 
00027 #include <kpopupmenu.h>
00028 #include <kdebug.h>
00029 #include <kmessagebox.h>
00030 #include <kurldrag.h>
00031 
00032 #include <ktempfile.h>
00033 #include <klocale.h>
00034 #include <kapplication.h>
00035 #include <kdirwatch.h>
00036 #include <kiconloader.h>
00037 
00038 #include "globalsettings.h"
00039 #include "replyphrases.h"
00040 
00041 #include <kspell.h>
00042 #include <kspelldlg.h>
00043 #include <spellingfilter.h>
00044 #include <ksyntaxhighlighter.h>
00045 
00046 #include <qregexp.h>
00047 #include <qbuffer.h>
00048 #include <qevent.h>
00049 
00050 #include <sys/stat.h>
00051 #include <sys/types.h>
00052 #include <stdlib.h>
00053 #include <unistd.h>
00054 #include <errno.h>
00055 #include <fcntl.h>
00056 #include <assert.h>
00057 
00058 
00059 void KMEdit::contentsDragEnterEvent(QDragEnterEvent *e)
00060 {
00061     if (e->provides(MailListDrag::format()))
00062         e->accept(true);
00063     else if (e->provides("image/png"))
00064         e->accept();
00065     else
00066         return KEdit::contentsDragEnterEvent(e);
00067 }
00068 
00069 void KMEdit::contentsDragMoveEvent(QDragMoveEvent *e)
00070 {
00071     if (e->provides(MailListDrag::format()))
00072         e->accept();
00073     else if (e->provides("image/png"))
00074         e->accept();
00075     else
00076         return KEdit::contentsDragMoveEvent(e);
00077 }
00078 
00079 void KMEdit::keyPressEvent( QKeyEvent* e )
00080 {
00081     if( e->key() == Key_Return ) {
00082         int line, col;
00083         getCursorPosition( &line, &col );
00084         QString lineText = text( line );
00085         // returns line with additional trailing space (bug in Qt?), cut it off
00086         lineText.truncate( lineText.length() - 1 );
00087         // special treatment of quoted lines only if the cursor is neither at
00088         // the begin nor at the end of the line
00089         if( ( col > 0 ) && ( col < int( lineText.length() ) ) ) {
00090             bool isQuotedLine = false;
00091             uint bot = 0; // bot = begin of text after quote indicators
00092             while( bot < lineText.length() ) {
00093                 if( ( lineText[bot] == '>' ) || ( lineText[bot] == '|' ) ) {
00094                     isQuotedLine = true;
00095                     ++bot;
00096                 }
00097                 else if( lineText[bot].isSpace() ) {
00098                     ++bot;
00099                 }
00100                 else {
00101                     break;
00102                 }
00103             }
00104 
00105             KEdit::keyPressEvent( e );
00106 
00107             // duplicate quote indicators of the previous line before the new
00108             // line if the line actually contained text (apart from the quote
00109             // indicators) and the cursor is behind the quote indicators
00110             if( isQuotedLine
00111                 && ( bot != lineText.length() )
00112                 && ( col >= int( bot ) ) ) {
00113 
00114         // The cursor position might have changed unpredictably if there was selected
00115         // text which got replaced by a new line, so we query it again:
00116         getCursorPosition( &line, &col );
00117                 QString newLine = text( line );
00118                 // remove leading white space from the new line and instead
00119                 // add the quote indicators of the previous line
00120                 unsigned int leadingWhiteSpaceCount = 0;
00121                 while( ( leadingWhiteSpaceCount < newLine.length() )
00122                        && newLine[leadingWhiteSpaceCount].isSpace() ) {
00123                     ++leadingWhiteSpaceCount;
00124                 }
00125                 newLine = newLine.replace( 0, leadingWhiteSpaceCount,
00126                                            lineText.left( bot ) );
00127                 removeParagraph( line );
00128                 insertParagraph( newLine, line );
00129                 // place the cursor at the begin of the new line since
00130                 // we assume that the user split the quoted line in order
00131                 // to add a comment to the first part of the quoted line
00132                 setCursorPosition( line, 0 );
00133             }
00134         }
00135         else
00136             KEdit::keyPressEvent( e );
00137     }
00138     else
00139         KEdit::keyPressEvent( e );
00140 }
00141 
00142 void KMEdit::contentsDropEvent(QDropEvent *e)
00143 {
00144     if (e->provides(MailListDrag::format())) {
00145         // Decode the list of serial numbers stored as the drag data
00146         QByteArray serNums;
00147         MailListDrag::decode( e, serNums );
00148         QBuffer serNumBuffer(serNums);
00149         serNumBuffer.open(IO_ReadOnly);
00150         QDataStream serNumStream(&serNumBuffer);
00151         Q_UINT32 serNum;
00152         KMFolder *folder = 0;
00153         int idx;
00154         QPtrList<KMMsgBase> messageList;
00155         while (!serNumStream.atEnd()) {
00156             KMMsgBase *msgBase = 0;
00157             serNumStream >> serNum;
00158             KMMsgDict::instance()->getLocation(serNum, &folder, &idx);
00159             if (folder)
00160                 msgBase = folder->getMsgBase(idx);
00161             if (msgBase)
00162                 messageList.append( msgBase );
00163         }
00164         serNumBuffer.close();
00165         uint identity = folder ? folder->identity() : 0;
00166         KMCommand *command =
00167             new KMForwardAttachedCommand(mComposer, messageList,
00168                                          identity, mComposer);
00169         command->start();
00170     }
00171     else if( e->provides("image/png") ) {
00172         emit attachPNGImageData(e->encodedData("image/png"));
00173     }
00174     else if( KURLDrag::canDecode( e ) ) {
00175         KURL::List urlList;
00176         if( KURLDrag::decode( e, urlList ) ) {
00177             KPopupMenu p;
00178             p.insertItem( i18n("Add as Text"), 0 );
00179             p.insertItem( i18n("Add as Attachment"), 1 );
00180             int id = p.exec( mapToGlobal( e->pos() ) );
00181             switch ( id) {
00182               case 0:
00183                 for ( KURL::List::Iterator it = urlList.begin();
00184                      it != urlList.end(); ++it ) {
00185                   insert( (*it).url() );
00186                 }
00187                 break;
00188               case 1:
00189                 for ( KURL::List::Iterator it = urlList.begin();
00190                      it != urlList.end(); ++it ) {
00191                   mComposer->addAttach( *it );
00192                 }
00193                 break;
00194             }
00195         }
00196         else if ( QTextDrag::canDecode( e ) ) {
00197           QString s;
00198           if ( QTextDrag::decode( e, s ) )
00199             insert( s );
00200         }
00201         else
00202           kdDebug(5006) << "KMEdit::contentsDropEvent, unable to add dropped object" << endl;
00203     } 
00204     else if( e->provides("text/x-textsnippet") ) {
00205     emit insertSnippet();
00206     } 
00207     else {
00208         KEdit::contentsDropEvent(e);
00209     }
00210 }
00211 
00212 KMEdit::KMEdit(QWidget *parent, KMComposeWin* composer,
00213                KSpellConfig* autoSpellConfig,
00214                const char *name)
00215   : KEdit( parent, name ),
00216     mComposer( composer ),
00217     mKSpellForDialog( 0 ),
00218     mSpellConfig( autoSpellConfig ),
00219     mSpellingFilter( 0 ),
00220     mExtEditorTempFile( 0 ),
00221     mExtEditorTempFileWatcher( 0 ),
00222     mExtEditorProcess( 0 ),
00223     mUseExtEditor( false ),
00224     mWasModifiedBeforeSpellCheck( false ),
00225     mHighlighter( 0 ),
00226     mSpellLineEdit( false ),
00227     mPasteMode( QClipboard::Clipboard )
00228 {
00229   connect( this, SIGNAL(selectionChanged()), this, SLOT(slotSelectionChanged()) );
00230   installEventFilter(this);
00231   KCursor::setAutoHideCursor( this, true, true );
00232   setOverwriteEnabled( true );
00233   mSpeller = new KMSpell( this, SLOT( spellerReady( KSpell * ) ) );
00234   connect( mSpeller, SIGNAL( death() ),
00235            this, SLOT( spellerDied() ) );
00236 }
00237 
00238 
00239 void KMEdit::initializeAutoSpellChecking()
00240 {
00241   if ( mHighlighter )
00242     return; // already initialized
00243   QColor defaultColor1( 0x00, 0x80, 0x00 ); // defaults from kmreaderwin.cpp
00244   QColor defaultColor2( 0x00, 0x70, 0x00 );
00245   QColor defaultColor3( 0x00, 0x60, 0x00 );
00246   QColor defaultForeground( kapp->palette().active().text() );
00247 
00248   QColor c = Qt::red;
00249   KConfigGroup readerConfig( KMKernel::config(), "Reader" );
00250   QColor col1;
00251   if ( !readerConfig.readBoolEntry(  "defaultColors", true ) )
00252       col1 = readerConfig.readColorEntry( "ForegroundColor", &defaultForeground );
00253   else
00254       col1 = defaultForeground;
00255   QColor col2 = readerConfig.readColorEntry( "QuotedText3", &defaultColor3 );
00256   QColor col3 = readerConfig.readColorEntry( "QuotedText2", &defaultColor2 );
00257   QColor col4 = readerConfig.readColorEntry( "QuotedText1", &defaultColor1 );
00258   QColor misspelled = readerConfig.readColorEntry( "MisspelledColor", &c );
00259   mHighlighter = new KMSyntaxHighter( this, /*active*/ true,
00260                                        /*autoEnabled*/ false,
00261                                        /*spellColor*/ misspelled,
00262                                        /*colorQuoting*/ true,
00263                                        col1, col2, col3, col4,
00264                                        mSpellConfig );
00265 
00266   connect( mHighlighter, SIGNAL(newSuggestions(const QString&, const QStringList&, unsigned int)),
00267            this, SLOT(addSuggestion(const QString&, const QStringList&, unsigned int)) );
00268 }
00269 
00270 
00271 QPopupMenu *KMEdit::createPopupMenu( const QPoint& pos )
00272 {
00273   enum { IdUndo, IdRedo, IdSep1, IdCut, IdCopy, IdPaste, IdClear, IdSep2, IdSelectAll };
00274 
00275   QPopupMenu *menu = KEdit::createPopupMenu( pos );
00276   if ( !QApplication::clipboard()->image().isNull() ) {
00277     int id = menu->idAt(0);
00278     menu->setItemEnabled( id - IdPaste, true);
00279   }
00280 
00281   return menu;
00282 }
00283 
00284 void KMEdit::deleteAutoSpellChecking()
00285 { // because the highlighter doesn't support RichText, delete its instance.
00286   delete mHighlighter;
00287   mHighlighter =0;
00288 }
00289 
00290 void KMEdit::addSuggestion(const QString& text, const QStringList& lst, unsigned int )
00291 {
00292   mReplacements[text] = lst;
00293 }
00294 
00295 void KMEdit::setSpellCheckingActive(bool spellCheckingActive)
00296 {
00297   if ( mHighlighter ) {
00298     mHighlighter->setActive(spellCheckingActive);
00299   }
00300 }
00301 
00302 
00303 KMEdit::~KMEdit()
00304 {
00305   removeEventFilter(this);
00306 
00307   if ( mSpeller ) {
00308     // The speller needs some time to clean up, so trigger cleanup and let it delete itself
00309     mSpeller->setAutoDelete( true );
00310     mSpeller->cleanUp();
00311     mSpeller = 0;
00312   }
00313 
00314   delete mKSpellForDialog;
00315   delete mHighlighter;
00316   mHighlighter = 0;
00317 }
00318 
00319 
00320 
00321 QString KMEdit::brokenText()
00322 {
00323   QString temp, line;
00324 
00325   int num_lines = numLines();
00326   for (int i = 0; i < num_lines; ++i)
00327   {
00328     int lastLine = 0;
00329     line = textLine(i);
00330     for (int j = 0; j < (int)line.length(); ++j)
00331     {
00332       if (lineOfChar(i, j) > lastLine)
00333       {
00334         lastLine = lineOfChar(i, j);
00335         temp += '\n';
00336       }
00337       temp += line[j];
00338     }
00339     if (i + 1 < num_lines) temp += '\n';
00340   }
00341 
00342   return temp;
00343 }
00344 
00345 
00346 unsigned int KMEdit::lineBreakColumn() const
00347 {
00348   unsigned int lineBreakColumn = 0;
00349   unsigned int numlines = numLines();
00350   while ( numlines-- ) {
00351     lineBreakColumn = QMAX( lineBreakColumn, textLine( numlines ).length() );
00352   }
00353   return lineBreakColumn;
00354 }
00355 
00356 KMSpell::KMSpell( QObject *receiver, const char *slot )
00357   : KSpell( 0, QString(), receiver, slot )
00358 {
00359 }
00360 
00361 KMSyntaxHighter::KMSyntaxHighter( QTextEdit *textEdit,
00362                                   bool spellCheckingActive,
00363                                   bool autoEnable,
00364                                   const QColor& spellColor,
00365                                   bool colorQuoting,
00366                                   const QColor& QuoteColor0,
00367                                   const QColor& QuoteColor1,
00368                                   const QColor& QuoteColor2,
00369                                   const QColor& QuoteColor3,
00370                                   KSpellConfig *spellConfig )
00371   : KDictSpellingHighlighter( textEdit, spellCheckingActive, autoEnable, spellColor, colorQuoting,
00372                               QuoteColor0, QuoteColor1, QuoteColor2, QuoteColor3, spellConfig )
00373 {
00374 }
00375 
00376 bool KMSyntaxHighter::isMisspelled( const QString &word )
00377 {
00378   if ( mIgnoredWords.contains( word ) ) {
00379     return false;
00380   }
00381   else {
00382     return KDictSpellingHighlighter::isMisspelled( word );
00383   }
00384 }
00385 
00386 void KMSyntaxHighter::ignoreWord( const QString &word )
00387 {
00388   mIgnoredWords << word;
00389 }
00390 
00391 QStringList KMSyntaxHighter::ignoredWords() const
00392 {
00393   return mIgnoredWords;
00394 }
00395 
00396 void KMEdit::spellerDied()
00397 {
00398   mSpeller = 0;
00399 }
00400 
00401 void KMEdit::spellerReady( KSpell *spell )
00402 {
00403   Q_ASSERT( mSpeller == spell );
00404 }
00405 
00406 bool KMEdit::eventFilter(QObject*o, QEvent* e)
00407 {
00408   if (o == this)
00409     KCursor::autoHideEventFilter(o, e);
00410 
00411   if (e->type() == QEvent::KeyPress)
00412   {
00413     QKeyEvent *k = (QKeyEvent*)e;
00414 
00415     if (mUseExtEditor) {
00416       if (k->key() == Key_Up)
00417       {
00418         emit focusUp();
00419         return true;
00420       }
00421 
00422       // ignore modifier keys (cf. bug 48841)
00423       if ( (k->key() == Key_Shift) || (k->key() == Key_Control) ||
00424            (k->key() == Key_Meta) || (k->key() == Key_Alt) )
00425         return true;
00426       if (mExtEditorTempFile) return true;
00427       QString sysLine = mExtEditor;
00428       mExtEditorTempFile = new KTempFile();
00429 
00430       mExtEditorTempFile->setAutoDelete(true);
00431 
00432       (*mExtEditorTempFile->textStream()) << text();
00433 
00434       mExtEditorTempFile->close();
00435       // replace %f in the system line
00436       sysLine.replace( "%f", mExtEditorTempFile->name() );
00437       mExtEditorProcess = new KProcess();
00438       mExtEditorProcess->setUseShell( true );
00439       sysLine += " ";
00440       while (!sysLine.isEmpty())
00441       {
00442         *mExtEditorProcess << sysLine.left(sysLine.find(" ")).local8Bit();
00443         sysLine.remove(0, sysLine.find(" ") + 1);
00444       }
00445       connect(mExtEditorProcess, SIGNAL(processExited(KProcess*)),
00446               SLOT(slotExternalEditorDone(KProcess*)));
00447       if (!mExtEditorProcess->start())
00448       {
00449         KMessageBox::error( topLevelWidget(),
00450                             i18n("Unable to start external editor.") );
00451         killExternalEditor();
00452       } else {
00453         mExtEditorTempFileWatcher = new KDirWatch( this, "mExtEditorTempFileWatcher" );
00454         connect( mExtEditorTempFileWatcher, SIGNAL(dirty(const QString&)),
00455                  SLOT(slotExternalEditorTempFileChanged(const QString&)) );
00456         mExtEditorTempFileWatcher->addFile( mExtEditorTempFile->name() );
00457       }
00458       return true;
00459     } else {
00460     // ---sven's Arrow key navigation start ---
00461     // Key Up in first line takes you to Subject line.
00462     if (k->key() == Key_Up && k->state() != ShiftButton && currentLine() == 0
00463       && lineOfChar(0, currentColumn()) == 0)
00464     {
00465       deselect();
00466       emit focusUp();
00467       return true;
00468     }
00469     // ---sven's Arrow key navigation end ---
00470 
00471     if (k->key() == Key_Backtab && k->state() == ShiftButton)
00472     {
00473       deselect();
00474       emit focusUp();
00475       return true;
00476     }
00477 
00478     }
00479   } else if ( e->type() == QEvent::ContextMenu ) {
00480     QContextMenuEvent *event = (QContextMenuEvent*) e;
00481 
00482     int para = 1, charPos, firstSpace, lastSpace;
00483 
00484     //Get the character at the position of the click
00485     charPos = charAt( viewportToContents(event->pos()), &para );
00486     QString paraText = text( para );
00487 
00488     if( !paraText.at(charPos).isSpace() )
00489     {
00490       //Get word right clicked on
00491       const QRegExp wordBoundary( "[\\s\\W]" );
00492       firstSpace = paraText.findRev( wordBoundary, charPos ) + 1;
00493       lastSpace = paraText.find( wordBoundary, charPos );
00494       if( lastSpace == -1 )
00495         lastSpace = paraText.length();
00496       QString word = paraText.mid( firstSpace, lastSpace - firstSpace );
00497       //Continue if this word was misspelled
00498       if( !word.isEmpty() && mReplacements.contains( word ) )
00499       {
00500         KPopupMenu p;
00501 
00502         //Add the suggestions to the popup menu
00503         QStringList reps = mReplacements[word];
00504         if( reps.count() > 0 )
00505         {
00506           int listPos = 0;
00507           for ( QStringList::Iterator it = reps.begin(); it != reps.end(); ++it ) {
00508             p.insertItem( *it, listPos );
00509             listPos++;
00510           }
00511         }
00512         else
00513         {
00514           p.setItemEnabled( p.insertItem( i18n( "No Suggestions" ), -2 ), false );
00515         }
00516 
00517         int addToDictionaryId = -42;
00518         int ignoreId = -43;
00519         if ( mSpeller && mSpeller->status() == KSpell::Running ) {
00520           p.insertSeparator();
00521           addToDictionaryId = p.insertItem( i18n( "Add to Dictionary" ) );
00522           ignoreId = p.insertItem( i18n( "Ignore All" ) );
00523         }
00524 
00525         //Execute the popup inline
00526         const int id = p.exec( mapToGlobal( event->pos() ) );
00527 
00528         if ( id != -1 ) {
00529           // No longer misspelled: Either added to dictionary, ignored or replaced
00530           mReplacements.remove( word );
00531         }
00532 
00533         if ( id == ignoreId ) {
00534           mHighlighter->ignoreWord( word );
00535           mHighlighter->rehighlight();
00536         }
00537         if ( id == addToDictionaryId ) {
00538           mSpeller->addPersonal( word );
00539           mSpeller->writePersonalDictionary();
00540           if ( mHighlighter ) {
00541             // Wait a bit until reloading the highlighter, the mSpeller first needs to finish saving
00542             // the personal word list.
00543             QTimer::singleShot( 200, mHighlighter, SLOT( slotLocalSpellConfigChanged() ) );
00544           }
00545         }
00546         else if( id > -1 )
00547         {
00548           //Save the cursor position
00549           int parIdx = 1, txtIdx = 1;
00550           getCursorPosition(&parIdx, &txtIdx);
00551           setSelection(para, firstSpace, para, lastSpace);
00552           insert(mReplacements[word][id]);
00553           // Restore the cursor position; if the cursor was behind the
00554           // misspelled word then adjust the cursor position
00555           if ( para == parIdx && txtIdx >= lastSpace )
00556             txtIdx += mReplacements[word][id].length() - word.length();
00557           setCursorPosition(parIdx, txtIdx);
00558         }
00559         //Cancel original event
00560         return true;
00561       }
00562     }
00563   } else if ( e->type() == QEvent::FocusIn || e->type() == QEvent::FocusOut ) {
00564     QFocusEvent *fe = static_cast<QFocusEvent*>(e);
00565     if(! (fe->reason() == QFocusEvent::ActiveWindow || fe->reason() == QFocusEvent::Popup) )
00566       emit focusChanged( fe->gotFocus() );
00567   }
00568 
00569   return KEdit::eventFilter(o, e);
00570 }
00571 
00572 
00573 int KMEdit::autoSpellChecking( bool on )
00574 {
00575   if ( textFormat() == Qt::RichText ) {
00576      // syntax highlighter doesn't support extended text properties
00577      if ( on )
00578        KMessageBox::sorry(this, i18n("Automatic spellchecking is not possible on text with markup."));
00579      return -1;
00580   }
00581   if ( mHighlighter ) {
00582     // don't autoEnable spell checking if the user turned spell checking off
00583     mHighlighter->setAutomatic( on );
00584     mHighlighter->setActive( on );
00585   }
00586   return 1;
00587 }
00588 
00589 
00590 void KMEdit::slotExternalEditorTempFileChanged( const QString & fileName ) {
00591   if ( !mExtEditorTempFile )
00592     return;
00593   if ( fileName != mExtEditorTempFile->name() )
00594     return;
00595   // read data back in from file
00596   setAutoUpdate(false);
00597   clear();
00598 
00599   insertLine(QString::fromLocal8Bit(KPIM::kFileToString( fileName, true, false )), -1);
00600   setAutoUpdate(true);
00601   repaint();
00602 }
00603 
00604 void KMEdit::slotExternalEditorDone( KProcess * proc ) {
00605   assert(proc == mExtEditorProcess);
00606   // make sure, we update even when KDirWatcher is too slow:
00607   slotExternalEditorTempFileChanged( mExtEditorTempFile->name() );
00608   killExternalEditor();
00609 }
00610 
00611 void KMEdit::killExternalEditor() {
00612   delete mExtEditorTempFileWatcher; mExtEditorTempFileWatcher = 0;
00613   delete mExtEditorTempFile; mExtEditorTempFile = 0;
00614   delete mExtEditorProcess; mExtEditorProcess = 0;
00615 }
00616 
00617 
00618 bool KMEdit::checkExternalEditorFinished() {
00619   if ( !mExtEditorProcess )
00620     return true;
00621   switch ( KMessageBox::warningYesNoCancel( topLevelWidget(),
00622            i18n("The external editor is still running.\n"
00623                 "Abort the external editor or leave it open?"),
00624            i18n("External Editor"),
00625            i18n("Abort Editor"), i18n("Leave Editor Open") ) ) {
00626   case KMessageBox::Yes:
00627     killExternalEditor();
00628     return true;
00629   case KMessageBox::No:
00630     return true;
00631   default:
00632     return false;
00633   }
00634 }
00635 
00636 void KMEdit::spellcheck()
00637 {
00638   if ( mKSpellForDialog )
00639     return;
00640   mWasModifiedBeforeSpellCheck = isModified();
00641   mSpellLineEdit = !mSpellLineEdit;
00642 //  maybe for later, for now plaintext is given to KSpell
00643 //  if (textFormat() == Qt::RichText ) {
00644 //    kdDebug(5006) << "KMEdit::spellcheck, spellchecking for RichText" << endl;
00645 //    mKSpellForDialog = new KSpell(this, i18n("Spellcheck - KMail"), this,
00646 //                    SLOT(slotSpellcheck2(KSpell*)),0,true,false,KSpell::HTML);
00647 //  }
00648 //  else {
00649     mKSpellForDialog = new KSpell(this, i18n("Spellcheck - KMail"), this,
00650                       SLOT(slotSpellcheck2(KSpell*)));
00651 //  }
00652 
00653   QStringList l = KSpellingHighlighter::personalWords();
00654   for ( QStringList::Iterator it = l.begin(); it != l.end(); ++it ) {
00655       mKSpellForDialog->addPersonal( *it );
00656   }
00657   connect (mKSpellForDialog, SIGNAL( death()),
00658           this, SLOT (slotSpellDone()));
00659   connect (mKSpellForDialog, SIGNAL (misspelling (const QString &, const QStringList &, unsigned int)),
00660           this, SLOT (slotMisspelling (const QString &, const QStringList &, unsigned int)));
00661   connect (mKSpellForDialog, SIGNAL (corrected (const QString &, const QString &, unsigned int)),
00662           this, SLOT (slotCorrected (const QString &, const QString &, unsigned int)));
00663   connect (mKSpellForDialog, SIGNAL (done(const QString &)),
00664           this, SLOT (slotSpellResult (const QString&)));
00665 }
00666 
00667 void KMEdit::cut()
00668 {
00669   KEdit::cut();
00670   if ( textFormat() != Qt::RichText && mHighlighter )
00671     mHighlighter->restartBackgroundSpellCheck();
00672 }
00673 
00674 void KMEdit::clear()
00675 {
00676   KEdit::clear();
00677   if ( textFormat() != Qt::RichText && mHighlighter )
00678     mHighlighter->restartBackgroundSpellCheck();
00679 }
00680 
00681 void KMEdit::del()
00682 {
00683   KEdit::del();
00684   if ( textFormat() != Qt::RichText && mHighlighter )
00685     mHighlighter->restartBackgroundSpellCheck();
00686 }
00687 
00688 void KMEdit::paste()
00689 {
00690   mComposer->paste( mPasteMode );
00691 }
00692 
00693 // KMEdit indirectly inherits from QTextEdit, which has virtual paste() method,
00694 // but it controls whether it pastes clipboard or selection by an internal
00695 // flag that is not accessible in any way, so paste() being virtual is actually
00696 // useless, because reimplementations can't known where to paste from anyway.
00697 // Roll our own internal flag.
00698 void KMEdit::contentsMouseReleaseEvent( QMouseEvent * e )
00699 {
00700   if( e->button() != Qt::MidButton )
00701     return KEdit::contentsMouseReleaseEvent( e );
00702   mPasteMode = QClipboard::Selection;
00703   KEdit::contentsMouseReleaseEvent( e );
00704   mPasteMode = QClipboard::Clipboard;
00705 }
00706 
00707 void KMEdit::contentsMouseDoubleClickEvent( QMouseEvent *e )
00708 {
00709   bool handled = false;
00710   if ( e->button() == Qt::LeftButton ) {
00711 
00712     // Get the cursor position for the place where the user clicked to
00713     int paragraphPos;
00714     int charPos = charAt ( e->pos(), &paragraphPos );
00715     QString paraText = text( paragraphPos );
00716 
00717     // Now select the word under the cursor
00718     if ( charPos >= 0 && static_cast<unsigned int>( charPos ) <= paraText.length() ) {
00719 
00720       // Start the selection where the user clicked
00721       int start = charPos;
00722       unsigned int end = charPos;
00723 
00724       // Extend the selection to the left, until we reach a non-letter and non-digit char
00725       for (;;) {
00726         if ( ( start - 1 ) < 0 )
00727           break;
00728         QChar charToTheLeft = paraText.at( start - 1 );
00729         if ( charToTheLeft.isLetter() || charToTheLeft.isDigit() )
00730           start--;
00731         else
00732           break;
00733       }
00734 
00735       // Extend the selection to the left, until we reach a non-letter and non-digit char
00736       for (;;) {
00737         if ( ( end + 1 ) >= paraText.length() )
00738           break;
00739         QChar charToTheRight = paraText.at( end + 1 );
00740         if ( charToTheRight.isLetter() || charToTheRight.isDigit() )
00741           end++;
00742         else
00743           break;
00744       }
00745 
00746       setSelection( paragraphPos, start, paragraphPos, end + 1 );
00747       handled = true;
00748     }
00749   }
00750 
00751   if ( !handled )
00752     return KEdit::contentsMouseDoubleClickEvent( e );
00753 }
00754 
00755 void KMEdit::slotMisspelling(const QString &text, const QStringList &lst, unsigned int pos)
00756 {
00757     kdDebug(5006)<<"void KMEdit::slotMisspelling(const QString &text, const QStringList &lst, unsigned int pos) : "<<text <<endl;
00758     if( mSpellLineEdit )
00759         mComposer->sujectLineWidget()->spellCheckerMisspelling( text, lst, pos);
00760     else
00761         misspelling(text, lst, pos);
00762 }
00763 
00764 void KMEdit::slotCorrected (const QString &oldWord, const QString &newWord, unsigned int pos)
00765 {
00766     kdDebug(5006)<<"slotCorrected (const QString &oldWord, const QString &newWord, unsigned int pos) : "<<oldWord<<endl;
00767     if( mSpellLineEdit )
00768         mComposer->sujectLineWidget()->spellCheckerCorrected( oldWord, newWord, pos);
00769     else {
00770         unsigned int l = 0;
00771         unsigned int cnt = 0;
00772         bool _bold,_underline,_italic;
00773         QColor _color;
00774         QFont _font;
00775         posToRowCol (pos, l, cnt);
00776         setCursorPosition(l, cnt+1); // the new word will get the same markup now as the first character of the word
00777         _bold = bold();
00778         _underline = underline();
00779         _italic = italic();
00780         _color = color();
00781         _font = currentFont();
00782         corrected(oldWord, newWord, pos);
00783         setSelection (l, cnt, l, cnt+newWord.length());
00784         setBold(_bold);
00785         setItalic(_italic);
00786         setUnderline(_underline);
00787         setColor(_color);
00788         setCurrentFont(_font);
00789     }
00790 
00791 }
00792 
00793 void KMEdit::slotSpellcheck2(KSpell*)
00794 {
00795   // Make sure words ignored by the highlighter are ignored by KSpell as well
00796   if ( mHighlighter ) {
00797     for ( int i = 0; i < mHighlighter->ignoredWords().size(); i++ )
00798       mKSpellForDialog->ignore( mHighlighter->ignoredWords()[i] );
00799   }
00800 
00801     if( !mSpellLineEdit)
00802     {
00803         spellcheck_start();
00804 
00805         QString quotePrefix;
00806         if(mComposer && mComposer->msg())
00807         {
00808             int languageNr = GlobalSettings::self()->replyCurrentLanguage();
00809             ReplyPhrases replyPhrases( QString::number(languageNr) );
00810             replyPhrases.readConfig();
00811 
00812             quotePrefix = mComposer->msg()->formatString(
00813                  replyPhrases.indentPrefix() );
00814         }
00815 
00816         kdDebug(5006) << "spelling: new SpellingFilter with prefix=\"" << quotePrefix << "\"" << endl;
00817         QTextEdit plaintext;
00818         plaintext.setText(text());
00819         plaintext.setTextFormat(Qt::PlainText);
00820         mSpellingFilter = new SpellingFilter(plaintext.text(), quotePrefix, SpellingFilter::FilterUrls,
00821                                              SpellingFilter::FilterEmailAddresses);
00822 
00823         mKSpellForDialog->check(mSpellingFilter->filteredText());
00824     }
00825     else if( mComposer )
00826         mKSpellForDialog->check( mComposer->sujectLineWidget()->text());
00827 }
00828 
00829 void KMEdit::slotSpellResult(const QString &s)
00830 {
00831     if( !mSpellLineEdit)
00832         spellcheck_stop();
00833 
00834   int dlgResult = mKSpellForDialog->dlgResult();
00835   if ( dlgResult == KS_CANCEL )
00836   {
00837       if( mSpellLineEdit)
00838       {
00839           //stop spell check
00840           mSpellLineEdit = false;
00841           QString tmpText( s );
00842           tmpText =  tmpText.remove('\n');
00843 
00844           if( tmpText != mComposer->sujectLineWidget()->text() )
00845               mComposer->sujectLineWidget()->setText( tmpText );
00846       }
00847       else
00848       {
00849           setModified(true);
00850       }
00851   }
00852   mKSpellForDialog->cleanUp();
00853   KDictSpellingHighlighter::dictionaryChanged();
00854 
00855   emit spellcheck_done( dlgResult );
00856 }
00857 
00858 void KMEdit::slotSpellDone()
00859 {
00860   kdDebug(5006)<<" void KMEdit::slotSpellDone()\n";
00861   KSpell::spellStatus status = mKSpellForDialog->status();
00862   delete mKSpellForDialog;
00863   mKSpellForDialog = 0;
00864 
00865   kdDebug(5006) << "spelling: delete SpellingFilter" << endl;
00866   delete mSpellingFilter;
00867   mSpellingFilter = 0;
00868   mComposer->sujectLineWidget()->deselect();
00869   if (status == KSpell::Error)
00870   {
00871      KMessageBox::sorry( topLevelWidget(),
00872                          i18n("ISpell/Aspell could not be started. Please "
00873                               "make sure you have ISpell or Aspell properly "
00874                               "configured and in your PATH.") );
00875      emit spellcheck_done( KS_CANCEL );
00876   }
00877   else if (status == KSpell::Crashed)
00878   {
00879      spellcheck_stop();
00880      KMessageBox::sorry( topLevelWidget(),
00881                          i18n("ISpell/Aspell seems to have crashed.") );
00882      emit spellcheck_done( KS_CANCEL );
00883   }
00884   else
00885   {
00886       if( mSpellLineEdit )
00887           spellcheck();
00888       else if( !mComposer->subjectTextWasSpellChecked() && status == KSpell::FinishedNoMisspellingsEncountered )
00889           KMessageBox::information( topLevelWidget(),
00890                                     i18n("No misspellings encountered.") );
00891   }
00892 }
00893 
00894 void KMEdit::setCursorPositionFromStart( unsigned int pos ) {
00895   unsigned int l = 0;
00896   unsigned int c = 0;
00897   posToRowCol( pos, l, c );
00898   // kdDebug() << "Num lines: " << numLines() << endl;
00899   // kdDebug() << "Position " << pos << " converted to " << l << ":" << c << endl;
00900   setCursorPosition( l, c );
00901   ensureCursorVisible();
00902 }
00903 
00904 #include "kmedit.moc"
KDE Home | KDE Accessibility Home | Description of Access Keys