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 == ignoreId ) {
00529           mHighlighter->ignoreWord( word );
00530           mHighlighter->rehighlight();
00531         }
00532         if ( id == addToDictionaryId ) {
00533           mSpeller->addPersonal( word );
00534           mSpeller->writePersonalDictionary();
00535           if ( mHighlighter ) {
00536             // Wait a bit until reloading the highlighter, the mSpeller first needs to finish saving
00537             // the personal word list.
00538             QTimer::singleShot( 200, mHighlighter, SLOT( slotLocalSpellConfigChanged() ) );
00539           }
00540         }
00541         else if( id > -1 )
00542         {
00543           //Save the cursor position
00544           int parIdx = 1, txtIdx = 1;
00545           getCursorPosition(&parIdx, &txtIdx);
00546           setSelection(para, firstSpace, para, lastSpace);
00547           insert(mReplacements[word][id]);
00548           // Restore the cursor position; if the cursor was behind the
00549           // misspelled word then adjust the cursor position
00550           if ( para == parIdx && txtIdx >= lastSpace )
00551             txtIdx += mReplacements[word][id].length() - word.length();
00552           setCursorPosition(parIdx, txtIdx);
00553         }
00554 
00555         if ( id == addToDictionaryId || id == ignoreId ) {
00556           // No longer misspelled: Either added to dictionary or ignored
00557           mReplacements.remove( word );
00558         }
00559 
00560         //Cancel original event
00561         return true;
00562       }
00563     }
00564   } else if ( e->type() == QEvent::FocusIn || e->type() == QEvent::FocusOut ) {
00565     QFocusEvent *fe = static_cast<QFocusEvent*>(e);
00566     if(! (fe->reason() == QFocusEvent::ActiveWindow || fe->reason() == QFocusEvent::Popup) )
00567       emit focusChanged( fe->gotFocus() );
00568   }
00569 
00570   return KEdit::eventFilter(o, e);
00571 }
00572 
00573 
00574 int KMEdit::autoSpellChecking( bool on )
00575 {
00576   if ( textFormat() == Qt::RichText ) {
00577      // syntax highlighter doesn't support extended text properties
00578      if ( on )
00579        KMessageBox::sorry(this, i18n("Automatic spellchecking is not possible on text with markup."));
00580      return -1;
00581   }
00582   if ( mHighlighter ) {
00583     // don't autoEnable spell checking if the user turned spell checking off
00584     mHighlighter->setAutomatic( on );
00585     mHighlighter->setActive( on );
00586   }
00587   return 1;
00588 }
00589 
00590 
00591 void KMEdit::slotExternalEditorTempFileChanged( const QString & fileName ) {
00592   if ( !mExtEditorTempFile )
00593     return;
00594   if ( fileName != mExtEditorTempFile->name() )
00595     return;
00596   // read data back in from file
00597   setAutoUpdate(false);
00598   clear();
00599 
00600   insertLine(QString::fromLocal8Bit(KPIM::kFileToString( fileName, true, false )), -1);
00601   setAutoUpdate(true);
00602   repaint();
00603 }
00604 
00605 void KMEdit::slotExternalEditorDone( KProcess * proc ) {
00606   assert(proc == mExtEditorProcess);
00607   // make sure, we update even when KDirWatcher is too slow:
00608   slotExternalEditorTempFileChanged( mExtEditorTempFile->name() );
00609   killExternalEditor();
00610 }
00611 
00612 void KMEdit::killExternalEditor() {
00613   delete mExtEditorTempFileWatcher; mExtEditorTempFileWatcher = 0;
00614   delete mExtEditorTempFile; mExtEditorTempFile = 0;
00615   delete mExtEditorProcess; mExtEditorProcess = 0;
00616 }
00617 
00618 
00619 bool KMEdit::checkExternalEditorFinished() {
00620   if ( !mExtEditorProcess )
00621     return true;
00622   switch ( KMessageBox::warningYesNoCancel( topLevelWidget(),
00623            i18n("The external editor is still running.\n"
00624                 "Abort the external editor or leave it open?"),
00625            i18n("External Editor"),
00626            i18n("Abort Editor"), i18n("Leave Editor Open") ) ) {
00627   case KMessageBox::Yes:
00628     killExternalEditor();
00629     return true;
00630   case KMessageBox::No:
00631     return true;
00632   default:
00633     return false;
00634   }
00635 }
00636 
00637 void KMEdit::spellcheck()
00638 {
00639   if ( mKSpellForDialog )
00640     return;
00641   mWasModifiedBeforeSpellCheck = isModified();
00642   mSpellLineEdit = !mSpellLineEdit;
00643 //  maybe for later, for now plaintext is given to KSpell
00644 //  if (textFormat() == Qt::RichText ) {
00645 //    kdDebug(5006) << "KMEdit::spellcheck, spellchecking for RichText" << endl;
00646 //    mKSpellForDialog = new KSpell(this, i18n("Spellcheck - KMail"), this,
00647 //                    SLOT(slotSpellcheck2(KSpell*)),0,true,false,KSpell::HTML);
00648 //  }
00649 //  else {
00650     mKSpellForDialog = new KSpell(this, i18n("Spellcheck - KMail"), this,
00651                       SLOT(slotSpellcheck2(KSpell*)));
00652 //  }
00653 
00654   QStringList l = KSpellingHighlighter::personalWords();
00655   for ( QStringList::Iterator it = l.begin(); it != l.end(); ++it ) {
00656       mKSpellForDialog->addPersonal( *it );
00657   }
00658   connect (mKSpellForDialog, SIGNAL( death()),
00659           this, SLOT (slotSpellDone()));
00660   connect (mKSpellForDialog, SIGNAL (misspelling (const QString &, const QStringList &, unsigned int)),
00661           this, SLOT (slotMisspelling (const QString &, const QStringList &, unsigned int)));
00662   connect (mKSpellForDialog, SIGNAL (corrected (const QString &, const QString &, unsigned int)),
00663           this, SLOT (slotCorrected (const QString &, const QString &, unsigned int)));
00664   connect (mKSpellForDialog, SIGNAL (done(const QString &)),
00665           this, SLOT (slotSpellResult (const QString&)));
00666 }
00667 
00668 void KMEdit::cut()
00669 {
00670   KEdit::cut();
00671   if ( textFormat() != Qt::RichText && mHighlighter )
00672     mHighlighter->restartBackgroundSpellCheck();
00673 }
00674 
00675 void KMEdit::clear()
00676 {
00677   KEdit::clear();
00678   if ( textFormat() != Qt::RichText && mHighlighter )
00679     mHighlighter->restartBackgroundSpellCheck();
00680 }
00681 
00682 void KMEdit::del()
00683 {
00684   KEdit::del();
00685   if ( textFormat() != Qt::RichText && mHighlighter )
00686     mHighlighter->restartBackgroundSpellCheck();
00687 }
00688 
00689 void KMEdit::paste()
00690 {
00691   mComposer->paste( mPasteMode );
00692 }
00693 
00694 // KMEdit indirectly inherits from QTextEdit, which has virtual paste() method,
00695 // but it controls whether it pastes clipboard or selection by an internal
00696 // flag that is not accessible in any way, so paste() being virtual is actually
00697 // useless, because reimplementations can't known where to paste from anyway.
00698 // Roll our own internal flag.
00699 void KMEdit::contentsMouseReleaseEvent( QMouseEvent * e )
00700 {
00701   if( e->button() != Qt::MidButton )
00702     return KEdit::contentsMouseReleaseEvent( e );
00703   mPasteMode = QClipboard::Selection;
00704   KEdit::contentsMouseReleaseEvent( e );
00705   mPasteMode = QClipboard::Clipboard;
00706 }
00707 
00708 void KMEdit::contentsMouseDoubleClickEvent( QMouseEvent *e )
00709 {
00710   bool handled = false;
00711   if ( e->button() == Qt::LeftButton ) {
00712 
00713     // Get the cursor position for the place where the user clicked to
00714     int paragraphPos;
00715     int charPos = charAt ( e->pos(), &paragraphPos );
00716     QString paraText = text( paragraphPos );
00717 
00718     // Now select the word under the cursor
00719     if ( charPos >= 0 && static_cast<unsigned int>( charPos ) <= paraText.length() ) {
00720 
00721       // Start the selection where the user clicked
00722       int start = charPos;
00723       unsigned int end = charPos;
00724 
00725       // Extend the selection to the left, until we reach a non-letter and non-digit char
00726       for (;;) {
00727         if ( ( start - 1 ) < 0 )
00728           break;
00729         QChar charToTheLeft = paraText.at( start - 1 );
00730         if ( charToTheLeft.isLetter() || charToTheLeft.isDigit() )
00731           start--;
00732         else
00733           break;
00734       }
00735 
00736       // Extend the selection to the left, until we reach a non-letter and non-digit char
00737       for (;;) {
00738         if ( ( end + 1 ) >= paraText.length() )
00739           break;
00740         QChar charToTheRight = paraText.at( end + 1 );
00741         if ( charToTheRight.isLetter() || charToTheRight.isDigit() )
00742           end++;
00743         else
00744           break;
00745       }
00746 
00747       setSelection( paragraphPos, start, paragraphPos, end + 1 );
00748       handled = true;
00749     }
00750   }
00751 
00752   if ( !handled )
00753     return KEdit::contentsMouseDoubleClickEvent( e );
00754 }
00755 
00756 void KMEdit::slotMisspelling(const QString &text, const QStringList &lst, unsigned int pos)
00757 {
00758     kdDebug(5006)<<"void KMEdit::slotMisspelling(const QString &text, const QStringList &lst, unsigned int pos) : "<<text <<endl;
00759     if( mSpellLineEdit )
00760         mComposer->sujectLineWidget()->spellCheckerMisspelling( text, lst, pos);
00761     else
00762         misspelling(text, lst, pos);
00763 }
00764 
00765 void KMEdit::slotCorrected (const QString &oldWord, const QString &newWord, unsigned int pos)
00766 {
00767     kdDebug(5006)<<"slotCorrected (const QString &oldWord, const QString &newWord, unsigned int pos) : "<<oldWord<<endl;
00768     if( mSpellLineEdit )
00769         mComposer->sujectLineWidget()->spellCheckerCorrected( oldWord, newWord, pos);
00770     else {
00771         unsigned int l = 0;
00772         unsigned int cnt = 0;
00773         bool _bold,_underline,_italic;
00774         QColor _color;
00775         QFont _font;
00776         posToRowCol (pos, l, cnt);
00777         setCursorPosition(l, cnt+1); // the new word will get the same markup now as the first character of the word
00778         _bold = bold();
00779         _underline = underline();
00780         _italic = italic();
00781         _color = color();
00782         _font = currentFont();
00783         corrected(oldWord, newWord, pos);
00784         setSelection (l, cnt, l, cnt+newWord.length());
00785         setBold(_bold);
00786         setItalic(_italic);
00787         setUnderline(_underline);
00788         setColor(_color);
00789         setCurrentFont(_font);
00790     }
00791 
00792 }
00793 
00794 void KMEdit::slotSpellcheck2(KSpell*)
00795 {
00796   // Make sure words ignored by the highlighter are ignored by KSpell as well
00797   if ( mHighlighter ) {
00798     for ( uint i = 0; i < mHighlighter->ignoredWords().size(); i++ )
00799       mKSpellForDialog->ignore( mHighlighter->ignoredWords()[i] );
00800   }
00801 
00802     if( !mSpellLineEdit)
00803     {
00804         spellcheck_start();
00805 
00806         QString quotePrefix;
00807         if(mComposer && mComposer->msg())
00808         {
00809             int languageNr = GlobalSettings::self()->replyCurrentLanguage();
00810             ReplyPhrases replyPhrases( QString::number(languageNr) );
00811             replyPhrases.readConfig();
00812 
00813             quotePrefix = mComposer->msg()->formatString(
00814                  replyPhrases.indentPrefix() );
00815         }
00816 
00817         kdDebug(5006) << "spelling: new SpellingFilter with prefix=\"" << quotePrefix << "\"" << endl;
00818         QTextEdit plaintext;
00819         plaintext.setText(text());
00820         plaintext.setTextFormat(Qt::PlainText);
00821         mSpellingFilter = new SpellingFilter(plaintext.text(), quotePrefix, SpellingFilter::FilterUrls,
00822                                              SpellingFilter::FilterEmailAddresses);
00823 
00824         mKSpellForDialog->check(mSpellingFilter->filteredText());
00825     }
00826     else if( mComposer )
00827         mKSpellForDialog->check( mComposer->sujectLineWidget()->text());
00828 }
00829 
00830 void KMEdit::slotSpellResult(const QString &s)
00831 {
00832     if( !mSpellLineEdit)
00833         spellcheck_stop();
00834 
00835   int dlgResult = mKSpellForDialog->dlgResult();
00836   if ( dlgResult == KS_CANCEL )
00837   {
00838       if( mSpellLineEdit)
00839       {
00840           //stop spell check
00841           mSpellLineEdit = false;
00842           QString tmpText( s );
00843           tmpText =  tmpText.remove('\n');
00844 
00845           if( tmpText != mComposer->sujectLineWidget()->text() )
00846               mComposer->sujectLineWidget()->setText( tmpText );
00847       }
00848       else
00849       {
00850           setModified(true);
00851       }
00852   }
00853   mKSpellForDialog->cleanUp();
00854   KDictSpellingHighlighter::dictionaryChanged();
00855 
00856   emit spellcheck_done( dlgResult );
00857 }
00858 
00859 void KMEdit::slotSpellDone()
00860 {
00861   kdDebug(5006)<<" void KMEdit::slotSpellDone()\n";
00862   KSpell::spellStatus status = mKSpellForDialog->status();
00863   delete mKSpellForDialog;
00864   mKSpellForDialog = 0;
00865 
00866   kdDebug(5006) << "spelling: delete SpellingFilter" << endl;
00867   delete mSpellingFilter;
00868   mSpellingFilter = 0;
00869   mComposer->sujectLineWidget()->deselect();
00870   if (status == KSpell::Error)
00871   {
00872      KMessageBox::sorry( topLevelWidget(),
00873                          i18n("ISpell/Aspell could not be started. Please "
00874                               "make sure you have ISpell or Aspell properly "
00875                               "configured and in your PATH.") );
00876      emit spellcheck_done( KS_CANCEL );
00877   }
00878   else if (status == KSpell::Crashed)
00879   {
00880      spellcheck_stop();
00881      KMessageBox::sorry( topLevelWidget(),
00882                          i18n("ISpell/Aspell seems to have crashed.") );
00883      emit spellcheck_done( KS_CANCEL );
00884   }
00885   else
00886   {
00887       if( mSpellLineEdit )
00888           spellcheck();
00889       else if( !mComposer->subjectTextWasSpellChecked() && status == KSpell::FinishedNoMisspellingsEncountered )
00890           KMessageBox::information( topLevelWidget(),
00891                                     i18n("No misspellings encountered.") );
00892   }
00893 }
00894 
00895 void KMEdit::setCursorPositionFromStart( unsigned int pos ) {
00896   unsigned int l = 0;
00897   unsigned int c = 0;
00898   posToRowCol( pos, l, c );
00899   // kdDebug() << "Num lines: " << numLines() << endl;
00900   // kdDebug() << "Position " << pos << " converted to " << l << ":" << c << endl;
00901   setCursorPosition( l, c );
00902   ensureCursorVisible();
00903 }
00904 
00905 #include "kmedit.moc"
KDE Home | KDE Accessibility Home | Description of Access Keys