kmail

kmcomposewin.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 #undef GrayScale
00007 #undef Color
00008 #include <config.h>
00009 
00010 #define REALLY_WANT_KMCOMPOSEWIN_H
00011 #include "kmcomposewin.h"
00012 #undef REALLY_WANT_KMCOMPOSEWIN_H
00013 
00014 #include "kmedit.h"
00015 #include "kmlineeditspell.h"
00016 #include "kmatmlistview.h"
00017 
00018 #include "kmmainwin.h"
00019 #include "kmreadermainwin.h"
00020 #include "messagesender.h"
00021 #include "kmmsgpartdlg.h"
00022 #include <kpgpblock.h>
00023 #include <kaddrbook.h>
00024 #include "kmaddrbook.h"
00025 #include "kmmsgdict.h"
00026 #include "kmfolderimap.h"
00027 #include "kmfoldermgr.h"
00028 #include "kmfoldercombobox.h"
00029 #include "kmtransport.h"
00030 #include "kmcommands.h"
00031 #include "kcursorsaver.h"
00032 #include "partNode.h"
00033 #include "encodingdetector.h"
00034 #include "attachmentlistview.h"
00035 #include "transportmanager.h"
00036 using KMail::AttachmentListView;
00037 #include "dictionarycombobox.h"
00038 using KMail::DictionaryComboBox;
00039 #include "addressesdialog.h"
00040 using KPIM::AddressesDialog;
00041 #include "addresseeemailselection.h"
00042 using KPIM::AddresseeEmailSelection;
00043 using KPIM::AddresseeSelectorDialog;
00044 #include <maillistdrag.h>
00045 using KPIM::MailListDrag;
00046 #include "recentaddresses.h"
00047 using KRecentAddress::RecentAddresses;
00048 #include "kleo_util.h"
00049 #include "stl_util.h"
00050 #include "recipientseditor.h"
00051 #include "editorwatcher.h"
00052 
00053 #include "attachmentcollector.h"
00054 #include "objecttreeparser.h"
00055 
00056 #include "kmfoldermaildir.h"
00057 
00058 #include <libkpimidentities/identitymanager.h>
00059 #include <libkpimidentities/identitycombo.h>
00060 #include <libkpimidentities/identity.h>
00061 #include <libkdepim/kfileio.h>
00062 #include <libemailfunctions/email.h>
00063 #include <kleo/cryptobackendfactory.h>
00064 #include <kleo/exportjob.h>
00065 #include <kleo/specialjob.h>
00066 #include <ui/progressdialog.h>
00067 #include <ui/keyselectiondialog.h>
00068 
00069 #include <gpgmepp/context.h>
00070 #include <gpgmepp/key.h>
00071 
00072 #include <kabc/vcardconverter.h>
00073 #include <libkdepim/kvcarddrag.h>
00074 #include <kio/netaccess.h>
00075 
00076 #include "klistboxdialog.h"
00077 
00078 #include "messagecomposer.h"
00079 #include "chiasmuskeyselector.h"
00080 
00081 #include <kcharsets.h>
00082 #include <kcompletionbox.h>
00083 #include <kcursor.h>
00084 #include <kcombobox.h>
00085 #include <kstdaccel.h>
00086 #include <kpopupmenu.h>
00087 #include <kedittoolbar.h>
00088 #include <kkeydialog.h>
00089 #include <kdebug.h>
00090 #include <kfiledialog.h>
00091 #include <kwin.h>
00092 #include <kinputdialog.h>
00093 #include <kmessagebox.h>
00094 #include <kurldrag.h>
00095 #include <kio/scheduler.h>
00096 #include <ktempfile.h>
00097 #include <klocale.h>
00098 #include <kapplication.h>
00099 #include <kstatusbar.h>
00100 #include <kaction.h>
00101 #include <kstdaction.h>
00102 #include <kdirwatch.h>
00103 #include <kstdguiitem.h>
00104 #include <kiconloader.h>
00105 #include <kpushbutton.h>
00106 #include <kuserprofile.h>
00107 #include <krun.h>
00108 #include <ktempdir.h>
00109 #include <kstandarddirs.h>
00110 //#include <keditlistbox.h>
00111 #include "globalsettings.h"
00112 #include "replyphrases.h"
00113 
00114 #include <kspell.h>
00115 #include <kspelldlg.h>
00116 #include <spellingfilter.h>
00117 #include <ksyntaxhighlighter.h>
00118 #include <kcolordialog.h>
00119 #include <kzip.h>
00120 #include <ksavefile.h>
00121 
00122 #include <qtabdialog.h>
00123 #include <qregexp.h>
00124 #include <qbuffer.h>
00125 #include <qtooltip.h>
00126 #include <qtextcodec.h>
00127 #include <qheader.h>
00128 #include <qwhatsthis.h>
00129 #include <qfontdatabase.h>
00130 
00131 #include <mimelib/mimepp.h>
00132 
00133 #include <algorithm>
00134 #include <memory>
00135 
00136 #include <sys/stat.h>
00137 #include <sys/types.h>
00138 #include <stdlib.h>
00139 #include <unistd.h>
00140 #include <errno.h>
00141 #include <fcntl.h>
00142 #include <assert.h>
00143 
00144 #include "kmcomposewin.moc"
00145 
00146 #include "snippetwidget.h"
00147 
00148 KMail::Composer * KMail::makeComposer( KMMessage * msg, uint identitiy ) {
00149   return KMComposeWin::create( msg, identitiy );
00150 }
00151 
00152 KMail::Composer * KMComposeWin::create( KMMessage * msg, uint identitiy ) {
00153   return new KMComposeWin( msg, identitiy );
00154 }
00155 
00156 //-----------------------------------------------------------------------------
00157 KMComposeWin::KMComposeWin( KMMessage *aMsg, uint id  )
00158   : MailComposerIface(), KMail::Composer( "kmail-composer#" ),
00159     mSpellCheckInProgress( false ),
00160     mDone( false ),
00161     mAtmModified( false ),
00162     mMsg( 0 ),
00163     mAttachMenu( 0 ),
00164     mSigningAndEncryptionExplicitlyDisabled( false ),
00165     mFolder( 0 ),
00166     mUseHTMLEditor( false ),
00167     mId( id ),
00168     mAttachPK( 0 ), mAttachMPK( 0 ),
00169     mAttachRemoveAction( 0 ), mAttachSaveAction( 0 ), mAttachPropertiesAction( 0 ),
00170     mAppendSignatureAction( 0 ), mPrependSignatureAction( 0 ), mInsertSignatureAction( 0 ),
00171     mSignAction( 0 ), mEncryptAction( 0 ), mRequestMDNAction( 0 ),
00172     mUrgentAction( 0 ), mAllFieldsAction( 0 ), mFromAction( 0 ),
00173     mReplyToAction( 0 ), mToAction( 0 ), mCcAction( 0 ), mBccAction( 0 ),
00174     mSubjectAction( 0 ),
00175     mIdentityAction( 0 ), mTransportAction( 0 ), mFccAction( 0 ),
00176     mWordWrapAction( 0 ), mFixedFontAction( 0 ), mAutoSpellCheckingAction( 0 ),
00177     mDictionaryAction( 0 ), mSnippetAction( 0 ),
00178     mEncodingAction( 0 ),
00179     mCryptoModuleAction( 0 ),
00180     mEncryptChiasmusAction( 0 ),
00181     mEncryptWithChiasmus( false ),
00182     mComposer( 0 ),
00183     mLabelWidth( 0 ),
00184     mAutoSaveTimer( 0 ), mLastAutoSaveErrno( 0 ),
00185     mSignatureStateIndicator( 0 ), mEncryptionStateIndicator( 0 ),
00186     mPreserveUserCursorPosition( false ),
00187     mPreventFccOverwrite( false ),
00188     mCheckForRecipients( true )
00189 {
00190   mClassicalRecipients = GlobalSettings::self()->recipientsEditorType() ==
00191     GlobalSettings::EnumRecipientsEditorType::Classic;
00192 
00193   mSubjectTextWasSpellChecked = false;
00194   if (kmkernel->xmlGuiInstance())
00195     setInstance( kmkernel->xmlGuiInstance() );
00196   mMainWidget = new QWidget(this);
00197   // splitter between the headers area and the actual editor
00198   mHeadersToEditorSplitter = new QSplitter( Qt::Vertical, mMainWidget, "mHeadersToEditorSplitter" );
00199   mHeadersToEditorSplitter->setChildrenCollapsible( false );
00200   mHeadersArea = new QWidget( mHeadersToEditorSplitter );
00201   mHeadersArea->setSizePolicy( mHeadersToEditorSplitter->sizePolicy().horData(), QSizePolicy::Maximum );
00202   QVBoxLayout *v = new QVBoxLayout( mMainWidget );
00203   v->addWidget( mHeadersToEditorSplitter );
00204   mIdentity = new KPIM::IdentityCombo(kmkernel->identityManager(), mHeadersArea);
00205   mDictionaryCombo = new DictionaryComboBox( mHeadersArea );
00206   mFcc = new KMFolderComboBox(mHeadersArea);
00207   mFcc->showOutboxFolder( false );
00208   mTransport = new QComboBox(true, mHeadersArea);
00209   mEdtFrom = new KMLineEdit(false,mHeadersArea, "fromLine");
00210 
00211   mEdtReplyTo = new KMLineEdit(true,mHeadersArea, "replyToLine");
00212   mLblReplyTo = new QLabel(mHeadersArea);
00213   mBtnReplyTo = new QPushButton("...",mHeadersArea);
00214   mBtnReplyTo->setFocusPolicy(QWidget::NoFocus);
00215   connect(mBtnReplyTo,SIGNAL(clicked()),SLOT(slotAddrBookReplyTo()));
00216   connect(mEdtReplyTo,SIGNAL(completionModeChanged(KGlobalSettings::Completion)),
00217           SLOT(slotCompletionModeChanged(KGlobalSettings::Completion)));
00218 
00219   if ( mClassicalRecipients ) {
00220     mRecipientsEditor = 0;
00221 
00222     mEdtTo = new KMLineEdit(true,mHeadersArea, "toLine");
00223     mEdtCc = new KMLineEdit(true,mHeadersArea, "ccLine");
00224     mEdtBcc = new KMLineEdit(true,mHeadersArea, "bccLine");
00225 
00226     mLblTo = new QLabel(mHeadersArea);
00227     mLblCc = new QLabel(mHeadersArea);
00228     mLblBcc = new QLabel(mHeadersArea);
00229 
00230     mBtnTo = new QPushButton("...",mHeadersArea);
00231     mBtnCc = new QPushButton("...",mHeadersArea);
00232     mBtnBcc = new QPushButton("...",mHeadersArea);
00233     //mBtnFrom = new QPushButton("...",mHeadersArea);
00234 
00235     QString tip = i18n("Select email address(es)");
00236     QToolTip::add( mBtnTo, tip );
00237     QToolTip::add( mBtnCc, tip );
00238     QToolTip::add( mBtnBcc, tip );
00239     QToolTip::add( mBtnReplyTo, tip );
00240 
00241     mBtnTo->setFocusPolicy(QWidget::NoFocus);
00242     mBtnCc->setFocusPolicy(QWidget::NoFocus);
00243     mBtnBcc->setFocusPolicy(QWidget::NoFocus);
00244     //mBtnFrom->setFocusPolicy(QWidget::NoFocus);
00245 
00246     connect(mBtnTo,SIGNAL(clicked()),SLOT(slotAddrBookTo()));
00247     connect(mBtnCc,SIGNAL(clicked()),SLOT(slotAddrBookTo()));
00248     connect(mBtnBcc,SIGNAL(clicked()),SLOT(slotAddrBookTo()));
00249     //connect(mBtnFrom,SIGNAL(clicked()),SLOT(slotAddrBookFrom()));
00250 
00251     connect(mEdtTo,SIGNAL(completionModeChanged(KGlobalSettings::Completion)),
00252             SLOT(slotCompletionModeChanged(KGlobalSettings::Completion)));
00253     connect(mEdtCc,SIGNAL(completionModeChanged(KGlobalSettings::Completion)),
00254             SLOT(slotCompletionModeChanged(KGlobalSettings::Completion)));
00255     connect(mEdtBcc,SIGNAL(completionModeChanged(KGlobalSettings::Completion)),
00256             SLOT(slotCompletionModeChanged(KGlobalSettings::Completion)));
00257 
00258     mEdtTo->setFocus();
00259   } else {
00260     mEdtTo = 0;
00261     mEdtCc = 0;
00262     mEdtBcc = 0;
00263 
00264     mLblTo = 0;
00265     mLblCc = 0;
00266     mLblBcc = 0;
00267 
00268     mBtnTo = 0;
00269     mBtnCc = 0;
00270     mBtnBcc = 0;
00271     //mBtnFrom = 0;
00272 
00273     mRecipientsEditor = new RecipientsEditor( mHeadersArea );
00274     connect( mRecipientsEditor,
00275              SIGNAL( completionModeChanged( KGlobalSettings::Completion ) ),
00276              SLOT( slotCompletionModeChanged( KGlobalSettings::Completion ) ) );
00277     connect( mRecipientsEditor, SIGNAL(sizeHintChanged()), SLOT(recipientEditorSizeHintChanged()) );
00278 
00279     mRecipientsEditor->setFocus();
00280   }
00281   mEdtSubject = new KMLineEditSpell(false,mHeadersArea, "subjectLine");
00282   mLblIdentity = new QLabel(mHeadersArea);
00283   mDictionaryLabel = new QLabel( mHeadersArea );
00284   mLblFcc = new QLabel(mHeadersArea);
00285   mLblTransport = new QLabel(mHeadersArea);
00286   mLblFrom = new QLabel(mHeadersArea);
00287   mLblSubject = new QLabel(mHeadersArea);
00288   QString sticky = i18n("Sticky");
00289   mBtnIdentity = new QCheckBox(sticky,mHeadersArea);
00290   mBtnFcc = new QCheckBox(sticky,mHeadersArea);
00291   mBtnTransport = new QCheckBox(sticky,mHeadersArea);
00292 
00293   //setWFlags( WType_TopLevel | WStyle_Dialog );
00294   mHtmlMarkup = GlobalSettings::self()->useHtmlMarkup();
00295   mShowHeaders = GlobalSettings::self()->headers();
00296   mDone = false;
00297   mGrid = 0;
00298   mAtmListView = 0;
00299   mAtmList.setAutoDelete(true);
00300   mAtmTempList.setAutoDelete(true);
00301   mAtmModified = false;
00302   mAutoDeleteMsg = false;
00303   mFolder = 0;
00304   mAutoCharset = true;
00305   mFixedFontAction = 0;
00306   mTempDir = 0;
00307   // the attachment view is separated from the editor by a splitter
00308   mSplitter = new QSplitter( Qt::Vertical, mHeadersToEditorSplitter, "mSplitter" );
00309   mSplitter->setChildrenCollapsible( false );
00310   mSnippetSplitter = new QSplitter( Qt::Horizontal, mSplitter, "mSnippetSplitter");
00311   mSnippetSplitter->setChildrenCollapsible( false );
00312 
00313   QWidget *editorAndCryptoStateIndicators = new QWidget( mSnippetSplitter );
00314   QVBoxLayout *vbox = new QVBoxLayout( editorAndCryptoStateIndicators );
00315   QHBoxLayout *hbox = new QHBoxLayout( vbox );
00316   {
00317       mSignatureStateIndicator = new QLabel( editorAndCryptoStateIndicators );
00318       mSignatureStateIndicator->setAlignment( Qt::AlignHCenter );
00319       hbox->addWidget( mSignatureStateIndicator );
00320 
00321       KConfigGroup reader( KMKernel::config(), "Reader" );
00322       QPalette p( mSignatureStateIndicator->palette() );
00323 
00324       QColor defaultSignedColor( 0x40, 0xFF, 0x40 ); // light green // pgp ok, trusted key
00325       QColor defaultEncryptedColor( 0x00, 0x80, 0xFF ); // light blue // pgp encrypted
00326       p.setColor( QColorGroup::Background, reader.readColorEntry( "PGPMessageOkKeyOk", &defaultSignedColor ) );
00327       mSignatureStateIndicator->setPalette( p );
00328 
00329       mEncryptionStateIndicator = new QLabel( editorAndCryptoStateIndicators );
00330       mEncryptionStateIndicator->setAlignment( Qt::AlignHCenter );
00331       hbox->addWidget( mEncryptionStateIndicator );
00332       p.setColor( QColorGroup::Background, reader.readColorEntry( "PGPMessageEncr" , &defaultEncryptedColor ) );
00333       mEncryptionStateIndicator->setPalette( p );
00334   }
00335 
00336   mEditor = new KMEdit( editorAndCryptoStateIndicators, this, mDictionaryCombo->spellConfig() );
00337   vbox->addWidget( mEditor );
00338 
00339   mSnippetWidget = new SnippetWidget( mEditor, actionCollection(), mSnippetSplitter );
00340   mSnippetWidget->setShown( GlobalSettings::self()->showSnippetManager() );
00341 
00342   //  mSplitter->moveToFirst( editorAndCryptoStateIndicators );
00343   mSplitter->setOpaqueResize( true );
00344 
00345   mEditor->initializeAutoSpellChecking();
00346   mEditor->setTextFormat(Qt::PlainText);
00347   mEditor->setAcceptDrops( true );
00348 
00349   QWhatsThis::add( mBtnIdentity,
00350     GlobalSettings::self()->stickyIdentityItem()->whatsThis() );
00351   QWhatsThis::add( mBtnFcc,
00352     GlobalSettings::self()->stickyFccItem()->whatsThis() );
00353   QWhatsThis::add( mBtnTransport,
00354     GlobalSettings::self()->stickyTransportItem()->whatsThis() );
00355 
00356   mSpellCheckInProgress=false;
00357 
00358   setCaption( i18n("Composer") );
00359   setMinimumSize(200,200);
00360 
00361   mBtnIdentity->setFocusPolicy(QWidget::NoFocus);
00362   mBtnFcc->setFocusPolicy(QWidget::NoFocus);
00363   mBtnTransport->setFocusPolicy(QWidget::NoFocus);
00364 
00365   mAtmListView = new AttachmentListView( this, mSplitter,
00366                                          "attachment list view" );
00367   mAtmListView->setSelectionMode( QListView::Extended );
00368   mAtmListView->addColumn( i18n("Name"), 200 );
00369   mAtmListView->addColumn( i18n("Size"), 80 );
00370   mAtmListView->addColumn( i18n("Encoding"), 120 );
00371   int atmColType = mAtmListView->addColumn( i18n("Type"), 120 );
00372   // Stretch "Type".
00373   mAtmListView->header()->setStretchEnabled( true, atmColType );
00374   mAtmEncryptColWidth = 80;
00375   mAtmSignColWidth = 80;
00376   mAtmCompressColWidth = 100;
00377   mAtmColCompress = mAtmListView->addColumn( i18n("Compress"),
00378                                             mAtmCompressColWidth );
00379   mAtmColEncrypt = mAtmListView->addColumn( i18n("Encrypt"),
00380                                             mAtmEncryptColWidth );
00381   mAtmColSign    = mAtmListView->addColumn( i18n("Sign"),
00382                                             mAtmSignColWidth );
00383   mAtmListView->setColumnWidth( mAtmColEncrypt, 0 );
00384   mAtmListView->setColumnWidth( mAtmColSign,    0 );
00385   mAtmListView->setAllColumnsShowFocus( true );
00386 
00387   connect( mAtmListView,
00388            SIGNAL( doubleClicked( QListViewItem* ) ),
00389            SLOT( slotAttachEdit() ) );
00390   connect( mAtmListView,
00391            SIGNAL( rightButtonPressed( QListViewItem*, const QPoint&, int ) ),
00392            SLOT( slotAttachPopupMenu( QListViewItem*, const QPoint&, int ) ) );
00393   connect( mAtmListView,
00394            SIGNAL( selectionChanged() ),
00395            SLOT( slotUpdateAttachActions() ) );
00396   connect( mAtmListView,
00397            SIGNAL( attachmentDeleted() ),
00398            SLOT( slotAttachRemove() ) );
00399   connect( mAtmListView,
00400            SIGNAL( dragStarted() ),
00401            SLOT( slotAttachmentDragStarted() ) );
00402   mAttachMenu = 0;
00403 
00404   readConfig();
00405   setupStatusBar();
00406   setupActions();
00407   setupEditor();
00408   slotUpdateSignatureAndEncrypionStateIndicators();
00409 
00410   applyMainWindowSettings(KMKernel::config(), "Composer");
00411 
00412   connect( mEdtSubject, SIGNAL( subjectTextSpellChecked() ),
00413            SLOT( slotSubjectTextSpellChecked() ) );
00414   connect(mEdtSubject,SIGNAL(textChanged(const QString&)),
00415           SLOT(slotUpdWinTitle(const QString&)));
00416   connect(mIdentity,SIGNAL(identityChanged(uint)),
00417           SLOT(slotIdentityChanged(uint)));
00418   connect( kmkernel->identityManager(), SIGNAL(changed(uint)),
00419           SLOT(slotIdentityChanged(uint)));
00420 
00421   connect(mEdtFrom,SIGNAL(completionModeChanged(KGlobalSettings::Completion)),
00422           SLOT(slotCompletionModeChanged(KGlobalSettings::Completion)));
00423   connect(kmkernel->folderMgr(),SIGNAL(folderRemoved(KMFolder*)),
00424                                   SLOT(slotFolderRemoved(KMFolder*)));
00425   connect(kmkernel->imapFolderMgr(),SIGNAL(folderRemoved(KMFolder*)),
00426                                   SLOT(slotFolderRemoved(KMFolder*)));
00427   connect(kmkernel->dimapFolderMgr(),SIGNAL(folderRemoved(KMFolder*)),
00428                                   SLOT(slotFolderRemoved(KMFolder*)));
00429   connect( kmkernel, SIGNAL( configChanged() ),
00430            this, SLOT( slotConfigChanged() ) );
00431 
00432   connect (mEditor, SIGNAL (spellcheck_done(int)),
00433     this, SLOT (slotSpellcheckDone (int)));
00434   connect (mEditor, SIGNAL( attachPNGImageData(const QByteArray &) ),
00435     this, SLOT ( slotAttachPNGImageData(const QByteArray &) ) );
00436   connect (mEditor, SIGNAL( focusChanged(bool) ),
00437     this, SLOT (editorFocusChanged(bool)) );
00438 
00439   mMainWidget->resize(480,510);
00440   setCentralWidget(mMainWidget);
00441   rethinkFields();
00442 
00443   if ( !mClassicalRecipients ) {
00444     // This is ugly, but if it isn't called the line edits in the recipients
00445     // editor aren't wide enough until the first resize event comes.
00446     rethinkFields();
00447   }
00448 
00449   if ( GlobalSettings::self()->useExternalEditor() ) {
00450     mEditor->setUseExternalEditor(true);
00451     mEditor->setExternalEditorPath( GlobalSettings::self()->externalEditor() );
00452   }
00453 
00454   initAutoSave();
00455   slotUpdateSignatureActions();
00456   mMsg = 0;
00457   if (aMsg)
00458     setMsg(aMsg);
00459   fontChanged( mEditor->currentFont() ); // set toolbar buttons to correct values
00460 
00461   mDone = true;
00462 }
00463 
00464 //-----------------------------------------------------------------------------
00465 KMComposeWin::~KMComposeWin()
00466 {
00467   writeConfig();
00468   if (mFolder && mMsg)
00469   {
00470     mAutoDeleteMsg = false;
00471     mFolder->addMsg(mMsg);
00472     // Ensure that the message is correctly and fully parsed
00473     mFolder->unGetMsg( mFolder->count() - 1 );
00474   }
00475   if (mAutoDeleteMsg) {
00476     delete mMsg;
00477     mMsg = 0;
00478   }
00479   QMap<KIO::Job*, atmLoadData>::Iterator it = mMapAtmLoadData.begin();
00480   while ( it != mMapAtmLoadData.end() )
00481   {
00482     KIO::Job *job = it.key();
00483     mMapAtmLoadData.remove( it );
00484     job->kill();
00485     it = mMapAtmLoadData.begin();
00486   }
00487   deleteAll( mComposedMessages );
00488 
00489   for ( std::set<KTempDir*>::iterator it = mTempDirs.begin() ; it != mTempDirs.end() ; ++it ) {
00490       delete *it;
00491   }
00492 }
00493 
00494 void KMComposeWin::setAutoDeleteWindow( bool f )
00495 {
00496   if ( f )
00497     setWFlags( getWFlags() | WDestructiveClose );
00498   else
00499     setWFlags( getWFlags() & ~WDestructiveClose );
00500 }
00501 
00502 //-----------------------------------------------------------------------------
00503 void KMComposeWin::send(int how)
00504 {
00505   switch (how) {
00506     case 1:
00507       slotSendNow();
00508       break;
00509     default:
00510     case 0:
00511       // TODO: find out, what the default send method is and send it this way
00512     case 2:
00513       slotSendLater();
00514       break;
00515   }
00516 }
00517 
00518 //-----------------------------------------------------------------------------
00519 void KMComposeWin::addAttachmentsAndSend(const KURL::List &urls, const QString &/*comment*/, int how)
00520 {
00521   if (urls.isEmpty())
00522   {
00523     send(how);
00524     return;
00525   }
00526   mAttachFilesSend = how;
00527   mAttachFilesPending = urls;
00528   connect(this, SIGNAL(attachmentAdded(const KURL&, bool)), SLOT(slotAttachedFile(const KURL&)));
00529   for( KURL::List::ConstIterator itr = urls.begin(); itr != urls.end(); ++itr ) {
00530     if (!addAttach( *itr ))
00531       mAttachFilesPending.remove(mAttachFilesPending.find(*itr)); // only remove one copy of the url
00532   }
00533 
00534   if (mAttachFilesPending.isEmpty() && mAttachFilesSend == how)
00535   {
00536     send(mAttachFilesSend);
00537     mAttachFilesSend = -1;
00538   }
00539 }
00540 
00541 void KMComposeWin::slotAttachedFile(const KURL &url)
00542 {
00543   if (mAttachFilesPending.isEmpty())
00544     return;
00545   mAttachFilesPending.remove(mAttachFilesPending.find(url)); // only remove one copy of url
00546   if (mAttachFilesPending.isEmpty())
00547   {
00548     send(mAttachFilesSend);
00549     mAttachFilesSend = -1;
00550   }
00551 }
00552 
00553 //-----------------------------------------------------------------------------
00554 void KMComposeWin::addAttachment(KURL url,QString /*comment*/)
00555 {
00556   addAttach(url);
00557 }
00558 
00559 //-----------------------------------------------------------------------------
00560 void KMComposeWin::addAttachment(const QString &name,
00561                                  const QCString &/*cte*/,
00562                                  const QByteArray &data,
00563                                  const QCString &type,
00564                                  const QCString &subType,
00565                                  const QCString &paramAttr,
00566                                  const QString &paramValue,
00567                                  const QCString &contDisp)
00568 {
00569   if (!data.isEmpty()) {
00570     KMMessagePart *msgPart = new KMMessagePart;
00571     msgPart->setName(name);
00572     if( type == "message" && subType == "rfc822" ) {
00573        msgPart->setMessageBody( data );
00574     } else {
00575        QValueList<int> dummy;
00576        msgPart->setBodyAndGuessCte(data, dummy,
00577               kmkernel->msgSender()->sendQuotedPrintable());
00578     }
00579     msgPart->setTypeStr(type);
00580     msgPart->setSubtypeStr(subType);
00581     msgPart->setParameter(paramAttr,paramValue);
00582     msgPart->setContentDisposition(contDisp);
00583     addAttach(msgPart);
00584   }
00585 }
00586 
00587 //-----------------------------------------------------------------------------
00588 void KMComposeWin::slotAttachPNGImageData(const QByteArray &image)
00589 {
00590   bool ok;
00591 
00592   QString attName = KInputDialog::getText( "KMail", i18n("Name of the attachment:"), QString::null, &ok, this );
00593   if ( !ok )
00594     return;
00595 
00596   if ( !attName.lower().endsWith(".png") ) attName += ".png";
00597 
00598   addAttachment( attName, "base64", image, "image", "png", QCString(), QString(), QCString() );
00599 }
00600 
00601 //-----------------------------------------------------------------------------
00602 void KMComposeWin::setBody(QString body)
00603 {
00604   mEditor->setText(body);
00605 }
00606 
00607 //-----------------------------------------------------------------------------
00608 bool KMComposeWin::event(QEvent *e)
00609 {
00610   if (e->type() == QEvent::ApplicationPaletteChange)
00611   {
00612      readColorConfig();
00613   }
00614   return KMail::Composer::event(e);
00615 }
00616 
00617 
00618 //-----------------------------------------------------------------------------
00619 void KMComposeWin::readColorConfig(void)
00620 {
00621   if ( GlobalSettings::self()->useDefaultColors() ) {
00622     mForeColor = QColor(kapp->palette().active().text());
00623     mBackColor = QColor(kapp->palette().active().base());
00624   } else {
00625     mForeColor = GlobalSettings::self()->foregroundColor();
00626     mBackColor = GlobalSettings::self()->backgroundColor();
00627   }
00628 
00629   // Color setup
00630   mPalette = kapp->palette();
00631   QColorGroup cgrp  = mPalette.active();
00632   cgrp.setColor( QColorGroup::Base, mBackColor);
00633   cgrp.setColor( QColorGroup::Text, mForeColor);
00634   mPalette.setDisabled(cgrp);
00635   mPalette.setActive(cgrp);
00636   mPalette.setInactive(cgrp);
00637 
00638   mEdtFrom->setPalette(mPalette);
00639   mEdtReplyTo->setPalette(mPalette);
00640   if ( mClassicalRecipients ) {
00641     mEdtTo->setPalette(mPalette);
00642     mEdtCc->setPalette(mPalette);
00643     mEdtBcc->setPalette(mPalette);
00644   }
00645   mEdtSubject->setPalette(mPalette);
00646   mTransport->setPalette(mPalette);
00647   mEditor->setPalette(mPalette);
00648   mFcc->setPalette(mPalette);
00649 }
00650 
00651 //-----------------------------------------------------------------------------
00652 void KMComposeWin::readConfig( bool reload /* = false */ )
00653 {
00654   mDefCharset = KMMessage::defaultCharset();
00655   mBtnIdentity->setChecked( GlobalSettings::self()->stickyIdentity() );
00656   if (mBtnIdentity->isChecked()) {
00657     mId = (GlobalSettings::self()->previousIdentity()!=0) ?
00658            GlobalSettings::self()->previousIdentity() : mId;
00659   }
00660   mBtnFcc->setChecked( GlobalSettings::self()->stickyFcc() );
00661   mBtnTransport->setChecked( GlobalSettings::self()->stickyTransport() );
00662   QStringList transportHistory = GlobalSettings::self()->transportHistory();
00663   QString currentTransport = GlobalSettings::self()->currentTransport();
00664 
00665   mEdtFrom->setCompletionMode( (KGlobalSettings::Completion)GlobalSettings::self()->completionMode() );
00666   mEdtReplyTo->setCompletionMode( (KGlobalSettings::Completion)GlobalSettings::self()->completionMode() );
00667   if ( mClassicalRecipients ) {
00668     mEdtTo->setCompletionMode( (KGlobalSettings::Completion)GlobalSettings::self()->completionMode() );
00669     mEdtCc->setCompletionMode( (KGlobalSettings::Completion)GlobalSettings::self()->completionMode() );
00670     mEdtBcc->setCompletionMode( (KGlobalSettings::Completion)GlobalSettings::self()->completionMode() );
00671   }
00672   else
00673     mRecipientsEditor->setCompletionMode( (KGlobalSettings::Completion)GlobalSettings::self()->completionMode() );
00674 
00675   readColorConfig();
00676 
00677   if ( GlobalSettings::self()->useDefaultFonts() ) {
00678     mBodyFont = KGlobalSettings::generalFont();
00679     mFixedFont = KGlobalSettings::fixedFont();
00680   } else {
00681     mBodyFont = GlobalSettings::self()->composerFont();
00682     mFixedFont = GlobalSettings::self()->fixedFont();
00683   }
00684 
00685   slotUpdateFont();
00686   mEdtFrom->setFont(mBodyFont);
00687   mEdtReplyTo->setFont(mBodyFont);
00688   if ( mClassicalRecipients ) {
00689     mEdtTo->setFont(mBodyFont);
00690     mEdtCc->setFont(mBodyFont);
00691     mEdtBcc->setFont(mBodyFont);
00692   }
00693   mEdtSubject->setFont(mBodyFont);
00694 
00695   if ( !reload ) {
00696     QSize siz = GlobalSettings::self()->composerSize();
00697     if (siz.width() < 200) siz.setWidth(200);
00698     if (siz.height() < 200) siz.setHeight(200);
00699     resize(siz);
00700 
00701     if ( !GlobalSettings::self()->snippetSplitterPosition().isEmpty() ) {
00702       mSnippetSplitter->setSizes( GlobalSettings::self()->snippetSplitterPosition() );
00703     } else {
00704       QValueList<int> defaults;
00705       defaults << (int)(width() * 0.8) << (int)(width() * 0.2);
00706       mSnippetSplitter->setSizes( defaults );
00707     }
00708   }
00709 
00710   mIdentity->setCurrentIdentity( mId );
00711 
00712   kdDebug(5006) << "KMComposeWin::readConfig. " << mIdentity->currentIdentityName() << endl;
00713   const KPIM::Identity & ident =
00714     kmkernel->identityManager()->identityForUoid( mIdentity->currentIdentity() );
00715 
00716   mDictionaryCombo->setCurrentByDictionary( ident.dictionary() );
00717 
00718   mTransport->clear();
00719   mTransport->insertStringList( KMTransportInfo::availableTransports() );
00720   while ( transportHistory.count() > (uint)GlobalSettings::self()->maxTransportEntries() )
00721     transportHistory.remove( transportHistory.last() );
00722   mTransport->insertStringList( transportHistory );
00723   mTransport->setCurrentText( GlobalSettings::self()->defaultTransport() );
00724   if ( mBtnTransport->isChecked() ) {
00725     setTransport( currentTransport );
00726   }
00727 
00728   QString fccName = "";
00729   if ( mBtnFcc->isChecked() ) {
00730     fccName = GlobalSettings::self()->previousFcc();
00731   } else if ( !ident.fcc().isEmpty() ) {
00732       fccName = ident.fcc();
00733   }
00734 
00735   setFcc( fccName );
00736 }
00737 
00738 //-----------------------------------------------------------------------------
00739 void KMComposeWin::writeConfig(void)
00740 {
00741   GlobalSettings::self()->setHeaders( mShowHeaders );
00742   GlobalSettings::self()->setStickyTransport( mBtnTransport->isChecked() );
00743   GlobalSettings::self()->setStickyIdentity( mBtnIdentity->isChecked() );
00744   GlobalSettings::self()->setStickyFcc( mBtnFcc->isChecked() );
00745   GlobalSettings::self()->setPreviousIdentity( mIdentity->currentIdentity() );
00746   GlobalSettings::self()->setCurrentTransport( mTransport->currentText() );
00747   GlobalSettings::self()->setPreviousFcc( mFcc->getFolder()->idString() );
00748   GlobalSettings::self()->setAutoSpellChecking(
00749                         mAutoSpellCheckingAction->isChecked() );
00750   QStringList transportHistory = GlobalSettings::self()->transportHistory();
00751   transportHistory.remove(mTransport->currentText());
00752     if (KMTransportInfo::availableTransports().findIndex(mTransport
00753     ->currentText()) == -1) {
00754       transportHistory.prepend(mTransport->currentText());
00755   }
00756   GlobalSettings::self()->setTransportHistory( transportHistory );
00757   GlobalSettings::self()->setUseFixedFont( mFixedFontAction->isChecked() );
00758   GlobalSettings::self()->setUseHtmlMarkup( mHtmlMarkup );
00759   GlobalSettings::self()->setComposerSize( size() );
00760   GlobalSettings::self()->setShowSnippetManager( mSnippetAction->isChecked() );
00761 
00762   KConfigGroupSaver saver( KMKernel::config(), "Geometry" );
00763   saveMainWindowSettings( KMKernel::config(), "Composer" );
00764   GlobalSettings::setSnippetSplitterPosition( mSnippetSplitter->sizes() );
00765 
00766   // make sure config changes are written to disk, cf. bug 127538
00767   GlobalSettings::self()->writeConfig();
00768 }
00769 
00770 //-----------------------------------------------------------------------------
00771 void KMComposeWin::autoSaveMessage()
00772 {
00773   kdDebug(5006) << k_funcinfo << endl;
00774   if ( !mMsg || mComposer || mAutoSaveFilename.isEmpty() )
00775     return;
00776   kdDebug(5006) << k_funcinfo << "autosaving message" << endl;
00777 
00778   if ( mAutoSaveTimer )
00779     mAutoSaveTimer->stop();
00780 
00781   connect( this, SIGNAL( applyChangesDone( bool ) ),
00782            this, SLOT( slotContinueAutoSave() ) );
00783   // This method is called when KMail crashed, so don't try signing/encryption
00784   // and don't disable controls because it is also called from a timer and
00785   // then the disabling is distracting.
00786   applyChanges( true, true );
00787 
00788   // Don't continue before the applyChanges is done!
00789 }
00790 
00791 void KMComposeWin::slotContinueAutoSave()
00792 {
00793   disconnect( this, SIGNAL( applyChangesDone( bool ) ),
00794               this, SLOT( slotContinueAutoSave() ) );
00795 
00796   // Ok, it's done now - continue dead letter saving
00797   if ( mComposedMessages.isEmpty() ) {
00798     kdDebug(5006) << "Composing the message failed." << endl;
00799     return;
00800   }
00801   KMMessage *msg = mComposedMessages.first();
00802   if ( !msg ) // a bit of extra defensiveness
00803     return;
00804 
00805   kdDebug(5006) << k_funcinfo << "opening autoSaveFile " << mAutoSaveFilename
00806                 << endl;
00807   const QString filename =
00808     KMKernel::localDataPath() + "autosave/cur/" + mAutoSaveFilename;
00809   KSaveFile autoSaveFile( filename, 0600 );
00810   int status = autoSaveFile.status();
00811   kdDebug(5006) << k_funcinfo << "autoSaveFile.status() = " << status << endl;
00812   if ( status == 0 ) { // no error
00813     kdDebug(5006) << "autosaving message in " << filename << endl;
00814     int fd = autoSaveFile.handle();
00815     const DwString& msgStr = msg->asDwString();
00816     if ( ::write( fd, msgStr.data(), msgStr.length() ) == -1 )
00817       status = errno;
00818   }
00819   if ( status == 0 ) {
00820     kdDebug(5006) << k_funcinfo << "closing autoSaveFile" << endl;
00821     autoSaveFile.close();
00822     mLastAutoSaveErrno = 0;
00823   }
00824   else {
00825     kdDebug(5006) << k_funcinfo << "autosaving failed" << endl;
00826     autoSaveFile.abort();
00827     if ( status != mLastAutoSaveErrno ) {
00828       // don't show the same error message twice
00829       KMessageBox::queuedMessageBox( 0, KMessageBox::Sorry,
00830                                      i18n("Autosaving the message as %1 "
00831                                           "failed.\n"
00832                                           "Reason: %2" )
00833                                      .arg( filename, strerror( status ) ),
00834                                      i18n("Autosaving Failed") );
00835       mLastAutoSaveErrno = status;
00836     }
00837   }
00838 
00839   if ( autoSaveInterval() > 0 )
00840     updateAutoSave();
00841 }
00842 
00843 //-----------------------------------------------------------------------------
00844 void KMComposeWin::slotView(void)
00845 {
00846   if (!mDone)
00847     return; // otherwise called from rethinkFields during the construction
00848             // which is not the intended behavior
00849   int id;
00850 
00851   //This sucks awfully, but no, I cannot get an activated(int id) from
00852   // actionContainer()
00853   if (!sender()->isA("KToggleAction"))
00854     return;
00855   KToggleAction *act = (KToggleAction *) sender();
00856 
00857   if (act == mAllFieldsAction)
00858     id = 0;
00859   else if (act == mIdentityAction)
00860     id = HDR_IDENTITY;
00861   else if (act == mTransportAction)
00862     id = HDR_TRANSPORT;
00863   else if (act == mFromAction)
00864     id = HDR_FROM;
00865   else if (act == mReplyToAction)
00866     id = HDR_REPLY_TO;
00867   else if (act == mToAction)
00868     id = HDR_TO;
00869   else if (act == mCcAction)
00870     id = HDR_CC;
00871   else  if (act == mBccAction)
00872     id = HDR_BCC;
00873   else if (act == mSubjectAction)
00874     id = HDR_SUBJECT;
00875   else if (act == mFccAction)
00876     id = HDR_FCC;
00877   else if ( act == mDictionaryAction )
00878     id = HDR_DICTIONARY;
00879   else
00880    {
00881      id = 0;
00882      kdDebug(5006) << "Something is wrong (Oh, yeah?)" << endl;
00883      return;
00884    }
00885 
00886   // sanders There's a bug here this logic doesn't work if no
00887   // fields are shown and then show all fields is selected.
00888   // Instead of all fields being shown none are.
00889   if (!act->isChecked())
00890   {
00891     // hide header
00892     if (id > 0) mShowHeaders = mShowHeaders & ~id;
00893     else mShowHeaders = abs(mShowHeaders);
00894   }
00895   else
00896   {
00897     // show header
00898     if (id > 0) mShowHeaders |= id;
00899     else mShowHeaders = -abs(mShowHeaders);
00900   }
00901   rethinkFields(true);
00902 }
00903 
00904 int KMComposeWin::calcColumnWidth(int which, long allShowing, int width)
00905 {
00906   if ( (allShowing & which) == 0 )
00907     return width;
00908 
00909   QLabel *w;
00910   if ( which == HDR_IDENTITY )
00911     w = mLblIdentity;
00912   else if ( which == HDR_DICTIONARY )
00913     w = mDictionaryLabel;
00914   else if ( which == HDR_FCC )
00915     w = mLblFcc;
00916   else if ( which == HDR_TRANSPORT )
00917     w = mLblTransport;
00918   else if ( which == HDR_FROM )
00919     w = mLblFrom;
00920   else if ( which == HDR_REPLY_TO )
00921     w = mLblReplyTo;
00922   else if ( which == HDR_SUBJECT )
00923     w = mLblSubject;
00924   else
00925     return width;
00926 
00927   w->setBuddy( mEditor ); // set dummy so we don't calculate width of '&' for this label.
00928   w->adjustSize();
00929   w->show();
00930   return QMAX( width, w->sizeHint().width() );
00931 }
00932 
00933 void KMComposeWin::rethinkFields(bool fromSlot)
00934 {
00935   //This sucks even more but again no ids. sorry (sven)
00936   int mask, row, numRows;
00937   long showHeaders;
00938 
00939   if (mShowHeaders < 0)
00940     showHeaders = HDR_ALL;
00941   else
00942     showHeaders = mShowHeaders;
00943 
00944   for (mask=1,mNumHeaders=0; mask<=showHeaders; mask<<=1)
00945     if ((showHeaders&mask) != 0) mNumHeaders++;
00946 
00947   numRows = mNumHeaders + 1;
00948 
00949   delete mGrid;
00950 
00951   mGrid = new QGridLayout( mHeadersArea, numRows, 3, KDialogBase::marginHint()/2, KDialogBase::spacingHint());
00952   mGrid->setColStretch(0, 1);
00953   mGrid->setColStretch(1, 100);
00954   mGrid->setColStretch(2, 1);
00955   mGrid->setRowStretch(mNumHeaders, 100);
00956 
00957   row = 0;
00958   kdDebug(5006) << "KMComposeWin::rethinkFields" << endl;
00959   if (mRecipientsEditor)
00960     mLabelWidth = mRecipientsEditor->setFirstColumnWidth( 0 );
00961   mLabelWidth = calcColumnWidth( HDR_IDENTITY, showHeaders, mLabelWidth );
00962   mLabelWidth = calcColumnWidth( HDR_DICTIONARY, showHeaders, mLabelWidth );
00963   mLabelWidth = calcColumnWidth( HDR_FCC, showHeaders, mLabelWidth );
00964   mLabelWidth = calcColumnWidth( HDR_TRANSPORT, showHeaders, mLabelWidth );
00965   mLabelWidth = calcColumnWidth( HDR_FROM, showHeaders, mLabelWidth );
00966   mLabelWidth = calcColumnWidth( HDR_REPLY_TO, showHeaders, mLabelWidth );
00967   mLabelWidth = calcColumnWidth( HDR_SUBJECT, showHeaders, mLabelWidth );
00968 
00969   if (!fromSlot) mAllFieldsAction->setChecked(showHeaders==HDR_ALL);
00970 
00971   if (!fromSlot) mIdentityAction->setChecked(abs(mShowHeaders)&HDR_IDENTITY);
00972   rethinkHeaderLine(showHeaders,HDR_IDENTITY, row, i18n("&Identity:"),
00973                     mLblIdentity, mIdentity, mBtnIdentity);
00974 
00975   if (!fromSlot) mDictionaryAction->setChecked(abs(mShowHeaders)&HDR_DICTIONARY);
00976   rethinkHeaderLine(showHeaders,HDR_DICTIONARY, row, i18n("&Dictionary:"),
00977                     mDictionaryLabel, mDictionaryCombo, 0 );
00978 
00979   if (!fromSlot) mFccAction->setChecked(abs(mShowHeaders)&HDR_FCC);
00980   rethinkHeaderLine(showHeaders,HDR_FCC, row, i18n("&Sent-Mail folder:"),
00981                     mLblFcc, mFcc, mBtnFcc);
00982 
00983   if (!fromSlot) mTransportAction->setChecked(abs(mShowHeaders)&HDR_TRANSPORT);
00984   rethinkHeaderLine(showHeaders,HDR_TRANSPORT, row, i18n("&Mail transport:"),
00985                     mLblTransport, mTransport, mBtnTransport);
00986 
00987   if (!fromSlot) mFromAction->setChecked(abs(mShowHeaders)&HDR_FROM);
00988   rethinkHeaderLine(showHeaders,HDR_FROM, row, i18n("sender address field", "&From:"),
00989                     mLblFrom, mEdtFrom /*, mBtnFrom */ );
00990 
00991   QWidget *prevFocus = mEdtFrom;
00992 
00993   if (!fromSlot) mReplyToAction->setChecked(abs(mShowHeaders)&HDR_REPLY_TO);
00994   rethinkHeaderLine(showHeaders,HDR_REPLY_TO,row,i18n("&Reply to:"),
00995                   mLblReplyTo, mEdtReplyTo, mBtnReplyTo);
00996   if ( showHeaders & HDR_REPLY_TO ) {
00997     prevFocus = connectFocusMoving( prevFocus, mEdtReplyTo );
00998   }
00999 
01000   if ( mClassicalRecipients ) {
01001     if (!fromSlot) mToAction->setChecked(abs(mShowHeaders)&HDR_TO);
01002     rethinkHeaderLine(showHeaders, HDR_TO, row, i18n("recipient address field", "&To:"),
01003                     mLblTo, mEdtTo, mBtnTo,
01004                     i18n("Primary Recipients"),
01005                     i18n("<qt>The email addresses you put "
01006                          "in this field receive a copy of the email.</qt>"));
01007     if ( showHeaders & HDR_TO ) {
01008       prevFocus = connectFocusMoving( prevFocus, mEdtTo );
01009     }
01010 
01011     if (!fromSlot) mCcAction->setChecked(abs(mShowHeaders)&HDR_CC);
01012     rethinkHeaderLine(showHeaders, HDR_CC, row, i18n("&Copy to (CC):"),
01013                     mLblCc, mEdtCc, mBtnCc,
01014                     i18n("Additional Recipients"),
01015                     i18n("<qt>The email addresses you put "
01016                          "in this field receive a copy of the email. "
01017                          "Technically it is the same thing as putting all the "
01018                          "addresses in the <b>To:</b> field but differs in "
01019                          "that it usually symbolises the receiver of the "
01020                          "Carbon Copy (CC) is a listener, not the main "
01021                          "recipient.</qt>"));
01022     if ( showHeaders & HDR_CC ) {
01023       prevFocus = connectFocusMoving( prevFocus, mEdtCc );
01024     }
01025 
01026     if (!fromSlot) mBccAction->setChecked(abs(mShowHeaders)&HDR_BCC);
01027     rethinkHeaderLine(showHeaders,HDR_BCC, row, i18n("&Blind copy to (BCC):"),
01028                     mLblBcc, mEdtBcc, mBtnBcc,
01029                     i18n("Hidden Recipients"),
01030                     i18n("<qt>Essentially the same thing "
01031                          "as the <b>Copy To:</b> field but differs in that "
01032                          "all other recipients do not see who receives a "
01033                          "blind copy.</qt>"));
01034     if ( showHeaders & HDR_BCC ) {
01035       prevFocus = connectFocusMoving( prevFocus, mEdtBcc );
01036     }
01037   } else {
01038     mGrid->addMultiCellWidget( mRecipientsEditor, row, row, 0, 2 );
01039     ++row;
01040 
01041     if ( showHeaders & HDR_REPLY_TO ) {
01042       connect( mEdtReplyTo, SIGNAL( focusDown() ), mRecipientsEditor,
01043         SLOT( setFocusTop() ) );
01044     } else {
01045     connect( mEdtFrom, SIGNAL( focusDown() ), mRecipientsEditor,
01046       SLOT( setFocusTop() ) );
01047     }
01048     if ( showHeaders & HDR_REPLY_TO ) {
01049       connect( mRecipientsEditor, SIGNAL( focusUp() ), mEdtReplyTo, SLOT( setFocus() ) );
01050     } else {
01051       connect( mRecipientsEditor, SIGNAL( focusUp() ), mEdtFrom, SLOT( setFocus() ) );
01052     }
01053 
01054     connect( mRecipientsEditor, SIGNAL( focusDown() ), mEdtSubject,
01055       SLOT( setFocus() ) );
01056     connect( mEdtSubject, SIGNAL( focusUp() ), mRecipientsEditor,
01057       SLOT( setFocusBottom() ) );
01058 
01059     prevFocus = mRecipientsEditor;
01060   }
01061   if (!fromSlot) mSubjectAction->setChecked(abs(mShowHeaders)&HDR_SUBJECT);
01062   rethinkHeaderLine(showHeaders,HDR_SUBJECT, row, i18n("S&ubject:"),
01063                     mLblSubject, mEdtSubject);
01064   connectFocusMoving( mEdtSubject, mEditor );
01065 
01066   assert(row<=mNumHeaders);
01067 
01068 
01069   if( !mAtmList.isEmpty() )
01070     mAtmListView->show();
01071   else
01072     mAtmListView->hide();
01073   resize(this->size());
01074   repaint();
01075 
01076   mHeadersArea->setMaximumHeight( mHeadersArea->sizeHint().height() );
01077   mGrid->activate();
01078   mHeadersArea->show();
01079 
01080   slotUpdateAttachActions();
01081   mIdentityAction->setEnabled(!mAllFieldsAction->isChecked());
01082   mDictionaryAction->setEnabled( !mAllFieldsAction->isChecked() );
01083   mTransportAction->setEnabled(!mAllFieldsAction->isChecked());
01084   mFromAction->setEnabled(!mAllFieldsAction->isChecked());
01085   if ( mReplyToAction ) mReplyToAction->setEnabled(!mAllFieldsAction->isChecked());
01086   if ( mToAction ) mToAction->setEnabled(!mAllFieldsAction->isChecked());
01087   if ( mCcAction ) mCcAction->setEnabled(!mAllFieldsAction->isChecked());
01088   if ( mBccAction ) mBccAction->setEnabled(!mAllFieldsAction->isChecked());
01089   mFccAction->setEnabled(!mAllFieldsAction->isChecked());
01090   mSubjectAction->setEnabled(!mAllFieldsAction->isChecked());
01091   if (mRecipientsEditor)
01092     mRecipientsEditor->setFirstColumnWidth( mLabelWidth );
01093 }
01094 
01095 QWidget *KMComposeWin::connectFocusMoving( QWidget *prev, QWidget *next )
01096 {
01097   connect( prev, SIGNAL( focusDown() ), next, SLOT( setFocus() ) );
01098   connect( next, SIGNAL( focusUp() ), prev, SLOT( setFocus() ) );
01099 
01100   return next;
01101 }
01102 
01103 //-----------------------------------------------------------------------------
01104 void KMComposeWin::rethinkHeaderLine(int aValue, int aMask, int& aRow,
01105                                      const QString &aLabelStr, QLabel* aLbl,
01106                                      QLineEdit* aEdt, QPushButton* aBtn,
01107                                      const QString &toolTip, const QString &whatsThis )
01108 {
01109   if (aValue & aMask)
01110   {
01111     aLbl->setText(aLabelStr);
01112     if ( !toolTip.isEmpty() )
01113       QToolTip::add( aLbl, toolTip );
01114     if ( !whatsThis.isEmpty() )
01115       QWhatsThis::add( aLbl, whatsThis );
01116     aLbl->setFixedWidth( mLabelWidth );
01117     aLbl->setBuddy(aEdt);
01118     mGrid->addWidget(aLbl, aRow, 0);
01119     aEdt->setBackgroundColor( mBackColor );
01120     aEdt->show();
01121 
01122     if (aBtn) {
01123       mGrid->addWidget(aEdt, aRow, 1);
01124 
01125       mGrid->addWidget(aBtn, aRow, 2);
01126       aBtn->show();
01127     } else {
01128       mGrid->addMultiCellWidget(aEdt, aRow, aRow, 1, 2 );
01129     }
01130     aRow++;
01131   }
01132   else
01133   {
01134     aLbl->hide();
01135     aEdt->hide();
01136     if (aBtn) aBtn->hide();
01137   }
01138 }
01139 
01140 //-----------------------------------------------------------------------------
01141 void KMComposeWin::rethinkHeaderLine(int aValue, int aMask, int& aRow,
01142                                      const QString &aLabelStr, QLabel* aLbl,
01143                                      QComboBox* aCbx, QCheckBox* aChk)
01144 {
01145   if (aValue & aMask)
01146   {
01147     aLbl->setText(aLabelStr);
01148     aLbl->adjustSize();
01149     aLbl->resize((int)aLbl->sizeHint().width(),aLbl->sizeHint().height() + 6);
01150     aLbl->setMinimumSize(aLbl->size());
01151     aLbl->show();
01152     aLbl->setBuddy(aCbx);
01153     mGrid->addWidget(aLbl, aRow, 0);
01154     aCbx->show();
01155     aCbx->setMinimumSize(100, aLbl->height()+2);
01156 
01157     mGrid->addWidget(aCbx, aRow, 1);
01158     if ( aChk ) {
01159       mGrid->addWidget(aChk, aRow, 2);
01160       aChk->setFixedSize(aChk->sizeHint().width(), aLbl->height());
01161       aChk->show();
01162     }
01163     aRow++;
01164   }
01165   else
01166   {
01167     aLbl->hide();
01168     aCbx->hide();
01169     if ( aChk )
01170       aChk->hide();
01171   }
01172 }
01173 
01174 //-----------------------------------------------------------------------------
01175 void KMComposeWin::getTransportMenu()
01176 {
01177   QStringList availTransports;
01178 
01179   mActNowMenu->clear();
01180   mActLaterMenu->clear();
01181   availTransports = KMail::TransportManager::transportNames();
01182   QStringList::Iterator it;
01183   int id = 0;
01184   for(it = availTransports.begin(); it != availTransports.end() ; ++it, id++)
01185   {
01186     mActNowMenu->insertItem((*it).replace("&", "&&"), id);
01187     mActLaterMenu->insertItem((*it).replace("&", "&&"), id);
01188   }
01189 }
01190 
01191 
01192 //-----------------------------------------------------------------------------
01193 void KMComposeWin::setupActions(void)
01194 {
01195   KActionMenu *actActionNowMenu, *actActionLaterMenu;
01196 
01197   if (kmkernel->msgSender()->sendImmediate()) //default == send now?
01198   {
01199     //default = send now, alternative = queue
01200     ( void )  new KAction( i18n("&Send Mail"), "mail_send", CTRL+Key_Return,
01201                         this, SLOT(slotSendNow()), actionCollection(),"send_default");
01202 
01203     // FIXME: change to mail_send_via icon when this exits.
01204     actActionNowMenu =  new KActionMenu (i18n("&Send Mail Via"), "mail_send",
01205             actionCollection(), "send_default_via" );
01206 
01207     (void) new KAction (i18n("Send &Later"), "queue", 0, this,
01208             SLOT(slotSendLater()), actionCollection(),"send_alternative");
01209     actActionLaterMenu = new KActionMenu (i18n("Send &Later Via"), "queue",
01210             actionCollection(), "send_alternative_via" );
01211 
01212   }
01213   else //no, default = send later
01214   {
01215     //default = queue, alternative = send now
01216     (void) new KAction (i18n("Send &Later"), "queue",
01217                         CTRL+Key_Return,
01218                         this, SLOT(slotSendLater()), actionCollection(),"send_default");
01219     actActionLaterMenu = new KActionMenu (i18n("Send &Later Via"), "queue",
01220             actionCollection(), "send_default_via" );
01221 
01222    ( void )  new KAction( i18n("&Send Mail"), "mail_send", 0,
01223                         this, SLOT(slotSendNow()), actionCollection(),"send_alternative");
01224 
01225     // FIXME: change to mail_send_via icon when this exits.
01226     actActionNowMenu =  new KActionMenu (i18n("&Send Mail Via"), "mail_send",
01227             actionCollection(), "send_alternative_via" );
01228 
01229   }
01230 
01231   // needed for sending "default transport"
01232   actActionNowMenu->setDelayed(true);
01233   actActionLaterMenu->setDelayed(true);
01234 
01235   connect(  actActionNowMenu, SIGNAL(  activated() ), this,
01236             SLOT( slotSendNow() ) );
01237   connect(  actActionLaterMenu, SIGNAL(  activated() ), this,
01238             SLOT( slotSendLater() ) );
01239 
01240 
01241   mActNowMenu = actActionNowMenu->popupMenu();
01242   mActLaterMenu = actActionLaterMenu->popupMenu();
01243 
01244   connect(  mActNowMenu, SIGNAL(  activated( int ) ), this,
01245             SLOT( slotSendNowVia( int ) ) );
01246   connect(  mActNowMenu, SIGNAL(  aboutToShow() ), this,
01247             SLOT( getTransportMenu() ) );
01248 
01249   connect(  mActLaterMenu, SIGNAL(  activated( int ) ), this,
01250           SLOT( slotSendLaterVia( int ) ) );
01251   connect(  mActLaterMenu, SIGNAL(  aboutToShow() ), this,
01252           SLOT( getTransportMenu() ) );
01253 
01254 
01255 
01256 
01257   (void) new KAction (i18n("Save as &Draft"), "filesave", 0,
01258                       this, SLOT(slotSaveDraft()),
01259                       actionCollection(), "save_in_drafts");
01260   (void) new KAction (i18n("Save as &Template"), "filesave", 0,
01261                       this, SLOT(slotSaveTemplate()),
01262                       actionCollection(), "save_in_templates");
01263   (void) new KAction (i18n("&Insert File..."), "fileopen", 0,
01264                       this,  SLOT(slotInsertFile()),
01265                       actionCollection(), "insert_file");
01266   mRecentAction = new KRecentFilesAction (i18n("&Insert File Recent"),
01267               "fileopen", 0,
01268               this,  SLOT(slotInsertRecentFile(const KURL&)),
01269               actionCollection(), "insert_file_recent");
01270 
01271   mRecentAction->loadEntries( KMKernel::config() );
01272 
01273   (void) new KAction (i18n("&Address Book"), "contents",0,
01274                       this, SLOT(slotAddrBook()),
01275                       actionCollection(), "addressbook");
01276   (void) new KAction (i18n("&New Composer"), "mail_new",
01277                       KStdAccel::shortcut(KStdAccel::New),
01278                       this, SLOT(slotNewComposer()),
01279                       actionCollection(), "new_composer");
01280   (void) new KAction (i18n("New Main &Window"), "window_new", 0,
01281                       this, SLOT(slotNewMailReader()),
01282                       actionCollection(), "open_mailreader");
01283 
01284   if ( !mClassicalRecipients ) {
01285     new KAction( i18n("Select &Recipients..."), CTRL + Key_L, mRecipientsEditor,
01286       SLOT( selectRecipients() ), actionCollection(), "select_recipients" );
01287     new KAction( i18n("Save &Distribution List..."), 0, mRecipientsEditor,
01288       SLOT( saveDistributionList() ), actionCollection(),
01289       "save_distribution_list" );
01290   }
01291 
01292   //KStdAction::save(this, SLOT(), actionCollection(), "save_message");
01293   KStdAction::print (this, SLOT(slotPrint()), actionCollection());
01294   KStdAction::close (this, SLOT(slotClose()), actionCollection());
01295 
01296   KStdAction::undo (this, SLOT(slotUndo()), actionCollection());
01297   KStdAction::redo (this, SLOT(slotRedo()), actionCollection());
01298   KStdAction::cut (this, SLOT(slotCut()), actionCollection());
01299   KStdAction::copy (this, SLOT(slotCopy()), actionCollection());
01300   KStdAction::pasteText (this, SLOT(slotPasteClipboard()), actionCollection());
01301   KStdAction::selectAll (this, SLOT(slotMarkAll()), actionCollection());
01302 
01303   KStdAction::find (this, SLOT(slotFind()), actionCollection());
01304   KStdAction::findNext(this, SLOT(slotSearchAgain()), actionCollection());
01305 
01306   KStdAction::replace (this, SLOT(slotReplace()), actionCollection());
01307   KStdAction::spelling (this, SLOT(slotSpellcheck()), actionCollection(), "spellcheck");
01308 
01309   mPasteQuotation = new KAction (i18n("Pa&ste as Quotation"),0,this,SLOT( slotPasteClipboardAsQuotation()),
01310                       actionCollection(), "paste_quoted");
01311 
01312   (void) new KAction (i18n("Paste as Attac&hment"),0,this,SLOT( slotPasteClipboardAsAttachment()),
01313                       actionCollection(), "paste_att");
01314 
01315   KAction * addq = new KAction(i18n("Add &Quote Characters"), 0, this,
01316               SLOT(slotAddQuotes()), actionCollection(), "tools_quote");
01317   connect( mEditor, SIGNAL(selectionAvailable(bool)),
01318            addq, SLOT(setEnabled(bool)) );
01319 
01320   KAction * remq = new KAction(i18n("Re&move Quote Characters"), 0, this,
01321               SLOT(slotRemoveQuotes()), actionCollection(), "tools_unquote");
01322   connect( mEditor, SIGNAL(selectionAvailable(bool)),
01323            remq, SLOT(setEnabled(bool)) );
01324 
01325 
01326   (void) new KAction (i18n("Cl&ean Spaces"), 0, this, SLOT(slotCleanSpace()),
01327                       actionCollection(), "clean_spaces");
01328 
01329   mFixedFontAction = new KToggleAction( i18n("Use Fi&xed Font"), 0, this,
01330                       SLOT(slotUpdateFont()), actionCollection(), "toggle_fixedfont" );
01331   mFixedFontAction->setChecked( GlobalSettings::self()->useFixedFont() );
01332 
01333   //these are checkable!!!
01334   mUrgentAction = new KToggleAction (i18n("&Urgent"), 0,
01335                                     actionCollection(),
01336                                     "urgent");
01337   mRequestMDNAction = new KToggleAction ( i18n("&Request Disposition Notification"), 0,
01338                                          actionCollection(),
01339                                          "options_request_mdn");
01340   mRequestMDNAction->setChecked(GlobalSettings::self()->requestMDN());
01341   //----- Message-Encoding Submenu
01342   mEncodingAction = new KSelectAction( i18n( "Se&t Encoding" ), "charset",
01343                                       0, this, SLOT(slotSetCharset() ),
01344                                       actionCollection(), "charsets" );
01345   mWordWrapAction = new KToggleAction (i18n("&Wordwrap"), 0,
01346                       actionCollection(), "wordwrap");
01347   mWordWrapAction->setChecked(GlobalSettings::self()->wordWrap());
01348   connect(mWordWrapAction, SIGNAL(toggled(bool)), SLOT(slotWordWrapToggled(bool)));
01349 
01350   mSnippetAction = new KToggleAction ( i18n("&Snippets"), 0,
01351                                        actionCollection(), "snippets");
01352   connect(mSnippetAction, SIGNAL(toggled(bool)), mSnippetWidget, SLOT(setShown(bool)) );
01353   mSnippetAction->setChecked( GlobalSettings::self()->showSnippetManager() );
01354 
01355   mAutoSpellCheckingAction =
01356     new KToggleAction( i18n( "&Automatic Spellchecking" ), "spellcheck", 0,
01357                        actionCollection(), "options_auto_spellchecking" );
01358   const bool spellChecking = GlobalSettings::self()->autoSpellChecking();
01359   mAutoSpellCheckingAction->setEnabled( !GlobalSettings::self()->useExternalEditor() );
01360   mAutoSpellCheckingAction->setChecked( !GlobalSettings::self()->useExternalEditor() && spellChecking );
01361   slotAutoSpellCheckingToggled( !GlobalSettings::self()->useExternalEditor() && spellChecking );
01362   connect( mAutoSpellCheckingAction, SIGNAL( toggled( bool ) ),
01363            this, SLOT( slotAutoSpellCheckingToggled( bool ) ) );
01364 
01365   QStringList encodings = KMMsgBase::supportedEncodings(true);
01366   encodings.prepend( i18n("Auto-Detect"));
01367   mEncodingAction->setItems( encodings );
01368   mEncodingAction->setCurrentItem( -1 );
01369 
01370   //these are checkable!!!
01371   markupAction = new KToggleAction (i18n("Formatting (HTML)"), 0, this,
01372                                     SLOT(slotToggleMarkup()),
01373                       actionCollection(), "html");
01374 
01375   mAllFieldsAction = new KToggleAction (i18n("&All Fields"), 0, this,
01376                                        SLOT(slotView()),
01377                                        actionCollection(), "show_all_fields");
01378   mIdentityAction = new KToggleAction (i18n("&Identity"), 0, this,
01379                                       SLOT(slotView()),
01380                                       actionCollection(), "show_identity");
01381   mDictionaryAction = new KToggleAction (i18n("&Dictionary"), 0, this,
01382                                          SLOT(slotView()),
01383                                          actionCollection(), "show_dictionary");
01384   mFccAction = new KToggleAction (i18n("&Sent-Mail Folder"), 0, this,
01385                                  SLOT(slotView()),
01386                                  actionCollection(), "show_fcc");
01387   mTransportAction = new KToggleAction (i18n("&Mail Transport"), 0, this,
01388                                       SLOT(slotView()),
01389                                       actionCollection(), "show_transport");
01390   mFromAction = new KToggleAction (i18n("&From"), 0, this,
01391                                   SLOT(slotView()),
01392                                   actionCollection(), "show_from");
01393   mReplyToAction = new KToggleAction (i18n("&Reply To"), 0, this,
01394                                        SLOT(slotView()),
01395                                        actionCollection(), "show_reply_to");
01396   if ( mClassicalRecipients ) {
01397     mToAction = new KToggleAction (i18n("&To"), 0, this,
01398                                   SLOT(slotView()),
01399                                   actionCollection(), "show_to");
01400     mCcAction = new KToggleAction (i18n("&CC"), 0, this,
01401                                   SLOT(slotView()),
01402                                   actionCollection(), "show_cc");
01403     mBccAction = new KToggleAction (i18n("&BCC"), 0, this,
01404                                    SLOT(slotView()),
01405                                    actionCollection(), "show_bcc");
01406   }
01407   mSubjectAction = new KToggleAction (i18n("S&ubject"), 0, this,
01408                                      SLOT(slotView()),
01409                                      actionCollection(), "show_subject");
01410   //end of checkable
01411 
01412   mAppendSignatureAction = new KAction (i18n("Append S&ignature"), 0, this,
01413                       SLOT(slotAppendSignature()),
01414                       actionCollection(), "append_signature");
01415   mPrependSignatureAction =  new KAction (i18n("Prepend S&ignature"), 0, this,
01416                       SLOT(slotPrependSignature()),
01417                       actionCollection(), "prepend_signature");
01418 
01419   mInsertSignatureAction =  new KAction (i18n("Insert Signature At C&ursor Position"), "edit", 0, this,
01420                       SLOT(slotInsertSignatureAtCursor()),
01421                       actionCollection(), "insert_signature_at_cursor_position");
01422 
01423   mAttachPK  = new KAction (i18n("Attach &Public Key..."), 0, this,
01424                            SLOT(slotInsertPublicKey()),
01425                            actionCollection(), "attach_public_key");
01426   mAttachMPK = new KAction (i18n("Attach &My Public Key"), 0, this,
01427                            SLOT(slotInsertMyPublicKey()),
01428                            actionCollection(), "attach_my_public_key");
01429   (void) new KAction (i18n("&Attach File..."), "attach",
01430                       0, this, SLOT(slotAttachFile()),
01431                       actionCollection(), "attach");
01432   mAttachRemoveAction = new KAction (i18n("&Remove Attachment"), 0, this,
01433                       SLOT(slotAttachRemove()),
01434                       actionCollection(), "remove");
01435   mAttachSaveAction = new KAction (i18n("&Save Attachment As..."), "filesave",0,
01436                       this, SLOT(slotAttachSave()),
01437                       actionCollection(), "attach_save");
01438   mAttachPropertiesAction = new KAction (i18n("Attachment Pr&operties"), 0, this,
01439                       SLOT(slotAttachProperties()),
01440                       actionCollection(), "attach_properties");
01441 
01442   setStandardToolBarMenuEnabled(true);
01443 
01444   KStdAction::keyBindings(this, SLOT(slotEditKeys()), actionCollection());
01445   KStdAction::configureToolbars(this, SLOT(slotEditToolbars()), actionCollection());
01446   KStdAction::preferences(kmkernel, SLOT(slotShowConfigurationDialog()), actionCollection());
01447 
01448   (void) new KAction (i18n("&Spellchecker..."), 0, this, SLOT(slotSpellcheckConfig()),
01449                       actionCollection(), "setup_spellchecker");
01450 
01451   if ( Kleo::CryptoBackendFactory::instance()->protocol( "Chiasmus" ) ) {
01452     KToggleAction * a = new KToggleAction( i18n( "Encrypt Message with Chiasmus..." ),
01453                                            "chidecrypted", 0, actionCollection(),
01454                                            "encrypt_message_chiasmus" );
01455     a->setCheckedState( KGuiItem( i18n( "Encrypt Message with Chiasmus..." ), "chiencrypted" ) );
01456     mEncryptChiasmusAction = a;
01457     connect( mEncryptChiasmusAction, SIGNAL(toggled(bool)),
01458              this, SLOT(slotEncryptChiasmusToggled(bool)) );
01459   } else {
01460     mEncryptChiasmusAction = 0;
01461   }
01462 
01463   mEncryptAction = new KToggleAction (i18n("&Encrypt Message"),
01464                                      "decrypted", 0,
01465                                      actionCollection(), "encrypt_message");
01466   mSignAction = new KToggleAction (i18n("&Sign Message"),
01467                                   "signature", 0,
01468                                   actionCollection(), "sign_message");
01469   // get PGP user id for the chosen identity
01470   const KPIM::Identity & ident =
01471     kmkernel->identityManager()->identityForUoidOrDefault( mIdentity->currentIdentity() );
01472   // PENDING(marc): check the uses of this member and split it into
01473   // smime/openpgp and or enc/sign, if necessary:
01474   mLastIdentityHasSigningKey = !ident.pgpSigningKey().isEmpty() || !ident.smimeSigningKey().isEmpty();
01475   mLastIdentityHasEncryptionKey = !ident.pgpEncryptionKey().isEmpty() || !ident.smimeEncryptionKey().isEmpty();
01476 
01477   mLastEncryptActionState = false;
01478   mLastSignActionState = GlobalSettings::self()->pgpAutoSign();
01479 
01480   // "Attach public key" is only possible if OpenPGP support is available:
01481   mAttachPK->setEnabled( Kleo::CryptoBackendFactory::instance()->openpgp() );
01482 
01483   // "Attach my public key" is only possible if OpenPGP support is
01484   // available and the user specified his key for the current identity:
01485   mAttachMPK->setEnabled( Kleo::CryptoBackendFactory::instance()->openpgp() &&
01486               !ident.pgpEncryptionKey().isEmpty() );
01487 
01488   if ( !Kleo::CryptoBackendFactory::instance()->openpgp() && !Kleo::CryptoBackendFactory::instance()->smime() ) {
01489     // no crypto whatsoever
01490     mEncryptAction->setEnabled( false );
01491     setEncryption( false );
01492     mSignAction->setEnabled( false );
01493     setSigning( false );
01494   } else {
01495     const bool canOpenPGPSign = Kleo::CryptoBackendFactory::instance()->openpgp()
01496       && !ident.pgpSigningKey().isEmpty();
01497     const bool canSMIMESign = Kleo::CryptoBackendFactory::instance()->smime()
01498       && !ident.smimeSigningKey().isEmpty();
01499 
01500     setEncryption( false );
01501     setSigning( ( canOpenPGPSign || canSMIMESign ) && GlobalSettings::self()->pgpAutoSign() );
01502   }
01503 
01504   connect(mEncryptAction, SIGNAL(toggled(bool)),
01505                          SLOT(slotEncryptToggled( bool )));
01506   connect(mSignAction,    SIGNAL(toggled(bool)),
01507                          SLOT(slotSignToggled(    bool )));
01508 
01509   QStringList l;
01510   for ( int i = 0 ; i < numCryptoMessageFormats ; ++i )
01511     l.push_back( Kleo::cryptoMessageFormatToLabel( cryptoMessageFormats[i] ) );
01512 
01513   mCryptoModuleAction = new KSelectAction( i18n( "&Cryptographic Message Format" ), 0,
01514                        this, SLOT(slotSelectCryptoModule()),
01515                        actionCollection(), "options_select_crypto" );
01516   mCryptoModuleAction->setItems( l );
01517   mCryptoModuleAction->setCurrentItem( format2cb( ident.preferredCryptoMessageFormat() ) );
01518   slotSelectCryptoModule( true /* initialize */ );
01519 
01520   QStringList styleItems;
01521   styleItems << i18n( "Standard" );
01522   styleItems << i18n( "Bulleted List (Disc)" );
01523   styleItems << i18n( "Bulleted List (Circle)" );
01524   styleItems << i18n( "Bulleted List (Square)" );
01525   styleItems << i18n( "Ordered List (Decimal)" );
01526   styleItems << i18n( "Ordered List (Alpha lower)" );
01527   styleItems << i18n( "Ordered List (Alpha upper)" );
01528 
01529   listAction = new KSelectAction( i18n( "Select Style" ), 0, actionCollection(),
01530                                  "text_list" );
01531   listAction->setItems( styleItems );
01532   connect( listAction, SIGNAL( activated( const QString& ) ),
01533            SLOT( slotListAction( const QString& ) ) );
01534   fontAction = new KFontAction( "Select Font", 0, actionCollection(),
01535                                "text_font" );
01536   connect( fontAction, SIGNAL( activated( const QString& ) ),
01537            SLOT( slotFontAction( const QString& ) ) );
01538   fontSizeAction = new KFontSizeAction( "Select Size", 0, actionCollection(),
01539                                        "text_size" );
01540   connect( fontSizeAction, SIGNAL( fontSizeChanged( int ) ),
01541            SLOT( slotSizeAction( int ) ) );
01542 
01543   alignLeftAction = new KToggleAction (i18n("Align Left"), "text_left", 0,
01544                       this, SLOT(slotAlignLeft()), actionCollection(),
01545                       "align_left");
01546   alignLeftAction->setChecked( true );
01547   alignRightAction = new KToggleAction (i18n("Align Right"), "text_right", 0,
01548                       this, SLOT(slotAlignRight()), actionCollection(),
01549                       "align_right");
01550   alignCenterAction = new KToggleAction (i18n("Align Center"), "text_center", 0,
01551                        this, SLOT(slotAlignCenter()), actionCollection(),
01552                        "align_center");
01553   textBoldAction = new KToggleAction( i18n("&Bold"), "text_bold", CTRL+Key_B,
01554                                      this, SLOT(slotTextBold()),
01555                                      actionCollection(), "text_bold");
01556   textItalicAction = new KToggleAction( i18n("&Italic"), "text_italic", CTRL+Key_I,
01557                                        this, SLOT(slotTextItalic()),
01558                                        actionCollection(), "text_italic");
01559   textUnderAction = new KToggleAction( i18n("&Underline"), "text_under", CTRL+Key_U,
01560                                      this, SLOT(slotTextUnder()),
01561                                      actionCollection(), "text_under");
01562   actionFormatReset = new KAction( i18n( "Reset Font Settings" ), "eraser", 0,
01563                                      this, SLOT( slotFormatReset() ),
01564                                      actionCollection(), "format_reset");
01565   actionFormatColor = new KAction( i18n( "Text Color..." ), "colorize", 0,
01566                                      this, SLOT( slotTextColor() ),
01567                                      actionCollection(), "format_color");
01568 
01569   //  editorFocusChanged(false);
01570   createGUI("kmcomposerui.rc");
01571 
01572   connect( toolBar("htmlToolBar"), SIGNAL( visibilityChanged(bool) ),
01573            this, SLOT( htmlToolBarVisibilityChanged(bool) ) );
01574 
01575   // In Kontact, this entry would read "Configure Kontact", but bring
01576   // up KMail's config dialog. That's sensible, though, so fix the label.
01577   KAction* configureAction = actionCollection()->action("options_configure" );
01578   if ( configureAction )
01579     configureAction->setText( i18n("Configure KMail..." ) );
01580 }
01581 
01582 //-----------------------------------------------------------------------------
01583 void KMComposeWin::setupStatusBar(void)
01584 {
01585   statusBar()->insertItem("", 0, 1);
01586   statusBar()->setItemAlignment(0, AlignLeft | AlignVCenter);
01587 
01588   statusBar()->insertItem(i18n( " Spellcheck: %1 ").arg( "   " ), 3, 0, true );
01589   statusBar()->insertItem(i18n( " Column: %1 ").arg("     "), 2, 0, true);
01590   statusBar()->insertItem(i18n( " Line: %1 ").arg("     "), 1, 0, true);
01591 }
01592 
01593 
01594 //-----------------------------------------------------------------------------
01595 void KMComposeWin::updateCursorPosition()
01596 {
01597   int col,line;
01598   QString temp;
01599   line = mEditor->currentLine();
01600   col = mEditor->currentColumn();
01601   temp = i18n(" Line: %1 ").arg(line+1);
01602   statusBar()->changeItem(temp,1);
01603   temp = i18n(" Column: %1 ").arg(col+1);
01604   statusBar()->changeItem(temp,2);
01605 }
01606 
01607 
01608 //-----------------------------------------------------------------------------
01609 void KMComposeWin::setupEditor(void)
01610 {
01611   //QPopupMenu* menu;
01612   mEditor->setModified(false);
01613   QFontMetrics fm(mBodyFont);
01614   mEditor->setTabStopWidth(fm.width(QChar(' ')) * 8);
01615   //mEditor->setFocusPolicy(QWidget::ClickFocus);
01616 
01617   slotWordWrapToggled( GlobalSettings::self()->wordWrap() );
01618 
01619   // Font setup
01620   slotUpdateFont();
01621 
01622   /* installRBPopup() is broken in kdelibs, we should wait for
01623           the new klibtextedit (dnaber, 2002-01-01)
01624   menu = new QPopupMenu(this);
01625   //#ifdef BROKEN
01626   menu->insertItem(i18n("Undo"),mEditor,
01627                    SLOT(undo()), KStdAccel::shortcut(KStdAccel::Undo));
01628   menu->insertItem(i18n("Redo"),mEditor,
01629                    SLOT(redo()), KStdAccel::shortcut(KStdAccel::Redo));
01630   menu->insertSeparator();
01631   //#endif //BROKEN
01632   menu->insertItem(i18n("Cut"), this, SLOT(slotCut()));
01633   menu->insertItem(i18n("Copy"), this, SLOT(slotCopy()));
01634   menu->insertItem(i18n("Paste"), this, SLOT(slotPasteClipboard()));
01635   menu->insertItem(i18n("Mark All"),this, SLOT(slotMarkAll()));
01636   menu->insertSeparator();
01637   menu->insertItem(i18n("Find..."), this, SLOT(slotFind()));
01638   menu->insertItem(i18n("Replace..."), this, SLOT(slotReplace()));
01639   menu->insertSeparator();
01640   menu->insertItem(i18n("Fixed Font Widths"), this, SLOT(slotUpdateFont()));
01641   mEditor->installRBPopup(menu);
01642   */
01643   updateCursorPosition();
01644   connect(mEditor,SIGNAL(CursorPositionChanged()),SLOT(updateCursorPosition()));
01645   connect( mEditor, SIGNAL( currentFontChanged( const QFont & ) ),
01646           this, SLOT( fontChanged( const QFont & ) ) );
01647   connect( mEditor, SIGNAL( currentAlignmentChanged( int ) ),
01648           this, SLOT( alignmentChanged( int ) ) );
01649 
01650 }
01651 
01652 
01653 //-----------------------------------------------------------------------------
01654 static QString cleanedUpHeaderString( const QString & s )
01655 {
01656   // remove invalid characters from the header strings
01657   QString res( s );
01658   res.replace( '\r', "" );
01659   res.replace( '\n', " " );
01660   return res.stripWhiteSpace();
01661 }
01662 
01663 //-----------------------------------------------------------------------------
01664 QString KMComposeWin::subject() const
01665 {
01666   return cleanedUpHeaderString( mEdtSubject->text() );
01667 }
01668 
01669 //-----------------------------------------------------------------------------
01670 QString KMComposeWin::to() const
01671 {
01672   if ( mEdtTo ) {
01673     return cleanedUpHeaderString( mEdtTo->text() );
01674   } else if ( mRecipientsEditor ) {
01675     return mRecipientsEditor->recipientString( Recipient::To );
01676   } else {
01677     return QString::null;
01678   }
01679 }
01680 
01681 //-----------------------------------------------------------------------------
01682 QString KMComposeWin::cc() const
01683 {
01684   if ( mEdtCc && !mEdtCc->isHidden() ) {
01685     return cleanedUpHeaderString( mEdtCc->text() );
01686   } else if ( mRecipientsEditor ) {
01687     return mRecipientsEditor->recipientString( Recipient::Cc );
01688   } else {
01689     return QString::null;
01690   }
01691 }
01692 
01693 //-----------------------------------------------------------------------------
01694 QString KMComposeWin::bcc() const
01695 {
01696   if ( mEdtBcc && !mEdtBcc->isHidden() ) {
01697     return cleanedUpHeaderString( mEdtBcc->text() );
01698   } else if ( mRecipientsEditor ) {
01699     return mRecipientsEditor->recipientString( Recipient::Bcc );
01700   } else {
01701     return QString::null;
01702   }
01703 }
01704 
01705 //-----------------------------------------------------------------------------
01706 QString KMComposeWin::from() const
01707 {
01708   return cleanedUpHeaderString( mEdtFrom->text() );
01709 }
01710 
01711 //-----------------------------------------------------------------------------
01712 QString KMComposeWin::replyTo() const
01713 {
01714   if ( mEdtReplyTo ) {
01715     return cleanedUpHeaderString( mEdtReplyTo->text() );
01716   } else {
01717     return QString::null;
01718   }
01719 }
01720 
01721 //-----------------------------------------------------------------------------
01722 void KMComposeWin::verifyWordWrapLengthIsAdequate(const QString &body)
01723 {
01724   int maxLineLength = 0;
01725   int curPos;
01726   int oldPos = 0;
01727   if (mEditor->QTextEdit::wordWrap() == QTextEdit::FixedColumnWidth) {
01728     for (curPos = 0; curPos < (int)body.length(); ++curPos)
01729         if (body[curPos] == '\n') {
01730           if ((curPos - oldPos) > maxLineLength)
01731             maxLineLength = curPos - oldPos;
01732           oldPos = curPos;
01733         }
01734     if ((curPos - oldPos) > maxLineLength)
01735       maxLineLength = curPos - oldPos;
01736     if (mEditor->wrapColumnOrWidth() < maxLineLength) // column
01737       mEditor->setWrapColumnOrWidth(maxLineLength);
01738   }
01739 }
01740 
01741 //-----------------------------------------------------------------------------
01742 void KMComposeWin::decryptOrStripOffCleartextSignature( QCString& body )
01743 {
01744   QPtrList<Kpgp::Block> pgpBlocks;
01745   QStrList nonPgpBlocks;
01746   if( Kpgp::Module::prepareMessageForDecryption( body,
01747                                                  pgpBlocks, nonPgpBlocks ) )
01748   {
01749     // Only decrypt/strip off the signature if there is only one OpenPGP
01750     // block in the message
01751     if( pgpBlocks.count() == 1 )
01752     {
01753       Kpgp::Block* block = pgpBlocks.first();
01754       if( ( block->type() == Kpgp::PgpMessageBlock ) ||
01755           ( block->type() == Kpgp::ClearsignedBlock ) )
01756       {
01757         if( block->type() == Kpgp::PgpMessageBlock )
01758           // try to decrypt this OpenPGP block
01759           block->decrypt();
01760         else
01761           // strip off the signature
01762           block->verify();
01763 
01764         body = nonPgpBlocks.first()
01765              + block->text()
01766              + nonPgpBlocks.last();
01767       }
01768     }
01769   }
01770 }
01771 
01772 //-----------------------------------------------------------------------------
01773 void KMComposeWin::setTransport( const QString & transport )
01774 {
01775   kdDebug(5006) << "KMComposeWin::setTransport( \"" << transport << "\" )" << endl;
01776   // Don't change the transport combobox if transport is empty
01777   if ( transport.isEmpty() )
01778     return;
01779 
01780   bool transportFound = false;
01781   for ( int i = 0; i < mTransport->count(); ++i ) {
01782     if ( mTransport->text(i) == transport ) {
01783       transportFound = true;
01784       mTransport->setCurrentItem(i);
01785       kdDebug(5006) << "transport found, it's no. " << i << " in the list" << endl;
01786       break;
01787     }
01788   }
01789   if ( !transportFound ) { // unknown transport
01790     kdDebug(5006) << "unknown transport \"" << transport << "\"" << endl;
01791     if ( transport.startsWith("smtp://") || transport.startsWith("smtps://") ||
01792          transport.startsWith("file://") ) {
01793       // set custom transport
01794       mTransport->setEditText( transport );
01795     }
01796     else {
01797       // neither known nor custom transport -> use default transport
01798       mTransport->setCurrentText( GlobalSettings::self()->defaultTransport() );
01799     }
01800   }
01801 }
01802 
01803 //-----------------------------------------------------------------------------
01804 void KMComposeWin::setMsg(KMMessage* newMsg, bool mayAutoSign,
01805                           bool allowDecryption, bool isModified)
01806 {
01807   //assert(newMsg!=0);
01808   if(!newMsg)
01809     {
01810       kdDebug(5006) << "KMComposeWin::setMsg() : newMsg == 0!" << endl;
01811       return;
01812     }
01813   mMsg = newMsg;
01814   KPIM::IdentityManager * im = kmkernel->identityManager();
01815 
01816   mEdtFrom->setText(mMsg->from());
01817   mEdtReplyTo->setText(mMsg->replyTo());
01818   if ( mClassicalRecipients ) {
01819     mEdtTo->setText(mMsg->to());
01820     mEdtCc->setText(mMsg->cc());
01821     mEdtBcc->setText(mMsg->bcc());
01822   } else {
01823     mRecipientsEditor->setRecipientString( mMsg->to(), Recipient::To );
01824     mRecipientsEditor->setRecipientString( mMsg->cc(), Recipient::Cc );
01825     mRecipientsEditor->setRecipientString( mMsg->bcc(), Recipient::Bcc );
01826     mRecipientsEditor->setFocusBottom();
01827   }
01828   mEdtSubject->setText(mMsg->subject());
01829 
01830   const bool stickyIdentity = mBtnIdentity->isChecked();
01831   const bool messageHasIdentity = !newMsg->headerField("X-KMail-Identity").isEmpty();
01832   if (!stickyIdentity && messageHasIdentity)
01833     mId = newMsg->headerField("X-KMail-Identity").stripWhiteSpace().toUInt();
01834 
01835   // don't overwrite the header values with identity specific values
01836   // unless the identity is sticky
01837   if ( !stickyIdentity ) {
01838     disconnect(mIdentity,SIGNAL(identityChanged(uint)),
01839                this, SLOT(slotIdentityChanged(uint)));
01840   }
01841   // load the mId into the gui, sticky or not, without emitting
01842   mIdentity->setCurrentIdentity( mId );
01843   const uint idToApply = mId;
01844   if ( !stickyIdentity ) {
01845     connect(mIdentity,SIGNAL(identityChanged(uint)),
01846             this, SLOT(slotIdentityChanged(uint)));
01847   }  else {
01848     // load the message's state into the mId, without applying it to the gui
01849     // that's so we can detect that the id changed (because a sticky was set)
01850     // on apply()
01851     if ( messageHasIdentity )
01852       mId = newMsg->headerField("X-KMail-Identity").stripWhiteSpace().toUInt();
01853     else
01854       mId = im->defaultIdentity().uoid();
01855   }
01856   // manually load the identity's value into the fields; either the one from the
01857   // messge, where appropriate, or the one from the sticky identity. What's in
01858   // mId might have changed meanwhile, thus the save value
01859   slotIdentityChanged( idToApply );
01860 
01861   const KPIM::Identity & ident = im->identityForUoid( mIdentity->currentIdentity() );
01862 
01863   // check for the presence of a DNT header, indicating that MDN's were
01864   // requested
01865   QString mdnAddr = newMsg->headerField("Disposition-Notification-To");
01866   mRequestMDNAction->setChecked( ( !mdnAddr.isEmpty() &&
01867                                   im->thatIsMe( mdnAddr ) ) ||
01868                                   GlobalSettings::self()->requestMDN() );
01869 
01870   // check for presence of a priority header, indicating urgent mail:
01871   mUrgentAction->setChecked( newMsg->isUrgent() );
01872 
01873   if (!ident.isXFaceEnabled() || ident.xface().isEmpty())
01874     mMsg->removeHeaderField("X-Face");
01875   else
01876   {
01877     QString xface = ident.xface();
01878     if (!xface.isEmpty())
01879     {
01880       int numNL = ( xface.length() - 1 ) / 70;
01881       for ( int i = numNL; i > 0; --i )
01882         xface.insert( i*70, "\n\t" );
01883       mMsg->setHeaderField("X-Face", xface);
01884     }
01885   }
01886 
01887   // enable/disable encryption if the message was/wasn't encrypted
01888   switch ( mMsg->encryptionState() ) {
01889     case KMMsgFullyEncrypted: // fall through
01890     case KMMsgPartiallyEncrypted:
01891       mLastEncryptActionState = true;
01892       break;
01893     case KMMsgNotEncrypted:
01894       mLastEncryptActionState = false;
01895       break;
01896     default: // nothing
01897       break;
01898   }
01899 
01900   // enable/disable signing if the message was/wasn't signed
01901   switch ( mMsg->signatureState() ) {
01902     case KMMsgFullySigned: // fall through
01903     case KMMsgPartiallySigned:
01904       mLastSignActionState = true;
01905       break;
01906     case KMMsgNotSigned:
01907       mLastSignActionState = false;
01908       break;
01909     default: // nothing
01910       break;
01911   }
01912 
01913   // if these headers are present, the state of the message should be overruled
01914   if ( mMsg->headers().FindField( "X-KMail-SignatureActionEnabled" ) )
01915     mLastSignActionState = (mMsg->headerField( "X-KMail-SignatureActionEnabled" ) == "true");
01916   if ( mMsg->headers().FindField( "X-KMail-EncryptActionEnabled" ) )
01917     mLastEncryptActionState = (mMsg->headerField( "X-KMail-EncryptActionEnabled" ) == "true");
01918   if ( mMsg->headers().FindField( "X-KMail-CryptoMessageFormat" ) )
01919     mCryptoModuleAction->setCurrentItem( format2cb( static_cast<Kleo::CryptoMessageFormat>(
01920                     mMsg->headerField( "X-KMail-CryptoMessageFormat" ).toInt() ) ) );
01921 
01922   mLastIdentityHasSigningKey = !ident.pgpSigningKey().isEmpty() || !ident.smimeSigningKey().isEmpty();
01923   mLastIdentityHasEncryptionKey = !ident.pgpEncryptionKey().isEmpty() || !ident.smimeEncryptionKey().isEmpty();
01924 
01925   if ( Kleo::CryptoBackendFactory::instance()->openpgp() || Kleo::CryptoBackendFactory::instance()->smime() ) {
01926     const bool canOpenPGPSign = Kleo::CryptoBackendFactory::instance()->openpgp()
01927       && !ident.pgpSigningKey().isEmpty();
01928     const bool canSMIMESign = Kleo::CryptoBackendFactory::instance()->smime()
01929       && !ident.smimeSigningKey().isEmpty();
01930 
01931     setEncryption( mLastEncryptActionState );
01932     setSigning( ( canOpenPGPSign || canSMIMESign ) && mLastSignActionState );
01933   }
01934   slotUpdateSignatureAndEncrypionStateIndicators();
01935 
01936   // "Attach my public key" is only possible if the user uses OpenPGP
01937   // support and he specified his key:
01938   mAttachMPK->setEnabled( Kleo::CryptoBackendFactory::instance()->openpgp() &&
01939               !ident.pgpEncryptionKey().isEmpty() );
01940 
01941   QString transport = newMsg->headerField("X-KMail-Transport");
01942   if (!mBtnTransport->isChecked() && !transport.isEmpty())
01943     setTransport( transport );
01944 
01945   if (!mBtnFcc->isChecked())
01946   {
01947     if (!mMsg->fcc().isEmpty())
01948       setFcc(mMsg->fcc());
01949     else
01950       setFcc(ident.fcc());
01951   }
01952 
01953   mDictionaryCombo->setCurrentByDictionary( ident.dictionary() );
01954 
01955   partNode * root = partNode::fromMessage( mMsg );
01956 
01957   KMail::ObjectTreeParser otp; // all defaults are ok
01958   otp.parseObjectTree( root );
01959 
01960   KMail::AttachmentCollector ac;
01961   ac.collectAttachmentsFrom( root );
01962 
01963   for ( std::vector<partNode*>::const_iterator it = ac.attachments().begin() ; it != ac.attachments().end() ; ++it )
01964     addAttach( new KMMessagePart( (*it)->msgPart() ) );
01965 
01966   mEditor->setText( otp.textualContent() );
01967   mCharset = otp.textualContentCharset();
01968   if ( partNode * n = root->findType( DwMime::kTypeText, DwMime::kSubtypeHtml ) )
01969     if ( partNode * p = n->parentNode() )
01970       if ( p->hasType( DwMime::kTypeMultipart ) &&
01971            p->hasSubType( DwMime::kSubtypeAlternative ) )
01972         if ( mMsg->headerField( "X-KMail-Markup" ) == "true" ) {
01973           toggleMarkup( true );
01974 
01975           // get cte decoded body part
01976           mCharset = n->msgPart().charset();
01977           QCString bodyDecoded = n->msgPart().bodyDecoded();
01978 
01979           // respect html part charset
01980           const QTextCodec *codec = KMMsgBase::codecForName( mCharset );
01981           if ( codec ) {
01982             mEditor->setText( codec->toUnicode( bodyDecoded ) );
01983           } else {
01984             mEditor->setText( QString::fromLocal8Bit( bodyDecoded ) );
01985           }
01986         }
01987 
01988   if ( mCharset.isEmpty() )
01989     mCharset = mMsg->charset();
01990   if ( mCharset.isEmpty() )
01991     mCharset = mDefCharset;
01992   setCharset( mCharset );
01993 
01994   /* Handle the special case of non-mime mails */
01995   if ( mMsg->numBodyParts() == 0 && otp.textualContent().isEmpty() ) {
01996     mCharset=mMsg->charset();
01997     if ( mCharset.isEmpty() ||  mCharset == "default" )
01998       mCharset = mDefCharset;
01999 
02000     QCString bodyDecoded = mMsg->bodyDecoded();
02001 
02002     if( allowDecryption )
02003       decryptOrStripOffCleartextSignature( bodyDecoded );
02004 
02005     const QTextCodec *codec = KMMsgBase::codecForName(mCharset);
02006     if (codec) {
02007       mEditor->setText(codec->toUnicode(bodyDecoded));
02008     } else
02009       mEditor->setText(QString::fromLocal8Bit(bodyDecoded));
02010   }
02011 #ifdef BROKEN_FOR_OPAQUE_SIGNED_OR_ENCRYPTED_MAILS
02012   const int num = mMsg->numBodyParts();
02013   kdDebug(5006) << "KMComposeWin::setMsg() mMsg->numBodyParts="
02014                 << mMsg->numBodyParts() << endl;
02015 
02016   if ( num > 0 ) {
02017     KMMessagePart bodyPart;
02018     int firstAttachment = 0;
02019 
02020     mMsg->bodyPart(1, &bodyPart);
02021     if ( bodyPart.typeStr().lower() == "text" &&
02022          bodyPart.subtypeStr().lower() == "html" ) {
02023       // check whether we are inside a mp/al body part
02024       partNode *root = partNode::fromMessage( mMsg );
02025       partNode *node = root->findType( DwMime::kTypeText,
02026                                        DwMime::kSubtypeHtml );
02027       if ( node && node->parentNode() &&
02028            node->parentNode()->hasType( DwMime::kTypeMultipart ) &&
02029            node->parentNode()->hasSubType( DwMime::kSubtypeAlternative ) ) {
02030         // we have a mp/al body part with a text and an html body
02031       kdDebug(5006) << "KMComposeWin::setMsg() : text/html found" << endl;
02032       firstAttachment = 2;
02033         if ( mMsg->headerField( "X-KMail-Markup" ) == "true" )
02034           toggleMarkup( true );
02035       }
02036       delete root; root = 0;
02037     }
02038     if ( firstAttachment == 0 ) {
02039         mMsg->bodyPart(0, &bodyPart);
02040         if ( bodyPart.typeStr().lower() == "text" ) {
02041           // we have a mp/mx body with a text body
02042         kdDebug(5006) << "KMComposeWin::setMsg() : text/* found" << endl;
02043           firstAttachment = 1;
02044         }
02045       }
02046 
02047     if ( firstAttachment != 0 ) // there's text to show
02048     {
02049       mCharset = bodyPart.charset();
02050       if ( mCharset.isEmpty() || mCharset == "default" )
02051         mCharset = mDefCharset;
02052 
02053       QCString bodyDecoded = bodyPart.bodyDecoded();
02054 
02055       if( allowDecryption )
02056         decryptOrStripOffCleartextSignature( bodyDecoded );
02057 
02058       // As nobody seems to know the purpose of the following line and
02059       // as it breaks word wrapping of long lines if drafts with attachments
02060       // are opened for editting in the composer (cf. Bug#41102) I comment it
02061       // out. Ingo, 2002-04-21
02062       //verifyWordWrapLengthIsAdequate(bodyDecoded);
02063 
02064       const QTextCodec *codec = KMMsgBase::codecForName(mCharset);
02065       if (codec)
02066         mEditor->setText(codec->toUnicode(bodyDecoded));
02067       else
02068         mEditor->setText(QString::fromLocal8Bit(bodyDecoded));
02069       //mEditor->insertLine("\n", -1); <-- why ?
02070     } else mEditor->setText("");
02071     for( int i = firstAttachment; i < num; ++i )
02072     {
02073       KMMessagePart *msgPart = new KMMessagePart;
02074       mMsg->bodyPart(i, msgPart);
02075       QCString mimeType = msgPart->typeStr().lower() + '/'
02076                         + msgPart->subtypeStr().lower();
02077       // don't add the detached signature as attachment when editting a
02078       // PGP/MIME signed message
02079       if( mimeType != "application/pgp-signature" ) {
02080         addAttach(msgPart);
02081       }
02082     }
02083   } else{
02084     mCharset=mMsg->charset();
02085     if ( mCharset.isEmpty() ||  mCharset == "default" )
02086       mCharset = mDefCharset;
02087 
02088     QCString bodyDecoded = mMsg->bodyDecoded();
02089 
02090     if( allowDecryption )
02091       decryptOrStripOffCleartextSignature( bodyDecoded );
02092 
02093     const QTextCodec *codec = KMMsgBase::codecForName(mCharset);
02094     if (codec) {
02095       mEditor->setText(codec->toUnicode(bodyDecoded));
02096     } else
02097       mEditor->setText(QString::fromLocal8Bit(bodyDecoded));
02098   }
02099 
02100   setCharset(mCharset);
02101 #endif // BROKEN_FOR_OPAQUE_SIGNED_OR_ENCRYPTED_MAILS
02102 
02103   if( (GlobalSettings::self()->autoTextSignature()=="auto") && mayAutoSign ) {
02104     //
02105     // Espen 2000-05-16
02106     // Delay the signature appending. It may start a fileseletor.
02107     // Not user friendy if this modal fileseletor opens before the
02108     // composer.
02109     //
02110     //QTimer::singleShot( 200, this, SLOT(slotAppendSignature()) );
02111       if ( GlobalSettings::self()->prependSignature() ) {
02112         QTimer::singleShot( 0, this, SLOT(slotPrependSignature()) );
02113       } else {
02114         QTimer::singleShot( 0, this, SLOT(slotAppendSignature()) );
02115       }
02116   }
02117 
02118   if ( mMsg->getCursorPos() > 0 ) {
02119     // The message has a cursor position explicitly set, so avoid
02120     // changing it when appending the signature.
02121     mPreserveUserCursorPosition = true;
02122   }
02123   setModified( isModified );
02124 
02125   // do this even for new messages
02126   mEditor->setCursorPositionFromStart( (unsigned int) mMsg->getCursorPos() );
02127 
02128   // honor "keep reply in this folder" setting even when the identity is changed later on
02129   mPreventFccOverwrite = ( !newMsg->fcc().isEmpty() && ident.fcc() != newMsg->fcc() );
02130 }
02131 
02132 
02133 //-----------------------------------------------------------------------------
02134 void KMComposeWin::setFcc( const QString &idString )
02135 {
02136   // check if the sent-mail folder still exists
02137   if ( ! idString.isEmpty() && kmkernel->findFolderById( idString ) ) {
02138     mFcc->setFolder( idString );
02139   } else {
02140     mFcc->setFolder( kmkernel->sentFolder() );
02141   }
02142 }
02143 
02144 
02145 //-----------------------------------------------------------------------------
02146 bool KMComposeWin::isModified() const
02147 {
02148   return ( mEditor->isModified() ||
02149            mEdtFrom->edited() ||
02150            ( mEdtReplyTo && mEdtReplyTo->edited() ) ||
02151            ( mEdtTo && mEdtTo->edited() ) ||
02152            ( mEdtCc && mEdtCc->edited() ) ||
02153            ( mEdtBcc && mEdtBcc->edited() ) ||
02154            ( mRecipientsEditor && mRecipientsEditor->isModified() ) ||
02155            mEdtSubject->edited() ||
02156            mAtmModified ||
02157            ( mTransport->lineEdit() && mTransport->lineEdit()->edited() ) );
02158 }
02159 
02160 
02161 //-----------------------------------------------------------------------------
02162 void KMComposeWin::setModified( bool modified )
02163 {
02164   mEditor->setModified( modified );
02165   if ( !modified ) {
02166     mEdtFrom->setEdited( false );
02167     if ( mEdtReplyTo ) mEdtReplyTo->setEdited( false );
02168     if ( mEdtTo ) mEdtTo->setEdited( false );
02169     if ( mEdtCc ) mEdtCc->setEdited( false );
02170     if ( mEdtBcc ) mEdtBcc->setEdited( false );
02171     if ( mRecipientsEditor ) mRecipientsEditor->clearModified();
02172     mEdtSubject->setEdited( false );
02173     mAtmModified =  false ;
02174     if ( mTransport->lineEdit() )
02175       mTransport->lineEdit()->setEdited( false );
02176   }
02177 }
02178 
02179 
02180 //-----------------------------------------------------------------------------
02181 bool KMComposeWin::queryClose ()
02182 {
02183   if ( !mEditor->checkExternalEditorFinished() )
02184     return false;
02185   if ( kmkernel->shuttingDown() || kapp->sessionSaving() )
02186     return true;
02187   if ( mComposer && mComposer->isPerformingSignOperation() ) // since the non-gpg-agent gpg plugin gets a passphrase using QDialog::exec()
02188     return false;                                            // the user can try to close the window, which destroys mComposer mid-call.
02189 
02190   if ( isModified() ) {
02191     bool istemplate = ( mFolder!=0 && mFolder->isTemplates() );
02192     const QString savebut = ( istemplate ?
02193                               i18n("Re&save as Template") :
02194                               i18n("&Save as Draft") );
02195     const QString savetext = ( istemplate ?
02196                                i18n("Resave this message in the Templates folder. "
02197                                     "It can then be used at a later time.") :
02198                                i18n("Save this message in the Drafts folder. "
02199                                     "It can then be edited and sent at a later time.") );
02200 
02201     const int rc = KMessageBox::warningYesNoCancel( this,
02202            i18n("Do you want to save the message for later or discard it?"),
02203            i18n("Close Composer"),
02204            KGuiItem(savebut, "filesave", QString::null, savetext),
02205            KStdGuiItem::discard() );
02206     if ( rc == KMessageBox::Cancel )
02207       return false;
02208     else if ( rc == KMessageBox::Yes ) {
02209       // doSend will close the window. Just return false from this method
02210       if ( istemplate ) {
02211         slotSaveTemplate();
02212       } else {
02213         slotSaveDraft();
02214       }
02215       return false;
02216     }
02217   }
02218   cleanupAutoSave();
02219   return true;
02220 }
02221 
02222 //-----------------------------------------------------------------------------
02223 bool KMComposeWin::userForgotAttachment()
02224 {
02225   bool checkForForgottenAttachments = GlobalSettings::self()->showForgottenAttachmentWarning();
02226 
02227   if ( !checkForForgottenAttachments || ( mAtmList.count() > 0 ) )
02228     return false;
02229 
02230 
02231   QStringList attachWordsList = GlobalSettings::self()->attachmentKeywords();
02232 
02233   if ( attachWordsList.isEmpty() ) {
02234     // default value (FIXME: this is duplicated in configuredialog.cpp)
02235     attachWordsList << QString::fromLatin1("attachment")
02236                     << QString::fromLatin1("attached");
02237     if ( QString::fromLatin1("attachment") != i18n("attachment") )
02238       attachWordsList << i18n("attachment");
02239     if ( QString::fromLatin1("attached") != i18n("attached") )
02240       attachWordsList << i18n("attached");
02241   }
02242 
02243   QRegExp rx ( QString::fromLatin1("\\b") +
02244                attachWordsList.join("\\b|\\b") +
02245                QString::fromLatin1("\\b") );
02246   rx.setCaseSensitive( false );
02247 
02248   bool gotMatch = false;
02249 
02250   // check whether the subject contains one of the attachment key words
02251   // unless the message is a reply or a forwarded message
02252   QString subj = subject();
02253   gotMatch =    ( KMMessage::stripOffPrefixes( subj ) == subj )
02254              && ( rx.search( subj ) >= 0 );
02255 
02256   if ( !gotMatch ) {
02257     // check whether the non-quoted text contains one of the attachment key
02258     // words
02259     QRegExp quotationRx ("^([ \\t]*([|>:}#]|[A-Za-z]+>))+");
02260     for ( int i = 0; i < mEditor->numLines(); ++i ) {
02261       QString line = mEditor->textLine( i );
02262       gotMatch =    ( quotationRx.search( line ) < 0 )
02263                  && ( rx.search( line ) >= 0 );
02264       if ( gotMatch )
02265         break;
02266     }
02267   }
02268 
02269   if ( !gotMatch )
02270     return false;
02271 
02272   int rc = KMessageBox::warningYesNoCancel( this,
02273              i18n("The message you have composed seems to refer to an "
02274                   "attached file but you have not attached anything.\n"
02275                   "Do you want to attach a file to your message?"),
02276              i18n("File Attachment Reminder"),
02277              i18n("&Attach File..."),
02278              i18n("&Send as Is") );
02279   if ( rc == KMessageBox::Cancel )
02280     return true;
02281   if ( rc == KMessageBox::Yes ) {
02282     slotAttachFile();
02283     //preceed with editing
02284     return true;
02285   }
02286   return false;
02287 }
02288 
02289 //-----------------------------------------------------------------------------
02290 void KMComposeWin::applyChanges( bool dontSignNorEncrypt, bool dontDisable )
02291 {
02292   kdDebug(5006) << "entering KMComposeWin::applyChanges" << endl;
02293 
02294   if(!mMsg || mComposer) {
02295     kdDebug(5006) << "KMComposeWin::applyChanges() : mMsg == 0!\n" << endl;
02296     emit applyChangesDone( false );
02297     return;
02298   }
02299 
02300   // Make new job and execute it
02301   mComposer = new MessageComposer( this );
02302   connect( mComposer, SIGNAL( done( bool ) ),
02303            this, SLOT( slotComposerDone( bool ) ) );
02304 
02305   // TODO: Add a cancel button for the following operations?
02306   // Disable any input to the window, so that we have a snapshot of the
02307   // composed stuff
02308   if ( !dontDisable ) setEnabled( false );
02309   // apply the current state to the composer and let it do it's thing
02310   mComposer->setDisableBreaking( mDisableBreaking ); // FIXME
02311   mComposer->applyChanges( dontSignNorEncrypt );
02312 }
02313 
02314 void KMComposeWin::slotComposerDone( bool rc )
02315 {
02316   deleteAll( mComposedMessages );
02317   mComposedMessages = mComposer->composedMessageList();
02318   emit applyChangesDone( rc );
02319   delete mComposer;
02320   mComposer = 0;
02321 
02322   // re-enable the composewin, the messsage composition is now done
02323   setEnabled( true );
02324 }
02325 
02326 const KPIM::Identity & KMComposeWin::identity() const {
02327   return kmkernel->identityManager()->identityForUoidOrDefault( mIdentity->currentIdentity() );
02328 }
02329 
02330 uint KMComposeWin::identityUid() const {
02331   return mIdentity->currentIdentity();
02332 }
02333 
02334 Kleo::CryptoMessageFormat KMComposeWin::cryptoMessageFormat() const {
02335   if ( !mCryptoModuleAction )
02336     return Kleo::AutoFormat;
02337   return cb2format( mCryptoModuleAction->currentItem() );
02338 }
02339 
02340 bool KMComposeWin::encryptToSelf() const {
02341 //   return !Kpgp::Module::getKpgp() || Kpgp::Module::getKpgp()->encryptToSelf();
02342     KConfigGroup group( KMKernel::config(), "Composer" );
02343     return group.readBoolEntry( "crypto-encrypt-to-self", true );
02344 }
02345 
02346 bool KMComposeWin::queryExit ()
02347 {
02348   return true;
02349 }
02350 
02351 //-----------------------------------------------------------------------------
02352 bool KMComposeWin::addAttach(const KURL aUrl)
02353 {
02354   if ( !aUrl.isValid() ) {
02355     KMessageBox::sorry( this, i18n( "<qt><p>KMail could not recognize the location of the attachment (%1);</p>"
02356                                  "<p>you have to specify the full path if you wish to attach a file.</p></qt>" )
02357                         .arg( aUrl.prettyURL() ) );
02358     return false;
02359   }
02360 
02361   const int maxAttachmentSize = GlobalSettings::maximumAttachmentSize();
02362   const uint maximumAttachmentSizeInByte = maxAttachmentSize*1024*1024;
02363   if ( aUrl.isLocalFile() && QFileInfo( aUrl.pathOrURL() ).size() > maximumAttachmentSizeInByte ) {
02364     KMessageBox::sorry( this, i18n( "<qt><p>Your administrator has disallowed attaching files bigger than %1 MB.</p>" ).arg( maxAttachmentSize ) );
02365     return false;
02366   }
02367 
02368   KIO::TransferJob *job = KIO::get(aUrl);
02369   KIO::Scheduler::scheduleJob( job );
02370   atmLoadData ld;
02371   ld.url = aUrl;
02372   ld.data = QByteArray();
02373   ld.insert = false;
02374   if( !aUrl.fileEncoding().isEmpty() )
02375     ld.encoding = aUrl.fileEncoding().latin1();
02376 
02377   mMapAtmLoadData.insert(job, ld);
02378   mAttachJobs[job] = aUrl;
02379   connect(job, SIGNAL(result(KIO::Job *)),
02380           this, SLOT(slotAttachFileResult(KIO::Job *)));
02381   connect(job, SIGNAL(data(KIO::Job *, const QByteArray &)),
02382           this, SLOT(slotAttachFileData(KIO::Job *, const QByteArray &)));
02383   return true;
02384 }
02385 
02386 
02387 //-----------------------------------------------------------------------------
02388 void KMComposeWin::addAttach(const KMMessagePart* msgPart)
02389 {
02390   mAtmList.append(msgPart);
02391 
02392   // show the attachment listbox if it does not up to now
02393   if (mAtmList.count()==1)
02394   {
02395     mAtmListView->resize(mAtmListView->width(), 50);
02396     mAtmListView->show();
02397     resize(size());
02398   }
02399 
02400   // add a line in the attachment listbox
02401   KMAtmListViewItem *lvi = new KMAtmListViewItem( mAtmListView );
02402   msgPartToItem(msgPart, lvi);
02403   mAtmItemList.append(lvi);
02404 
02405   // the Attach file job has finished, so the possibly present tmp dir can be deleted now.
02406   if ( mTempDir != 0 ) {
02407     delete mTempDir;
02408     mTempDir = 0;
02409   }
02410 
02411   connect( lvi, SIGNAL( compress( int ) ),
02412       this, SLOT( compressAttach( int ) ) );
02413   connect( lvi, SIGNAL( uncompress( int ) ),
02414       this, SLOT( uncompressAttach( int ) ) );
02415 
02416   slotUpdateAttachActions();
02417 }
02418 
02419 
02420 //-----------------------------------------------------------------------------
02421 void KMComposeWin::slotUpdateAttachActions()
02422 {
02423   int selectedCount = 0;
02424   for ( QPtrListIterator<QListViewItem> it(mAtmItemList); *it; ++it ) {
02425     if ( (*it)->isSelected() ) {
02426       ++selectedCount;
02427     }
02428   }
02429 
02430   mAttachRemoveAction->setEnabled( selectedCount >= 1 );
02431   mAttachSaveAction->setEnabled( selectedCount == 1 );
02432   mAttachPropertiesAction->setEnabled( selectedCount == 1 );
02433 }
02434 
02435 
02436 //-----------------------------------------------------------------------------
02437 
02438 QString KMComposeWin::prettyMimeType( const QString& type )
02439 {
02440   QString t = type.lower();
02441   KServiceType::Ptr st = KServiceType::serviceType( t );
02442   return st ? st->comment() : t;
02443 }
02444 
02445 void KMComposeWin::msgPartToItem(const KMMessagePart* msgPart,
02446                                  KMAtmListViewItem *lvi, bool loadDefaults)
02447 {
02448   assert(msgPart != 0);
02449 
02450   if (!msgPart->fileName().isEmpty())
02451     lvi->setText(0, msgPart->fileName());
02452   else
02453     lvi->setText(0, msgPart->name());
02454   lvi->setText(1, KIO::convertSize( msgPart->decodedSize()));
02455   lvi->setText(2, msgPart->contentTransferEncodingStr());
02456   lvi->setText(3, prettyMimeType(msgPart->typeStr() + "/" + msgPart->subtypeStr()));
02457   lvi->setAttachmentSize(msgPart->decodedSize());
02458 
02459   if ( loadDefaults ) {
02460     if( canSignEncryptAttachments() ) {
02461       lvi->enableCryptoCBs( true );
02462       lvi->setEncrypt( mEncryptAction->isChecked() );
02463       lvi->setSign(    mSignAction->isChecked() );
02464     } else {
02465       lvi->enableCryptoCBs( false );
02466     }
02467   }
02468 }
02469 
02470 
02471 //-----------------------------------------------------------------------------
02472 void KMComposeWin::removeAttach(const QString &aUrl)
02473 {
02474   int idx;
02475   KMMessagePart* msgPart;
02476   for(idx=0,msgPart=mAtmList.first(); msgPart;
02477       msgPart=mAtmList.next(),idx++) {
02478     if (msgPart->name() == aUrl) {
02479       removeAttach(idx);
02480       return;
02481     }
02482   }
02483 }
02484 
02485 
02486 //-----------------------------------------------------------------------------
02487 void KMComposeWin::removeAttach(int idx)
02488 {
02489   mAtmModified = true;
02490   mAtmList.remove(idx);
02491   delete mAtmItemList.take(idx);
02492 
02493   if( mAtmList.isEmpty() )
02494   {
02495     mAtmListView->hide();
02496     mAtmListView->setMinimumSize(0, 0);
02497     resize(size());
02498   }
02499 }
02500 
02501 
02502 //-----------------------------------------------------------------------------
02503 bool KMComposeWin::encryptFlagOfAttachment(int idx)
02504 {
02505   return (int)(mAtmItemList.count()) > idx
02506     ? static_cast<KMAtmListViewItem*>( mAtmItemList.at( idx ) )->isEncrypt()
02507     : false;
02508 }
02509 
02510 
02511 //-----------------------------------------------------------------------------
02512 bool KMComposeWin::signFlagOfAttachment(int idx)
02513 {
02514   return (int)(mAtmItemList.count()) > idx
02515     ? ((KMAtmListViewItem*)(mAtmItemList.at( idx )))->isSign()
02516     : false;
02517 }
02518 
02519 
02520 //-----------------------------------------------------------------------------
02521 void KMComposeWin::addrBookSelInto()
02522 {
02523   if ( mClassicalRecipients ) {
02524     if ( GlobalSettings::self()->addresseeSelectorType() ==
02525          GlobalSettings::EnumAddresseeSelectorType::New ) {
02526       addrBookSelIntoNew();
02527     } else {
02528       addrBookSelIntoOld();
02529     }
02530   } else {
02531     kdWarning() << "To be implemented: call recipients picker." << endl;
02532   }
02533 }
02534 
02535 void KMComposeWin::addrBookSelIntoOld()
02536 {
02537   AddressesDialog dlg( this );
02538   QString txt;
02539   QStringList lst;
02540 
02541   txt = to();
02542   if ( !txt.isEmpty() ) {
02543       lst = KPIM::splitEmailAddrList( txt );
02544       dlg.setSelectedTo( lst );
02545   }
02546 
02547   txt = mEdtCc->text();
02548   if ( !txt.isEmpty() ) {
02549       lst = KPIM::splitEmailAddrList( txt );
02550       dlg.setSelectedCC( lst );
02551   }
02552 
02553   txt = mEdtBcc->text();
02554   if ( !txt.isEmpty() ) {
02555       lst = KPIM::splitEmailAddrList( txt );
02556       dlg.setSelectedBCC( lst );
02557   }
02558 
02559   dlg.setRecentAddresses( RecentAddresses::self( KMKernel::config() )->kabcAddresses() );
02560 
02561   if (dlg.exec()==QDialog::Rejected) return;
02562 
02563   mEdtTo->setText( dlg.to().join(", ") );
02564   mEdtTo->setEdited( true );
02565 
02566   mEdtCc->setText( dlg.cc().join(", ") );
02567   mEdtCc->setEdited( true );
02568 
02569   mEdtBcc->setText( dlg.bcc().join(", ") );
02570   mEdtBcc->setEdited( true );
02571 
02572   //Make sure BCC field is shown if needed
02573   if ( !mEdtBcc->text().isEmpty() ) {
02574     mShowHeaders |= HDR_BCC;
02575     rethinkFields( false );
02576   }
02577 }
02578 
02579 void KMComposeWin::addrBookSelIntoNew()
02580 {
02581   AddresseeEmailSelection selection;
02582 
02583   AddresseeSelectorDialog dlg( &selection );
02584 
02585   QString txt;
02586   QStringList lst;
02587 
02588   txt = to();
02589   if ( !txt.isEmpty() ) {
02590       lst = KPIM::splitEmailAddrList( txt );
02591       selection.setSelectedTo( lst );
02592   }
02593 
02594   txt = mEdtCc->text();
02595   if ( !txt.isEmpty() ) {
02596       lst = KPIM::splitEmailAddrList( txt );
02597       selection.setSelectedCC( lst );
02598   }
02599 
02600   txt = mEdtBcc->text();
02601   if ( !txt.isEmpty() ) {
02602       lst = KPIM::splitEmailAddrList( txt );
02603       selection.setSelectedBCC( lst );
02604   }
02605 
02606   if (dlg.exec()==QDialog::Rejected) return;
02607 
02608   QStringList list = selection.to() + selection.toDistributionLists();
02609   mEdtTo->setText( list.join(", ") );
02610   mEdtTo->setEdited( true );
02611 
02612   list = selection.cc() + selection.ccDistributionLists();
02613   mEdtCc->setText( list.join(", ") );
02614   mEdtCc->setEdited( true );
02615 
02616   list = selection.bcc() + selection.bccDistributionLists();
02617   mEdtBcc->setText( list.join(", ") );
02618   mEdtBcc->setEdited( true );
02619 
02620   //Make sure BCC field is shown if needed
02621   if ( !mEdtBcc->text().isEmpty() ) {
02622     mShowHeaders |= HDR_BCC;
02623     rethinkFields( false );
02624   }
02625 }
02626 
02627 
02628 //-----------------------------------------------------------------------------
02629 void KMComposeWin::setCharset(const QCString& aCharset, bool forceDefault)
02630 {
02631   if ((forceDefault && GlobalSettings::self()->forceReplyCharset()) || aCharset.isEmpty())
02632     mCharset = mDefCharset;
02633   else
02634     mCharset = aCharset.lower();
02635 
02636   if ( mCharset.isEmpty() || mCharset == "default" )
02637      mCharset = mDefCharset;
02638 
02639   if (mAutoCharset)
02640   {
02641     mEncodingAction->setCurrentItem( 0 );
02642     return;
02643   }
02644 
02645   QStringList encodings = mEncodingAction->items();
02646   int i = 0;
02647   bool charsetFound = false;
02648   for ( QStringList::Iterator it = encodings.begin(); it != encodings.end();
02649      ++it, i++ )
02650   {
02651     if (i > 0 && ((mCharset == "us-ascii" && i == 1) ||
02652      (i != 1 && KGlobal::charsets()->codecForName(
02653       KGlobal::charsets()->encodingForName(*it))
02654       == KGlobal::charsets()->codecForName(mCharset))))
02655     {
02656       mEncodingAction->setCurrentItem( i );
02657       slotSetCharset();
02658       charsetFound = true;
02659       break;
02660     }
02661   }
02662   if (!aCharset.isEmpty() && !charsetFound) setCharset("", true);
02663 }
02664 
02665 
02666 //-----------------------------------------------------------------------------
02667 void KMComposeWin::slotAddrBook()
02668 {
02669   KAddrBookExternal::openAddressBook(this);
02670 }
02671 
02672 
02673 //-----------------------------------------------------------------------------
02674 void KMComposeWin::slotAddrBookFrom()
02675 {
02676   addrBookSelInto();
02677 }
02678 
02679 
02680 //-----------------------------------------------------------------------------
02681 void KMComposeWin::slotAddrBookReplyTo()
02682 {
02683   addrBookSelInto();
02684 }
02685 
02686 
02687 //-----------------------------------------------------------------------------
02688 void KMComposeWin::slotAddrBookTo()
02689 {
02690   addrBookSelInto();
02691 }
02692 
02693 //-----------------------------------------------------------------------------
02694 void KMComposeWin::slotAttachFile()
02695 {
02696   // Create File Dialog and return selected file(s)
02697   // We will not care about any permissions, existence or whatsoever in
02698   // this function.
02699 
02700   KFileDialog fdlg(QString::null, QString::null, this, 0, true);
02701   fdlg.setOperationMode( KFileDialog::Other );
02702   fdlg.setCaption(i18n("Attach File"));
02703   fdlg.okButton()->setGuiItem(KGuiItem(i18n("&Attach"),"fileopen"));
02704   fdlg.setMode(KFile::Files);
02705   fdlg.exec();
02706   KURL::List files = fdlg.selectedURLs();
02707 
02708   for (KURL::List::Iterator it = files.begin(); it != files.end(); ++it)
02709     addAttach(*it);
02710 }
02711 
02712 
02713 //-----------------------------------------------------------------------------
02714 void KMComposeWin::slotAttachFileData(KIO::Job *job, const QByteArray &data)
02715 {
02716   QMap<KIO::Job*, atmLoadData>::Iterator it = mMapAtmLoadData.find(job);
02717   assert(it != mMapAtmLoadData.end());
02718   QBuffer buff((*it).data);
02719   buff.open(IO_WriteOnly | IO_Append);
02720   buff.writeBlock(data.data(), data.size());
02721   buff.close();
02722 }
02723 
02724 
02725 //-----------------------------------------------------------------------------
02726 void KMComposeWin::slotAttachFileResult(KIO::Job *job)
02727 {
02728   QMap<KIO::Job*, atmLoadData>::Iterator it = mMapAtmLoadData.find(job);
02729   assert(it != mMapAtmLoadData.end());
02730   KURL attachURL;
02731   QMap<KIO::Job*, KURL>::iterator jit = mAttachJobs.find(job);
02732   bool attachURLfound = (jit != mAttachJobs.end());
02733   if (attachURLfound)
02734   {
02735     attachURL = jit.data();
02736     mAttachJobs.remove(jit);
02737   }
02738   if (job->error())
02739   {
02740     mMapAtmLoadData.remove(it);
02741     job->showErrorDialog();
02742     if (attachURLfound)
02743       emit attachmentAdded(attachURL, false);
02744     return;
02745   }
02746   if ((*it).insert)
02747   {
02748     (*it).data.resize((*it).data.size() + 1);
02749     (*it).data[(*it).data.size() - 1] = '\0';
02750     if ( const QTextCodec * codec = KGlobal::charsets()->codecForName((*it).encoding) )
02751       mEditor->insert( codec->toUnicode( (*it).data ) );
02752     else
02753       mEditor->insert( QString::fromLocal8Bit( (*it).data ) );
02754     mMapAtmLoadData.remove(it);
02755     if (attachURLfound)
02756       emit attachmentAdded(attachURL, true);
02757     return;
02758   }
02759   QCString partCharset;
02760   if ( !( *it ).url.fileEncoding().isEmpty() ) {
02761     partCharset = QCString( ( *it ).url.fileEncoding().latin1() );
02762   } else {
02763     EncodingDetector ed;
02764     KLocale *loc = KGlobal::locale();
02765     ed.setAutoDetectLanguage( EncodingDetector::scriptForLanguageCode ( loc->language() ) );
02766     ed.analyze( (*it).data );
02767     partCharset = ed.encoding();
02768     if ( partCharset.isEmpty() ) //shouldn't happen
02769       partCharset = mCharset;
02770   }
02771 
02772   KMMessagePart* msgPart;
02773 
02774   KCursorSaver busy(KBusyPtr::busy());
02775   QString name( (*it).url.fileName() );
02776   // ask the job for the mime type of the file
02777   QString mimeType = static_cast<KIO::MimetypeJob*>(job)->mimetype();
02778 
02779   if ( name.isEmpty() ) {
02780     // URL ends with '/' (e.g. http://www.kde.org/)
02781     // guess a reasonable filename
02782     if( mimeType == "text/html" )
02783       name = "index.html";
02784     else {
02785       // try to determine a reasonable extension
02786       QStringList patterns( KMimeType::mimeType( mimeType )->patterns() );
02787       QString ext;
02788       if( !patterns.isEmpty() ) {
02789         ext = patterns[0];
02790         int i = ext.findRev( '.' );
02791         if( i == -1 )
02792           ext.prepend( '.' );
02793         else if( i > 0 )
02794           ext = ext.mid( i );
02795       }
02796       name = QString("unknown") += ext;
02797     }
02798   }
02799 
02800   name.truncate( 256 ); // is this needed?
02801 
02802   QCString encoding = KMMsgBase::autoDetectCharset(partCharset,
02803     KMMessage::preferredCharsets(), name);
02804   if ( encoding.isEmpty() )
02805     encoding = "utf-8";
02806 
02807   QCString encName;
02808   if ( GlobalSettings::self()->outlookCompatibleAttachments() )
02809     encName = KMMsgBase::encodeRFC2047String( name, encoding );
02810   else
02811     encName = KMMsgBase::encodeRFC2231String( name, encoding );
02812   bool RFC2231encoded = false;
02813   if ( !GlobalSettings::self()->outlookCompatibleAttachments() )
02814     RFC2231encoded = name != QString( encName );
02815 
02816   // create message part
02817   msgPart = new KMMessagePart;
02818   msgPart->setName(name);
02819   QValueList<int> allowedCTEs;
02820   if ( mimeType == "message/rfc822" ) {
02821     msgPart->setMessageBody( (*it).data );
02822     allowedCTEs << DwMime::kCte7bit;
02823     allowedCTEs << DwMime::kCte8bit;
02824   } else {
02825     msgPart->setBodyAndGuessCte((*it).data, allowedCTEs,
02826                                !kmkernel->msgSender()->sendQuotedPrintable());
02827     kdDebug(5006) << "autodetected cte: " << msgPart->cteStr() << endl;
02828   }
02829   int slash = mimeType.find( '/' );
02830   if( slash == -1 )
02831     slash = mimeType.length();
02832   msgPart->setTypeStr( mimeType.left( slash ).latin1() );
02833   msgPart->setSubtypeStr( mimeType.mid( slash + 1 ).latin1() );
02834   msgPart->setContentDisposition(QCString("attachment;\n\tfilename")
02835     + ( RFC2231encoded ? "*=" + encName : "=\"" + encName + '"' ) );
02836 
02837   mMapAtmLoadData.remove(it);
02838 
02839   msgPart->setCharset(partCharset);
02840 
02841   // show message part dialog, if not configured away (default):
02842   KConfigGroup composer(KMKernel::config(), "Composer");
02843   if ( GlobalSettings::self()->showMessagePartDialogOnAttach() ) {
02844     const KCursorSaver saver( QCursor::ArrowCursor );
02845     KMMsgPartDialogCompat dlg(mMainWidget);
02846     int encodings = 0;
02847     for ( QValueListConstIterator<int> it = allowedCTEs.begin() ;
02848           it != allowedCTEs.end() ; ++it )
02849       switch ( *it ) {
02850       case DwMime::kCteBase64: encodings |= KMMsgPartDialog::Base64; break;
02851       case DwMime::kCteQp: encodings |= KMMsgPartDialog::QuotedPrintable; break;
02852       case DwMime::kCte7bit: encodings |= KMMsgPartDialog::SevenBit; break;
02853       case DwMime::kCte8bit: encodings |= KMMsgPartDialog::EightBit; break;
02854       default: ;
02855       }
02856     dlg.setShownEncodings( encodings );
02857     dlg.setMsgPart(msgPart);
02858     if (!dlg.exec()) {
02859       delete msgPart;
02860       msgPart = 0;
02861       if (attachURLfound)
02862         emit attachmentAdded(attachURL, false);
02863       return;
02864     }
02865   }
02866   mAtmModified = true;
02867   if (msgPart->typeStr().lower() != "text") msgPart->setCharset(QCString());
02868 
02869   // add the new attachment to the list
02870   addAttach(msgPart);
02871 
02872   if (attachURLfound)
02873     emit attachmentAdded(attachURL, true);
02874 }
02875 
02876 
02877 //-----------------------------------------------------------------------------
02878 void KMComposeWin::slotInsertFile()
02879 {
02880   KFileDialog fdlg(QString::null, QString::null, this, 0, true);
02881   fdlg.setOperationMode( KFileDialog::Opening );
02882   fdlg.okButton()->setText(i18n("&Insert"));
02883   fdlg.setCaption(i18n("Insert File"));
02884   fdlg.toolBar()->insertCombo(KMMsgBase::supportedEncodings(false), 4711,
02885     false, 0, 0, 0);
02886   KComboBox *combo = fdlg.toolBar()->getCombo(4711);
02887   for (int i = 0; i < combo->count(); i++)
02888     if (KGlobal::charsets()->codecForName(KGlobal::charsets()->
02889       encodingForName(combo->text(i)))
02890       == QTextCodec::codecForLocale()) combo->setCurrentItem(i);
02891   if (!fdlg.exec()) return;
02892 
02893   KURL u = fdlg.selectedURL();
02894   mRecentAction->addURL(u);
02895   // Prevent race condition updating list when multiple composers are open
02896   {
02897     KConfig *config = KMKernel::config();
02898     KConfigGroupSaver saver( config, "Composer" );
02899     QString encoding = KGlobal::charsets()->encodingForName(combo->currentText()).latin1();
02900     QStringList urls = config->readListEntry( "recent-urls" );
02901     QStringList encodings = config->readListEntry( "recent-encodings" );
02902     // Prevent config file from growing without bound
02903     // Would be nicer to get this constant from KRecentFilesAction
02904     uint mMaxRecentFiles = 30;
02905     while (urls.count() > mMaxRecentFiles)
02906       urls.erase( urls.fromLast() );
02907     while (encodings.count() > mMaxRecentFiles)
02908       encodings.erase( encodings.fromLast() );
02909     // sanity check
02910     if (urls.count() != encodings.count()) {
02911       urls.clear();
02912       encodings.clear();
02913     }
02914     urls.prepend( u.prettyURL() );
02915     encodings.prepend( encoding );
02916     config->writeEntry( "recent-urls", urls );
02917     config->writeEntry( "recent-encodings", encodings );
02918     mRecentAction->saveEntries( config );
02919   }
02920   slotInsertRecentFile(u);
02921 }
02922 
02923 
02924 //-----------------------------------------------------------------------------
02925 void KMComposeWin::slotInsertRecentFile(const KURL& u)
02926 {
02927   if (u.fileName().isEmpty()) return;
02928 
02929   KIO::Job *job = KIO::get(u);
02930   atmLoadData ld;
02931   ld.url = u;
02932   ld.data = QByteArray();
02933   ld.insert = true;
02934   // Get the encoding previously used when inserting this file
02935   {
02936     KConfig *config = KMKernel::config();
02937     KConfigGroupSaver saver( config, "Composer" );
02938     QStringList urls = config->readListEntry( "recent-urls" );
02939     QStringList encodings = config->readListEntry( "recent-encodings" );
02940     int index = urls.findIndex( u.prettyURL() );
02941     if (index != -1) {
02942       QString encoding = encodings[ index ];
02943       ld.encoding = encoding.latin1();
02944     }
02945   }
02946   mMapAtmLoadData.insert(job, ld);
02947   connect(job, SIGNAL(result(KIO::Job *)),
02948           this, SLOT(slotAttachFileResult(KIO::Job *)));
02949   connect(job, SIGNAL(data(KIO::Job *, const QByteArray &)),
02950           this, SLOT(slotAttachFileData(KIO::Job *, const QByteArray &)));
02951 }
02952 
02953 
02954 //-----------------------------------------------------------------------------
02955 void KMComposeWin::slotSetCharset()
02956 {
02957   if (mEncodingAction->currentItem() == 0)
02958   {
02959     mAutoCharset = true;
02960     return;
02961   }
02962   mAutoCharset = false;
02963 
02964   mCharset = KGlobal::charsets()->encodingForName( mEncodingAction->
02965     currentText() ).latin1();
02966 }
02967 
02968 
02969 //-----------------------------------------------------------------------------
02970 void KMComposeWin::slotSelectCryptoModule( bool init )
02971 {
02972   if ( !init ) {
02973     setModified( true );
02974   }
02975   if( canSignEncryptAttachments() ) {
02976     // if the encrypt/sign columns are hidden then show them
02977     if( 0 == mAtmListView->columnWidth( mAtmColEncrypt ) ) {
02978       // set/unset signing/encryption for all attachments according to the
02979       // state of the global sign/encrypt action
02980       if( !mAtmList.isEmpty() ) {
02981         for( KMAtmListViewItem* lvi = static_cast<KMAtmListViewItem*>( mAtmItemList.first() );
02982              lvi;
02983              lvi = static_cast<KMAtmListViewItem*>( mAtmItemList.next() ) ) {
02984           lvi->setSign( mSignAction->isChecked() );
02985           lvi->setEncrypt( mEncryptAction->isChecked() );
02986         }
02987       }
02988       int totalWidth = 0;
02989       // determine the total width of the columns
02990       for( int col=0; col < mAtmColEncrypt; col++ )
02991         totalWidth += mAtmListView->columnWidth( col );
02992       int reducedTotalWidth = totalWidth - mAtmEncryptColWidth
02993                                          - mAtmSignColWidth;
02994       // reduce the width of all columns so that the encrypt and sign column
02995       // fit
02996       int usedWidth = 0;
02997       for( int col=0; col < mAtmColEncrypt-1; col++ ) {
02998         int newWidth = mAtmListView->columnWidth( col ) * reducedTotalWidth
02999                                                        / totalWidth;
03000         mAtmListView->setColumnWidth( col, newWidth );
03001         usedWidth += newWidth;
03002       }
03003       // the last column before the encrypt column gets the remaining space
03004       // (because of rounding errors the width of this column isn't calculated
03005       // the same way as the width of the other columns)
03006       mAtmListView->setColumnWidth( mAtmColEncrypt-1,
03007                                     reducedTotalWidth - usedWidth );
03008       mAtmListView->setColumnWidth( mAtmColEncrypt, mAtmEncryptColWidth );
03009       mAtmListView->setColumnWidth( mAtmColSign,    mAtmSignColWidth );
03010       for( KMAtmListViewItem* lvi = static_cast<KMAtmListViewItem*>( mAtmItemList.first() );
03011            lvi;
03012            lvi = static_cast<KMAtmListViewItem*>( mAtmItemList.next() ) ) {
03013         lvi->enableCryptoCBs( true );
03014       }
03015     }
03016   } else {
03017     // if the encrypt/sign columns are visible then hide them
03018     if( 0 != mAtmListView->columnWidth( mAtmColEncrypt ) ) {
03019       mAtmEncryptColWidth = mAtmListView->columnWidth( mAtmColEncrypt );
03020       mAtmSignColWidth = mAtmListView->columnWidth( mAtmColSign );
03021       int totalWidth = 0;
03022       // determine the total width of the columns
03023       for( int col=0; col < mAtmListView->columns(); col++ )
03024         totalWidth += mAtmListView->columnWidth( col );
03025       int reducedTotalWidth = totalWidth - mAtmEncryptColWidth
03026                                          - mAtmSignColWidth;
03027       // increase the width of all columns so that the visible columns take
03028       // up the whole space
03029       int usedWidth = 0;
03030       for( int col=0; col < mAtmColEncrypt-1; col++ ) {
03031         int newWidth = mAtmListView->columnWidth( col ) * totalWidth
03032                                                        / reducedTotalWidth;
03033         mAtmListView->setColumnWidth( col, newWidth );
03034         usedWidth += newWidth;
03035       }
03036       // the last column before the encrypt column gets the remaining space
03037       // (because of rounding errors the width of this column isn't calculated
03038       // the same way as the width of the other columns)
03039       mAtmListView->setColumnWidth( mAtmColEncrypt-1, totalWidth - usedWidth );
03040       mAtmListView->setColumnWidth( mAtmColEncrypt, 0 );
03041       mAtmListView->setColumnWidth( mAtmColSign,    0 );
03042       for( KMAtmListViewItem* lvi = static_cast<KMAtmListViewItem*>( mAtmItemList.first() );
03043            lvi;
03044            lvi = static_cast<KMAtmListViewItem*>( mAtmItemList.next() ) ) {
03045         lvi->enableCryptoCBs( false );
03046       }
03047     }
03048   }
03049 }
03050 
03051 static void showExportError( QWidget * w, const GpgME::Error & err ) {
03052   assert( err );
03053   const QString msg = i18n("<qt><p>An error occurred while trying to export "
03054                "the key from the backend:</p>"
03055                "<p><b>%1</b></p></qt>")
03056     .arg( QString::fromLocal8Bit( err.asString() ) );
03057   KMessageBox::error( w, msg, i18n("Key Export Failed") );
03058 }
03059 
03060 
03061 //-----------------------------------------------------------------------------
03062 void KMComposeWin::slotInsertMyPublicKey()
03063 {
03064   // get PGP user id for the chosen identity
03065   mFingerprint =
03066     kmkernel->identityManager()->identityForUoidOrDefault( mIdentity->currentIdentity() ).pgpEncryptionKey();
03067   if ( !mFingerprint.isEmpty() )
03068     startPublicKeyExport();
03069 }
03070 
03071 void KMComposeWin::startPublicKeyExport() {
03072   if ( mFingerprint.isEmpty() || !Kleo::CryptoBackendFactory::instance()->openpgp() )
03073     return;
03074   Kleo::ExportJob * job = Kleo::CryptoBackendFactory::instance()->openpgp()->publicKeyExportJob( true );
03075   assert( job );
03076 
03077   connect( job, SIGNAL(result(const GpgME::Error&,const QByteArray&)),
03078        this, SLOT(slotPublicKeyExportResult(const GpgME::Error&,const QByteArray&)) );
03079 
03080   const GpgME::Error err = job->start( mFingerprint );
03081   if ( err )
03082     showExportError( this, err );
03083   else
03084     (void)new Kleo::ProgressDialog( job, i18n("Exporting key..."), this );
03085 }
03086 
03087 void KMComposeWin::slotPublicKeyExportResult( const GpgME::Error & err, const QByteArray & keydata ) {
03088   if ( err ) {
03089     showExportError( this, err );
03090     return;
03091   }
03092 
03093   // create message part
03094   KMMessagePart * msgPart = new KMMessagePart();
03095   msgPart->setName( i18n("OpenPGP key 0x%1").arg( mFingerprint ) );
03096   msgPart->setTypeStr("application");
03097   msgPart->setSubtypeStr("pgp-keys");
03098   QValueList<int> dummy;
03099   msgPart->setBodyAndGuessCte(keydata, dummy, false);
03100   msgPart->setContentDisposition( "attachment;\n\tfilename=0x" + QCString( mFingerprint.latin1() ) + ".asc" );
03101 
03102   // add the new attachment to the list
03103   addAttach(msgPart);
03104   rethinkFields(); //work around initial-size bug in Qt-1.32
03105 }
03106 
03107 //-----------------------------------------------------------------------------
03108 void KMComposeWin::slotInsertPublicKey()
03109 {
03110   Kleo::KeySelectionDialog dlg( i18n("Attach Public OpenPGP Key"),
03111                                 i18n("Select the public key which should "
03112                                      "be attached."),
03113                 std::vector<GpgME::Key>(),
03114                 Kleo::KeySelectionDialog::PublicKeys|Kleo::KeySelectionDialog::OpenPGPKeys,
03115                 false /* no multi selection */,
03116                 false /* no remember choice box */,
03117                 this, "attach public key selection dialog" );
03118   if ( dlg.exec() != QDialog::Accepted )
03119     return;
03120 
03121   mFingerprint = dlg.fingerprint();
03122   startPublicKeyExport();
03123 }
03124 
03125 
03126 //-----------------------------------------------------------------------------
03127 void KMComposeWin::slotAttachPopupMenu(QListViewItem *, const QPoint &, int)
03128 {
03129   if (!mAttachMenu)
03130   {
03131      mAttachMenu = new QPopupMenu(this);
03132 
03133      mOpenId = mAttachMenu->insertItem(i18n("to open", "Open"), this,
03134                              SLOT(slotAttachOpen()));
03135      mOpenWithId = mAttachMenu->insertItem(i18n("Open With..."), this,
03136                              SLOT(slotAttachOpenWith()));
03137      mViewId = mAttachMenu->insertItem(i18n("to view", "View"), this,
03138                              SLOT(slotAttachView()));
03139      mEditId = mAttachMenu->insertItem( i18n("Edit"), this, SLOT(slotAttachEdit()) );
03140      mEditWithId = mAttachMenu->insertItem( i18n("Edit With..."), this,
03141                                             SLOT(slotAttachEditWith()) );
03142      mRemoveId = mAttachMenu->insertItem(i18n("Remove"), this, SLOT(slotAttachRemove()));
03143      mSaveAsId = mAttachMenu->insertItem( SmallIconSet("filesaveas"), i18n("Save As..."), this,
03144                                           SLOT( slotAttachSave() ) );
03145      mPropertiesId = mAttachMenu->insertItem( i18n("Properties"), this,
03146                                               SLOT( slotAttachProperties() ) );
03147      mAttachMenu->insertSeparator();
03148      mAttachMenu->insertItem(i18n("Add Attachment..."), this, SLOT(slotAttachFile()));
03149   }
03150 
03151   int selectedCount = 0;
03152   for ( QPtrListIterator<QListViewItem> it(mAtmItemList); *it; ++it ) {
03153     if ( (*it)->isSelected() ) {
03154       ++selectedCount;
03155     }
03156   }
03157 
03158   mAttachMenu->setItemEnabled( mOpenId, selectedCount > 0 );
03159   mAttachMenu->setItemEnabled( mOpenWithId, selectedCount > 0 );
03160   mAttachMenu->setItemEnabled( mViewId, selectedCount > 0 );
03161   mAttachMenu->setItemEnabled( mEditId, selectedCount == 1 );
03162   mAttachMenu->setItemEnabled( mEditWithId, selectedCount == 1 );
03163   mAttachMenu->setItemEnabled( mRemoveId, selectedCount > 0 );
03164   mAttachMenu->setItemEnabled( mSaveAsId, selectedCount == 1 );
03165   mAttachMenu->setItemEnabled( mPropertiesId, selectedCount == 1 );
03166 
03167   mAttachMenu->popup(QCursor::pos());
03168 }
03169 
03170 //-----------------------------------------------------------------------------
03171 int KMComposeWin::currentAttachmentNum()
03172 {
03173   int i = 0;
03174   for ( QPtrListIterator<QListViewItem> it(mAtmItemList); *it; ++it, ++i )
03175     if ( *it == mAtmListView->currentItem() )
03176       return i;
03177   return -1;
03178 }
03179 
03180 //-----------------------------------------------------------------------------
03181 void KMComposeWin::slotAttachProperties()
03182 {
03183   int idx = currentAttachmentNum();
03184 
03185   if (idx < 0) return;
03186 
03187   KMMessagePart* msgPart = mAtmList.at(idx);
03188   msgPart->setCharset(mCharset);
03189 
03190   KMMsgPartDialogCompat dlg(mMainWidget);
03191   dlg.setMsgPart(msgPart);
03192   KMAtmListViewItem* listItem = (KMAtmListViewItem*)(mAtmItemList.at(idx));
03193   if( canSignEncryptAttachments() && listItem ) {
03194     dlg.setCanSign(    true );
03195     dlg.setCanEncrypt( true );
03196     dlg.setSigned(    listItem->isSign()    );
03197     dlg.setEncrypted( listItem->isEncrypt() );
03198   } else {
03199     dlg.setCanSign(    false );
03200     dlg.setCanEncrypt( false );
03201   }
03202   if (dlg.exec())
03203   {
03204     mAtmModified = true;
03205     // values may have changed, so recreate the listbox line
03206     if( listItem ) {
03207       msgPartToItem(msgPart, listItem);
03208       if( canSignEncryptAttachments() ) {
03209         listItem->setSign(    dlg.isSigned()    );
03210         listItem->setEncrypt( dlg.isEncrypted() );
03211       }
03212     }
03213   }
03214   if (msgPart->typeStr().lower() != "text") msgPart->setCharset(QCString());
03215 }
03216 
03217 //-----------------------------------------------------------------------------
03218 void KMComposeWin::compressAttach( int idx )
03219 {
03220   if (idx < 0) return;
03221 
03222   unsigned int i;
03223   for ( i = 0; i < mAtmItemList.count(); ++i )
03224       if ( mAtmItemList.at( i )->itemPos() == idx )
03225           break;
03226 
03227   if ( i > mAtmItemList.count() )
03228       return;
03229 
03230   KMMessagePart* msgPart;
03231   msgPart = mAtmList.at( i );
03232   QByteArray array;
03233   QBuffer dev( array );
03234   KZip zip( &dev );
03235   QByteArray decoded = msgPart->bodyDecodedBinary();
03236   if ( ! zip.open( IO_WriteOnly ) ) {
03237     KMessageBox::sorry(0, i18n("KMail could not compress the file.") );
03238     static_cast<KMAtmListViewItem*>( mAtmItemList.at( i ) )->setCompress( false );
03239     return;
03240   }
03241 
03242   zip.setCompression( KZip::DeflateCompression );
03243   if ( ! zip.writeFile( msgPart->name(), "", "", decoded.size(),
03244            decoded.data() ) ) {
03245     KMessageBox::sorry(0, i18n("KMail could not compress the file.") );
03246     static_cast<KMAtmListViewItem*>( mAtmItemList.at( i ) )->setCompress( false );
03247     return;
03248   }
03249   zip.close();
03250   if ( array.size() >= decoded.size() ) {
03251     if ( KMessageBox::questionYesNo( this, i18n("The compressed file is larger "
03252         "than the original. Do you want to keep the original one?" ), QString::null, i18n("Keep"), i18n("Compress") )
03253          == KMessageBox::Yes ) {
03254       static_cast<KMAtmListViewItem*>( mAtmItemList.at( i ) )->setCompress( false );
03255       return;
03256     }
03257   }
03258   static_cast<KMAtmListViewItem*>( mAtmItemList.at( i ) )->setUncompressedCodec(
03259       msgPart->cteStr() );
03260 
03261   msgPart->setCteStr( "base64" );
03262   msgPart->setBodyEncodedBinary( array );
03263   QString name = msgPart->name() + ".zip";
03264 
03265   msgPart->setName( name );
03266 
03267   QCString cDisp = "attachment;";
03268   QCString encoding = KMMsgBase::autoDetectCharset( msgPart->charset(),
03269     KMMessage::preferredCharsets(), name );
03270   kdDebug(5006) << "encoding: " << encoding << endl;
03271   if ( encoding.isEmpty() ) encoding = "utf-8";
03272   kdDebug(5006) << "encoding after: " << encoding << endl;
03273   QCString encName;
03274   if ( GlobalSettings::self()->outlookCompatibleAttachments() )
03275     encName = KMMsgBase::encodeRFC2047String( name, encoding );
03276   else
03277     encName = KMMsgBase::encodeRFC2231String( name, encoding );
03278 
03279   cDisp += "\n\tfilename";
03280   if ( name != QString( encName ) )
03281     cDisp += "*=" + encName;
03282   else
03283     cDisp += "=\"" + encName + '"';
03284   msgPart->setContentDisposition( cDisp );
03285 
03286   static_cast<KMAtmListViewItem*>( mAtmItemList.at( i ) )->setUncompressedMimeType(
03287       msgPart->typeStr(), msgPart->subtypeStr() );
03288   msgPart->setTypeStr( "application" );
03289   msgPart->setSubtypeStr( "x-zip" );
03290 
03291   KMAtmListViewItem* listItem = static_cast<KMAtmListViewItem*>( mAtmItemList.at( i ) );
03292   msgPartToItem( msgPart, listItem, false );
03293 }
03294 
03295 //-----------------------------------------------------------------------------
03296 
03297 void KMComposeWin::uncompressAttach( int idx )
03298 {
03299   if (idx < 0) return;
03300 
03301   unsigned int i;
03302   for ( i = 0; i < mAtmItemList.count(); ++i )
03303       if ( mAtmItemList.at( i )->itemPos() == idx )
03304           break;
03305 
03306   if ( i > mAtmItemList.count() )
03307       return;
03308 
03309   KMMessagePart* msgPart;
03310   msgPart = mAtmList.at( i );
03311 
03312   QBuffer dev( msgPart->bodyDecodedBinary() );
03313   KZip zip( &dev );
03314   QByteArray decoded;
03315 
03316   decoded = msgPart->bodyDecodedBinary();
03317   if ( ! zip.open( IO_ReadOnly ) ) {
03318     KMessageBox::sorry(0, i18n("KMail could not uncompress the file.") );
03319     static_cast<KMAtmListViewItem *>( mAtmItemList.at( i ) )->setCompress( true );
03320     return;
03321   }
03322   const KArchiveDirectory *dir = zip.directory();
03323 
03324   KZipFileEntry *entry;
03325   if ( dir->entries().count() != 1 ) {
03326     KMessageBox::sorry(0, i18n("KMail could not uncompress the file.") );
03327     static_cast<KMAtmListViewItem *>( mAtmItemList.at( i ) )->setCompress( true );
03328     return;
03329   }
03330   entry = (KZipFileEntry*)dir->entry( dir->entries()[0] );
03331 
03332   msgPart->setCteStr(
03333       static_cast<KMAtmListViewItem*>( mAtmItemList.at(i) )->uncompressedCodec() );
03334 
03335   msgPart->setBodyEncodedBinary( entry->data() );
03336   QString name = entry->name();
03337   msgPart->setName( name );
03338 
03339   zip.close();
03340 
03341   QCString cDisp = "attachment;";
03342   QCString encoding = KMMsgBase::autoDetectCharset( msgPart->charset(),
03343     KMMessage::preferredCharsets(), name );
03344   if ( encoding.isEmpty() ) encoding = "utf-8";
03345 
03346   QCString encName;
03347   if ( GlobalSettings::self()->outlookCompatibleAttachments() )
03348     encName = KMMsgBase::encodeRFC2047String( name, encoding );
03349   else
03350     encName = KMMsgBase::encodeRFC2231String( name, encoding );
03351 
03352   cDisp += "\n\tfilename";
03353   if ( name != QString( encName ) )
03354     cDisp += "*=" + encName;
03355   else
03356     cDisp += "=\"" + encName + '"';
03357   msgPart->setContentDisposition( cDisp );
03358 
03359   QCString type, subtype;
03360   static_cast<KMAtmListViewItem*>( mAtmItemList.at( i ) )->uncompressedMimeType( type,
03361         subtype );
03362 
03363   msgPart->setTypeStr( type );
03364   msgPart->setSubtypeStr( subtype );
03365 
03366   KMAtmListViewItem* listItem = static_cast<KMAtmListViewItem*>(mAtmItemList.at( i ));
03367   msgPartToItem( msgPart, listItem, false );
03368 }
03369 
03370 
03371 //-----------------------------------------------------------------------------
03372 void KMComposeWin::slotAttachView()
03373 {
03374   int i = 0;
03375   for ( QPtrListIterator<QListViewItem> it(mAtmItemList); *it; ++it, ++i ) {
03376     if ( (*it)->isSelected() ) {
03377       viewAttach( i );
03378     }
03379   }
03380 }
03381 //-----------------------------------------------------------------------------
03382 void KMComposeWin::slotAttachOpen()
03383 {
03384   int i = 0;
03385   for ( QPtrListIterator<QListViewItem> it(mAtmItemList); *it; ++it, ++i ) {
03386     if ( (*it)->isSelected() ) {
03387       openAttach( i, false );
03388     }
03389   }
03390 }
03391 
03392 //-----------------------------------------------------------------------------
03393 void KMComposeWin::slotAttachOpenWith()
03394 {
03395   int i = 0;
03396   for ( QPtrListIterator<QListViewItem> it(mAtmItemList); *it; ++it, ++i ) {
03397     if ( (*it)->isSelected() ) {
03398       openAttach( i, true );
03399     }
03400   }
03401 }
03402 
03403 void KMComposeWin::slotAttachEdit()
03404 {
03405   int i = 0;
03406   for ( QPtrListIterator<QListViewItem> it(mAtmItemList); *it; ++it, ++i ) {
03407     if ( (*it)->isSelected() ) {
03408       editAttach( i, false );
03409     }
03410   }
03411 }
03412 
03413 void KMComposeWin::slotAttachEditWith()
03414 {
03415   int i = 0;
03416   for ( QPtrListIterator<QListViewItem> it(mAtmItemList); *it; ++it, ++i ) {
03417     if ( (*it)->isSelected() ) {
03418       editAttach( i, true );
03419     }
03420   }
03421 }
03422 
03423 //-----------------------------------------------------------------------------
03424 bool KMComposeWin::inlineSigningEncryptionSelected() {
03425   if ( !mSignAction->isChecked() && !mEncryptAction->isChecked() )
03426     return false;
03427   return cryptoMessageFormat() == Kleo::InlineOpenPGPFormat;
03428 }
03429 
03430 //-----------------------------------------------------------------------------
03431 void KMComposeWin::viewAttach( int index )
03432 {
03433   QString pname;
03434   KMMessagePart* msgPart;
03435   msgPart = mAtmList.at(index);
03436   pname = msgPart->name().stripWhiteSpace();
03437   if (pname.isEmpty()) pname=msgPart->contentDescription();
03438   if (pname.isEmpty()) pname="unnamed";
03439 
03440   KTempFile* atmTempFile = new KTempFile();
03441   mAtmTempList.append( atmTempFile );
03442   atmTempFile->setAutoDelete( true );
03443   KPIM::kByteArrayToFile(msgPart->bodyDecodedBinary(), atmTempFile->name(), false, false,
03444     false);
03445   KMReaderMainWin *win = new KMReaderMainWin(msgPart, false,
03446     atmTempFile->name(), pname, mCharset );
03447   win->show();
03448 }
03449 
03450 //-----------------------------------------------------------------------------
03451 void KMComposeWin::openAttach( int index, bool with )
03452 {
03453   KMMessagePart* msgPart = mAtmList.at(index);
03454   const QString contentTypeStr =
03455     ( msgPart->typeStr() + '/' + msgPart->subtypeStr() ).lower();
03456 
03457   KMimeType::Ptr mimetype;
03458   mimetype = KMimeType::mimeType( contentTypeStr );
03459 
03460   KTempFile* atmTempFile = new KTempFile();
03461   mAtmTempList.append( atmTempFile );
03462   const bool autoDelete = true;
03463   atmTempFile->setAutoDelete( autoDelete );
03464 
03465   KURL url;
03466   url.setPath( atmTempFile->name() );
03467 
03468   KPIM::kByteArrayToFile( msgPart->bodyDecodedBinary(), atmTempFile->name(), false, false,
03469     false );
03470   if ( ::chmod( QFile::encodeName( atmTempFile->name() ), S_IRUSR ) != 0) {
03471     QFile::remove(url.path());
03472     return;
03473   }
03474 
03475   KService::Ptr offer =
03476     KServiceTypeProfile::preferredService( mimetype->name(), "Application" );
03477 
03478   if ( with || !offer || mimetype->name() == "application/octet-stream" ) {
03479     if ( ( !KRun::displayOpenWithDialog( url, autoDelete ) ) && autoDelete ) {
03480       QFile::remove(url.path());
03481     }
03482   }
03483   else {
03484     if ( ( !KRun::run( *offer, url, autoDelete ) ) && autoDelete ) {
03485         QFile::remove( url.path() );
03486     }
03487   }
03488 }
03489 
03490 void KMComposeWin::editAttach(int index, bool openWith)
03491 {
03492   KMMessagePart* msgPart = mAtmList.at(index);
03493   const QString contentTypeStr =
03494     ( msgPart->typeStr() + '/' + msgPart->subtypeStr() ).lower();
03495 
03496   KTempFile* atmTempFile = new KTempFile();
03497   mAtmTempList.append( atmTempFile );
03498   atmTempFile->setAutoDelete( true );
03499   atmTempFile->file()->writeBlock( msgPart->bodyDecodedBinary() );
03500   atmTempFile->file()->flush();
03501 
03502 
03503   KMail::EditorWatcher *watcher =
03504           new KMail::EditorWatcher( KURL( atmTempFile->name() ), contentTypeStr, openWith,
03505                                     this, this );
03506   connect( watcher, SIGNAL(editDone(KMail::EditorWatcher*)), SLOT(slotEditDone(KMail::EditorWatcher*)) );
03507   if ( watcher->start() ) {
03508     mEditorMap.insert( watcher, msgPart );
03509     mEditorTempFiles.insert( watcher, atmTempFile );
03510   }
03511 }
03512 
03513 //-----------------------------------------------------------------------------
03514 void KMComposeWin::slotAttachSave()
03515 {
03516   KMMessagePart* msgPart;
03517   QString fileName, pname;
03518   int idx = currentAttachmentNum();
03519 
03520   if (idx < 0) return;
03521 
03522   msgPart = mAtmList.at(idx);
03523   pname = msgPart->name();
03524   if (pname.isEmpty()) pname="unnamed";
03525 
03526   KURL url = KFileDialog::getSaveURL(QString::null, QString::null, 0, i18n("Save Attachment As"));
03527 
03528   if( url.isEmpty() )
03529     return;
03530 
03531   kmkernel->byteArrayToRemoteFile(msgPart->bodyDecodedBinary(), url);
03532 }
03533 
03534 
03535 //-----------------------------------------------------------------------------
03536 void KMComposeWin::slotAttachRemove()
03537 {
03538   bool attachmentRemoved = false;
03539   int i = 0;
03540   for ( QPtrListIterator<QListViewItem> it(mAtmItemList); *it; ) {
03541     if ( (*it)->isSelected() ) {
03542       removeAttach( i );
03543       attachmentRemoved = true;
03544     }
03545     else {
03546       ++it;
03547       ++i;
03548     }
03549   }
03550 
03551   if ( attachmentRemoved ) {
03552     setModified( true );
03553     slotUpdateAttachActions();
03554   }
03555 }
03556 
03557 //-----------------------------------------------------------------------------
03558 void KMComposeWin::slotFind()
03559 {
03560   mEditor->search();
03561 }
03562 
03563 void KMComposeWin::slotSearchAgain()
03564 {
03565   mEditor->repeatSearch();
03566 }
03567 
03568 //-----------------------------------------------------------------------------
03569 void KMComposeWin::slotReplace()
03570 {
03571   mEditor->replace();
03572 }
03573 
03574 //-----------------------------------------------------------------------------
03575 void KMComposeWin::slotUpdateFont()
03576 {
03577   kdDebug() << "KMComposeWin::slotUpdateFont " << endl;
03578   if ( ! mFixedFontAction ) {
03579     return;
03580   }
03581   mEditor->setFont( mFixedFontAction->isChecked() ? mFixedFont : mBodyFont );
03582 }
03583 
03584 QString KMComposeWin::quotePrefixName() const
03585 {
03586     if ( !msg() )
03587         return QString::null;
03588 
03589     int languageNr = GlobalSettings::self()->replyCurrentLanguage();
03590     ReplyPhrases replyPhrases( QString::number(languageNr) );
03591     replyPhrases.readConfig();
03592     QString quotePrefix = msg()->formatString(
03593                  replyPhrases.indentPrefix() );
03594 
03595     quotePrefix = msg()->formatString(quotePrefix);
03596     return quotePrefix;
03597 }
03598 
03599 void KMComposeWin::slotPasteClipboardAsQuotation()
03600 {
03601     if( mEditor->hasFocus() && msg() )
03602     {
03603         QString s = QApplication::clipboard()->text();
03604         if (!s.isEmpty())
03605             mEditor->insert(addQuotesToText(s));
03606     }
03607 }
03608 
03609 void KMComposeWin::slotPasteClipboardAsAttachment()
03610 {
03611   KURL url( QApplication::clipboard()->text( QClipboard::Clipboard ) );
03612   if ( url.isValid() ) {
03613     addAttach(QApplication::clipboard()->text( QClipboard::Clipboard ) );
03614     return;
03615   }
03616 
03617   QMimeSource *mimeSource = QApplication::clipboard()->data();
03618   if ( QImageDrag::canDecode(mimeSource) ) {
03619     slotAttachPNGImageData(mimeSource->encodedData("image/png"));
03620   }
03621   else {
03622     bool ok;
03623     QString attName = KInputDialog::getText( "KMail", i18n("Name of the attachment:"), QString::null, &ok, this );
03624     if ( !ok )
03625       return;
03626     KMMessagePart *msgPart = new KMMessagePart;
03627     msgPart->setName(attName);
03628     QValueList<int> dummy;
03629     msgPart->setBodyAndGuessCte(QCString(QApplication::clipboard()->text().latin1()), dummy,
03630                                 kmkernel->msgSender()->sendQuotedPrintable());
03631     addAttach(msgPart);
03632   }
03633 }
03634 
03635 void KMComposeWin::slotAddQuotes()
03636 {
03637     if( mEditor->hasFocus() && msg() )
03638     {
03639         // TODO: I think this is backwards.
03640         // i.e, if no region is marked then add quotes to every line
03641         // else add quotes only on the lines that are marked.
03642 
03643         if ( mEditor->hasMarkedText() ) {
03644             QString s = mEditor->markedText();
03645             if(!s.isEmpty())
03646                 mEditor->insert(addQuotesToText(s));
03647         } else {
03648             int l =  mEditor->currentLine();
03649             int c =  mEditor->currentColumn();
03650             QString s =  mEditor->textLine(l);
03651             s.prepend(quotePrefixName());
03652             mEditor->insertLine(s,l);
03653             mEditor->removeLine(l+1);
03654             mEditor->setCursorPosition(l,c+2);
03655         }
03656     }
03657 }
03658 
03659 QString KMComposeWin::addQuotesToText(const QString &inputText)
03660 {
03661     QString answer = QString( inputText );
03662     QString indentStr = quotePrefixName();
03663     answer.replace( '\n', '\n' + indentStr);
03664     answer.prepend( indentStr );
03665     answer += '\n';
03666     return KMMessage::smartQuote( answer, GlobalSettings::self()->lineWrapWidth() );
03667 }
03668 
03669 QString KMComposeWin::removeQuotesFromText(const QString &inputText)
03670 {
03671     QString s = inputText;
03672 
03673     // remove first leading quote
03674     QString quotePrefix = '^' + quotePrefixName();
03675     QRegExp rx(quotePrefix);
03676     s.remove(rx);
03677 
03678     // now remove all remaining leading quotes
03679     quotePrefix = '\n' + quotePrefixName();
03680     rx = quotePrefix;
03681     s.replace(rx, "\n");
03682 
03683     return s;
03684 }
03685 
03686 void KMComposeWin::slotRemoveQuotes()
03687 {
03688     if( mEditor->hasFocus() && msg() )
03689     {
03690         // TODO: I think this is backwards.
03691         // i.e, if no region is marked then remove quotes from every line
03692         // else remove quotes only on the lines that are marked.
03693 
03694         if ( mEditor->hasMarkedText() ) {
03695             QString s = mEditor->markedText();
03696             mEditor->insert(removeQuotesFromText(s));
03697         } else {
03698             int l = mEditor->currentLine();
03699             int c = mEditor->currentColumn();
03700             QString s = mEditor->textLine(l);
03701             mEditor->insertLine(removeQuotesFromText(s),l);
03702             mEditor->removeLine(l+1);
03703             mEditor->setCursorPosition(l,c-2);
03704         }
03705     }
03706 }
03707 
03708 //-----------------------------------------------------------------------------
03709 void KMComposeWin::slotUndo()
03710 {
03711   QWidget* fw = focusWidget();
03712   if (!fw) return;
03713 
03714   if ( ::qt_cast<KEdit*>(fw) )
03715       static_cast<QTextEdit*>(fw)->undo();
03716   else if (::qt_cast<QLineEdit*>(fw))
03717       static_cast<QLineEdit*>(fw)->undo();
03718 }
03719 
03720 void KMComposeWin::slotRedo()
03721 {
03722   QWidget* fw = focusWidget();
03723   if (!fw) return;
03724 
03725   if (::qt_cast<KEdit*>(fw))
03726       static_cast<KEdit*>(fw)->redo();
03727   else if (::qt_cast<QLineEdit*>(fw))
03728       static_cast<QLineEdit*>(fw)->redo();
03729 }
03730 
03731 //-----------------------------------------------------------------------------
03732 void KMComposeWin::slotCut()
03733 {
03734   QWidget* fw = focusWidget();
03735   if (!fw) return;
03736 
03737   if (::qt_cast<KEdit*>(fw))
03738       static_cast<KEdit*>(fw)->cut();
03739   else if (::qt_cast<QLineEdit*>(fw))
03740       static_cast<QLineEdit*>(fw)->cut();
03741 }
03742 
03743 
03744 //-----------------------------------------------------------------------------
03745 void KMComposeWin::slotCopy()
03746 {
03747   QWidget* fw = focusWidget();
03748   if (!fw) return;
03749 
03750 #ifdef KeyPress
03751 #undef KeyPress
03752 #endif
03753 
03754   QKeyEvent k(QEvent::KeyPress, Key_C, 0, ControlButton);
03755   kapp->notify(fw, &k);
03756 }
03757 
03758 
03759 //-----------------------------------------------------------------------------
03760 void KMComposeWin::slotPasteClipboard()
03761 {
03762   paste( QClipboard::Clipboard );
03763 }
03764 
03765 void KMComposeWin::paste( QClipboard::Mode mode )
03766 {
03767   QWidget* fw = focusWidget();
03768   if (!fw) return;
03769 
03770   QMimeSource *mimeSource = QApplication::clipboard()->data( mode );
03771   if ( mimeSource->provides("image/png") )  {
03772     slotAttachPNGImageData(mimeSource->encodedData("image/png"));
03773   } else if ( KURLDrag::canDecode( mimeSource ) ) {
03774         KURL::List urlList;
03775         if( KURLDrag::decode( mimeSource, urlList ) ) {
03776             const QString asText = i18n("Add as Text");
03777             const QString asAttachment = i18n("Add as Attachment");
03778             const QString text = i18n("Please select whether you want to insert the content as text into the editor, "
03779                     "or append the referenced file as an attachment.");
03780             const QString caption = i18n("Paste as text or attachment?");
03781 
03782             int id = KMessageBox::questionYesNoCancel( this, text, caption,
03783                     KGuiItem( asText ), KGuiItem( asAttachment) );
03784             switch ( id) {
03785               case KMessageBox::Yes:
03786                 for ( KURL::List::Iterator it = urlList.begin();
03787                      it != urlList.end(); ++it ) {
03788                   mEditor->insert( (*it).url() );
03789                 }
03790                 break;
03791               case KMessageBox::No:
03792                 for ( KURL::List::Iterator it = urlList.begin();
03793                      it != urlList.end(); ++it ) {
03794                   addAttach( *it );
03795                 }
03796                 break;
03797             }
03798         }
03799   } else if ( QTextDrag::canDecode( mimeSource ) ) {
03800       QString s;
03801       if ( QTextDrag::decode( mimeSource, s ) )
03802           mEditor->insert( s );
03803   }
03804 }
03805 
03806 
03807 //-----------------------------------------------------------------------------
03808 void KMComposeWin::slotMarkAll()
03809 {
03810   QWidget* fw = focusWidget();
03811   if (!fw) return;
03812 
03813   if (::qt_cast<QLineEdit*>(fw))
03814       static_cast<QLineEdit*>(fw)->selectAll();
03815   else if (::qt_cast<KEdit*>(fw))
03816       static_cast<KEdit*>(fw)->selectAll();
03817 }
03818 
03819 
03820 //-----------------------------------------------------------------------------
03821 void KMComposeWin::slotClose()
03822 {
03823   close(false);
03824 }
03825 
03826 
03827 //-----------------------------------------------------------------------------
03828 void KMComposeWin::slotNewComposer()
03829 {
03830   KMComposeWin* win;
03831   KMMessage* msg = new KMMessage;
03832 
03833   msg->initHeader();
03834   win = new KMComposeWin(msg);
03835   win->show();
03836 }
03837 
03838 
03839 //-----------------------------------------------------------------------------
03840 void KMComposeWin::slotNewMailReader()
03841 {
03842   KMMainWin *kmmwin = new KMMainWin(0);
03843   kmmwin->show();
03844   //d->resize(d->size());
03845 }
03846 
03847 
03848 //-----------------------------------------------------------------------------
03849 void KMComposeWin::slotUpdWinTitle(const QString& text)
03850 {
03851   QString s( text );
03852   // Remove characters that show badly in most window decorations:
03853   // newlines tend to become boxes.
03854   if (text.isEmpty())
03855     setCaption("("+i18n("unnamed")+")");
03856   else setCaption( s.replace( QChar('\n'), ' ' ) );
03857 }
03858 
03859 
03860 //-----------------------------------------------------------------------------
03861 void KMComposeWin::slotEncryptToggled(bool on)
03862 {
03863   setEncryption( on, true /* set by the user */ );
03864   slotUpdateSignatureAndEncrypionStateIndicators();
03865 }
03866 
03867 
03868 //-----------------------------------------------------------------------------
03869 void KMComposeWin::setEncryption( bool encrypt, bool setByUser )
03870 {
03871   bool wasModified = isModified();
03872   if ( setByUser )
03873     setModified( true );
03874   if ( !mEncryptAction->isEnabled() )
03875     encrypt = false;
03876   // check if the user wants to encrypt messages to himself and if he defined
03877   // an encryption key for the current identity
03878   else if ( encrypt && encryptToSelf() && !mLastIdentityHasEncryptionKey ) {
03879     if ( setByUser ) {
03880       KMessageBox::sorry( this,
03881                           i18n("<qt><p>You have requested that messages be "
03882                    "encrypted to yourself, but the currently selected "
03883                    "identity does not define an (OpenPGP or S/MIME) "
03884                    "encryption key to use for this.</p>"
03885                                "<p>Please select the key(s) to use "
03886                                "in the identity configuration.</p>"
03887                                "</qt>"),
03888                           i18n("Undefined Encryption Key") );
03889       setModified( wasModified );
03890     }
03891     encrypt = false;
03892   }
03893 
03894   // make sure the mEncryptAction is in the right state
03895   mEncryptAction->setChecked( encrypt );
03896 
03897   // show the appropriate icon
03898   if ( encrypt )
03899     mEncryptAction->setIcon("encrypted");
03900   else
03901     mEncryptAction->setIcon("decrypted");
03902 
03903   // mark the attachments for (no) encryption
03904   if ( canSignEncryptAttachments() ) {
03905     for ( KMAtmListViewItem* entry =
03906             static_cast<KMAtmListViewItem*>( mAtmItemList.first() );
03907           entry;
03908           entry = static_cast<KMAtmListViewItem*>( mAtmItemList.next() ) )
03909       entry->setEncrypt( encrypt );
03910   }
03911 }
03912 
03913 
03914 //-----------------------------------------------------------------------------
03915 void KMComposeWin::slotSignToggled(bool on)
03916 {
03917   setSigning( on, true /* set by the user */ );
03918   slotUpdateSignatureAndEncrypionStateIndicators();
03919 }
03920 
03921 
03922 //-----------------------------------------------------------------------------
03923 void KMComposeWin::setSigning( bool sign, bool setByUser )
03924 {
03925   bool wasModified = isModified();
03926   if ( setByUser )
03927     setModified( true );
03928   if ( !mSignAction->isEnabled() )
03929     sign = false;
03930 
03931   // check if the user defined a signing key for the current identity
03932   if ( sign && !mLastIdentityHasSigningKey ) {
03933     if ( setByUser ) {
03934       KMessageBox::sorry( this,
03935                           i18n("<qt><p>In order to be able to sign "
03936                                "this message you first have to "
03937                                "define the (OpenPGP or S/MIME) signing key "
03938                    "to use.</p>"
03939                                "<p>Please select the key to use "
03940                                "in the identity configuration.</p>"
03941                                "</qt>"),
03942                           i18n("Undefined Signing Key") );
03943       setModified( wasModified );
03944     }
03945     sign = false;
03946   }
03947 
03948   // make sure the mSignAction is in the right state
03949   mSignAction->setChecked( sign );
03950 
03951   // mark the attachments for (no) signing
03952   if ( canSignEncryptAttachments() ) {
03953     for ( KMAtmListViewItem* entry =
03954             static_cast<KMAtmListViewItem*>( mAtmItemList.first() );
03955           entry;
03956           entry = static_cast<KMAtmListViewItem*>( mAtmItemList.next() ) )
03957       entry->setSign( sign );
03958   }
03959 }
03960 
03961 
03962 //-----------------------------------------------------------------------------
03963 void KMComposeWin::slotWordWrapToggled(bool on)
03964 {
03965   if (on)
03966   {
03967     mEditor->setWordWrap( QTextEdit::FixedColumnWidth );
03968     mEditor->setWrapColumnOrWidth( GlobalSettings::self()->lineWrapWidth() );
03969   }
03970   else
03971   {
03972     mEditor->setWordWrap( QTextEdit::WidgetWidth );
03973   }
03974 }
03975 
03976 
03977 void KMComposeWin::disableWordWrap()
03978 {
03979     mEditor->setWordWrap( QTextEdit::NoWrap );
03980 }
03981 
03982 void KMComposeWin::disableRecipientNumberCheck()
03983 {
03984   mCheckForRecipients = false;
03985 }
03986 
03987 //-----------------------------------------------------------------------------
03988 void KMComposeWin::slotPrint()
03989 {
03990   mMessageWasModified = isModified();
03991   connect( this, SIGNAL( applyChangesDone( bool ) ),
03992            this, SLOT( slotContinuePrint( bool ) ) );
03993   applyChanges( true );
03994 }
03995 
03996 void KMComposeWin::slotContinuePrint( bool rc )
03997 {
03998   disconnect( this, SIGNAL( applyChangesDone( bool ) ),
03999               this, SLOT( slotContinuePrint( bool ) ) );
04000 
04001   if( rc ) {
04002     if ( mComposedMessages.isEmpty() ) {
04003       kdDebug(5006) << "Composing the message failed." << endl;
04004       return;
04005     }
04006     KMCommand *command = new KMPrintCommand( this, mComposedMessages.first() );
04007     command->start();
04008     setModified( mMessageWasModified );
04009   }
04010 }
04011 
04012 //----------------------------------------------------------------------------
04013 bool KMComposeWin::validateAddresses( QWidget * parent, const QString & addresses )
04014 {
04015   QString brokenAddress;
04016   KPIM::EmailParseResult errorCode = KMMessage::isValidEmailAddressList( KMMessage::expandAliases( addresses ), brokenAddress );
04017   if ( !( errorCode == KPIM::AddressOk || errorCode == KPIM::AddressEmpty ) ) {
04018     QString errorMsg( "<qt><p><b>" + brokenAddress +
04019                       "</b></p><p>" + KPIM::emailParseResultToString( errorCode ) +
04020                       "</p></qt>" );
04021     KMessageBox::sorry( parent, errorMsg, i18n("Invalid Email Address") );
04022     return false;
04023   }
04024   return true;
04025 }
04026 
04027 //----------------------------------------------------------------------------
04028 void KMComposeWin::doSend( KMail::MessageSender::SendMethod method,
04029                            KMComposeWin::SaveIn saveIn )
04030 {
04031   if ( method != KMail::MessageSender::SendLater && kmkernel->isOffline() ) {
04032     KMessageBox::information( this,
04033                               i18n("KMail is currently in offline mode,"
04034                                    "your messages will be kept in the outbox until you go online."),
04035                               i18n("Online/Offline"), "kmailIsOffline" );
04036     mSendMethod = KMail::MessageSender::SendLater;
04037   } else {
04038     mSendMethod = method;
04039   }
04040   mSaveIn = saveIn;
04041 
04042   if ( saveIn == KMComposeWin::None ) {
04043     if ( KPIM::getFirstEmailAddress( from() ).isEmpty() ) {
04044       if ( !( mShowHeaders & HDR_FROM ) ) {
04045         mShowHeaders |= HDR_FROM;
04046         rethinkFields( false );
04047       }
04048       mEdtFrom->setFocus();
04049       KMessageBox::sorry( this,
04050                           i18n("You must enter your email address in the "
04051                                "From: field. You should also set your email "
04052                                "address for all identities, so that you do "
04053                                "not have to enter it for each message.") );
04054       return;
04055     }
04056     if ( to().isEmpty() )
04057     {
04058         if (  cc().isEmpty() && bcc().isEmpty()) {
04059           if ( mEdtTo ) mEdtTo->setFocus();
04060           KMessageBox::information( this,
04061                                 i18n("You must specify at least one receiver,"
04062                                      "either in the To: field or as CC or as BCC.") );
04063           return;
04064         }
04065         else {
04066                 if ( mEdtTo ) mEdtTo->setFocus();
04067                 int rc =
04068                             KMessageBox::questionYesNo( this,
04069                                                         i18n("To field is missing."
04070                                                               "Send message anyway?"),
04071                                                         i18n("No To: specified") );
04072                 if ( rc == KMessageBox::No ){
04073                    return;
04074                 }
04075         }
04076     }
04077 
04078     // Validate the To:, CC: and BCC fields
04079     if ( !validateAddresses( this, to().stripWhiteSpace() ) ) {
04080       return;
04081     }
04082 
04083     if ( !validateAddresses( this, cc().stripWhiteSpace() ) ) {
04084       return;
04085     }
04086 
04087     if ( !validateAddresses( this, bcc().stripWhiteSpace() ) ) {
04088       return;
04089     }
04090 
04091     if (subject().isEmpty())
04092     {
04093         mEdtSubject->setFocus();
04094         int rc =
04095           KMessageBox::questionYesNo( this,
04096                                       i18n("You did not specify a subject. "
04097                                            "Send message anyway?"),
04098                                       i18n("No Subject Specified"),
04099                                       i18n("S&end as Is"),
04100                                       i18n("&Specify the Subject"),
04101                                       "no_subject_specified" );
04102         if( rc == KMessageBox::No )
04103         {
04104            return;
04105         }
04106     }
04107 
04108     if ( userForgotAttachment() )
04109       return;
04110   }
04111 
04112   KCursorSaver busy(KBusyPtr::busy());
04113   mMsg->setDateToday();
04114 
04115   // If a user sets up their outgoing messages preferences wrong and then
04116   // sends mail that gets 'stuck' in their outbox, they should be able to
04117   // rectify the problem by editing their outgoing preferences and
04118   // resending.
04119   // Hence this following conditional
04120   QString hf = mMsg->headerField("X-KMail-Transport");
04121   if ((mTransport->currentText() != mTransport->text(0)) ||
04122       (!hf.isEmpty() && (hf != mTransport->text(0))))
04123     mMsg->setHeaderField("X-KMail-Transport", mTransport->currentText());
04124 
04125   mDisableBreaking = ( saveIn != KMComposeWin::None );
04126 
04127   const bool neverEncrypt = ( mDisableBreaking && GlobalSettings::self()->neverEncryptDrafts() )
04128                            || mSigningAndEncryptionExplicitlyDisabled;
04129   connect( this, SIGNAL( applyChangesDone( bool ) ),
04130            SLOT( slotContinueDoSend( bool ) ) );
04131 
04132   if ( mEditor->textFormat() == Qt::RichText )
04133     mMsg->setHeaderField( "X-KMail-Markup", "true" );
04134   else
04135     mMsg->removeHeaderField( "X-KMail-Markup" );
04136   if ( mEditor->textFormat() == Qt::RichText && inlineSigningEncryptionSelected() ) {
04137     QString keepBtnText = mEncryptAction->isChecked() ?
04138       mSignAction->isChecked() ? i18n( "&Keep markup, do not sign/encrypt" )
04139                                : i18n( "&Keep markup, do not encrypt" )
04140       : i18n( "&Keep markup, do not sign" );
04141     QString yesBtnText = mEncryptAction->isChecked() ?
04142       mSignAction->isChecked() ? i18n("Sign/Encrypt (delete markup)")
04143       : i18n( "Encrypt (delete markup)" )
04144       : i18n( "Sign (delete markup)" );
04145     int ret = KMessageBox::warningYesNoCancel(this,
04146                                       i18n("<qt><p>Inline signing/encrypting of HTML messages is not possible;</p>"
04147                                            "<p>do you want to delete your markup?</p></qt>"),
04148                                            i18n("Sign/Encrypt Message?"),
04149                                            KGuiItem( yesBtnText ),
04150                                            KGuiItem( keepBtnText ) );
04151     if ( KMessageBox::Cancel == ret )
04152       return;
04153     if ( KMessageBox::No == ret ) {
04154       mEncryptAction->setChecked(false);
04155       mSignAction->setChecked(false);
04156     }
04157     else {
04158       toggleMarkup(false);
04159     }
04160   }
04161 
04162   if (neverEncrypt && saveIn != KMComposeWin::None ) {
04163       // we can't use the state of the mail itself, to remember the
04164       // signing and encryption state, so let's add a header instead
04165     mMsg->setHeaderField( "X-KMail-SignatureActionEnabled", mSignAction->isChecked()? "true":"false" );
04166     mMsg->setHeaderField( "X-KMail-EncryptActionEnabled", mEncryptAction->isChecked()? "true":"false"  );
04167     mMsg->setHeaderField( "X-KMail-CryptoMessageFormat", QString::number( cryptoMessageFormat() ) );
04168   } else {
04169     mMsg->removeHeaderField( "X-KMail-SignatureActionEnabled" );
04170     mMsg->removeHeaderField( "X-KMail-EncryptActionEnabled" );
04171     mMsg->removeHeaderField( "X-KMail-CryptoMessageFormat" );
04172   }
04173 
04174 
04175   kdDebug(5006) << "KMComposeWin::doSend() - calling applyChanges()"
04176                 << endl;
04177   applyChanges( neverEncrypt );
04178 }
04179 
04180 bool KMComposeWin::saveDraftOrTemplate( const QString &folderName,
04181                                         KMMessage *msg )
04182 {
04183   KMFolder *theFolder = 0, *imapTheFolder = 0;
04184   // get the draftsFolder
04185   if ( !folderName.isEmpty() ) {
04186     theFolder = kmkernel->folderMgr()->findIdString( folderName );
04187     if ( theFolder == 0 )
04188       // This is *NOT* supposed to be "imapDraftsFolder", because a
04189       // dIMAP folder works like a normal folder
04190       theFolder = kmkernel->dimapFolderMgr()->findIdString( folderName );
04191     if ( theFolder == 0 )
04192       imapTheFolder = kmkernel->imapFolderMgr()->findIdString( folderName );
04193     if ( !theFolder && !imapTheFolder ) {
04194       const KPIM::Identity & id = kmkernel->identityManager()
04195         ->identityForUoidOrDefault( msg->headerField( "X-KMail-Identity" ).stripWhiteSpace().toUInt() );
04196       KMessageBox::information( 0,
04197                                 i18n("The custom drafts or templates folder for "
04198                                      "identify \"%1\" does not exist (anymore); "
04199                                      "therefore, the default drafts or templates "
04200                                      "folder will be used.")
04201                                 .arg( id.identityName() ) );
04202     }
04203   }
04204   if ( imapTheFolder && imapTheFolder->noContent() )
04205     imapTheFolder = 0;
04206 
04207   bool didOpen = false;
04208   if ( theFolder == 0 ) {
04209     theFolder = ( mSaveIn==KMComposeWin::Drafts ?
04210                   kmkernel->draftsFolder() : kmkernel->templatesFolder() );
04211   } else {
04212     //XXX this looks really, really fishy
04213     theFolder->open( "composer" );
04214     didOpen = true;
04215   }
04216   kdDebug(5006) << k_funcinfo << "theFolder=" << theFolder->name() << endl;
04217   if ( imapTheFolder )
04218     kdDebug(5006) << k_funcinfo << "imapTheFolder=" << imapTheFolder->name() << endl;
04219 
04220   bool sentOk = !( theFolder->addMsg( msg ) );
04221 
04222   // Ensure the message is correctly and fully parsed
04223   theFolder->unGetMsg( theFolder->count() - 1 );
04224   msg = theFolder->getMsg( theFolder->count() - 1 );
04225   // Does that assignment needs to be propagated out to the caller?
04226   // Assuming the send is OK, the iterator is set to 0 immediately afterwards.
04227   if ( imapTheFolder ) {
04228     // move the message to the imap-folder and highlight it
04229     imapTheFolder->moveMsg( msg );
04230     (static_cast<KMFolderImap*>( imapTheFolder->storage() ))->getFolder();
04231   }
04232 
04233   if ( didOpen )
04234     theFolder->close( "composer" );
04235   return sentOk;
04236 }
04237 
04238 void KMComposeWin::slotContinueDoSend( bool sentOk )
04239 {
04240   kdDebug(5006) << "KMComposeWin::slotContinueDoSend( " << sentOk << " )"
04241                 << endl;
04242   disconnect( this, SIGNAL( applyChangesDone( bool ) ),
04243               this, SLOT( slotContinueDoSend( bool ) ) );
04244 
04245   if ( !sentOk ) {
04246     mDisableBreaking = false;
04247     return;
04248   }
04249 
04250   for ( QValueVector<KMMessage*>::iterator it = mComposedMessages.begin() ; it != mComposedMessages.end() ; ++it ) {
04251 
04252     // remove fields that contain no data (e.g. an empty Cc: or Bcc:)
04253     (*it)->cleanupHeader();
04254 
04255     // needed for imap
04256     (*it)->setComplete( true );
04257 
04258     if ( mSaveIn==KMComposeWin::Drafts ) {
04259       sentOk = saveDraftOrTemplate( (*it)->drafts(), (*it) );
04260     } else if ( mSaveIn==KMComposeWin::Templates ) {
04261       sentOk = saveDraftOrTemplate( (*it)->templates(), (*it) );
04262     } else {
04263       (*it)->setTo( KMMessage::expandAliases( to() ));
04264       (*it)->setCc( KMMessage::expandAliases( cc() ));
04265       if( !mComposer->originalBCC().isEmpty() )
04266     (*it)->setBcc( KMMessage::expandAliases( mComposer->originalBCC() ));
04267       QString recips = (*it)->headerField( "X-KMail-Recipients" );
04268       if( !recips.isEmpty() ) {
04269     (*it)->setHeaderField( "X-KMail-Recipients", KMMessage::expandAliases( recips ), KMMessage::Address );
04270       }
04271       (*it)->cleanupHeader();
04272       sentOk = kmkernel->msgSender()->send((*it), mSendMethod);
04273     }
04274 
04275     if (!sentOk)
04276       return;
04277 
04278     *it = 0; // don't kill it later...
04279   }
04280 
04281   RecentAddresses::self( KMKernel::config() )->add( bcc() );
04282   RecentAddresses::self( KMKernel::config() )->add( cc() );
04283   RecentAddresses::self( KMKernel::config() )->add( to() );
04284 
04285   setModified( false );
04286   mAutoDeleteMsg = false;
04287   mFolder = 0;
04288   cleanupAutoSave();
04289   close();
04290   return;
04291 }
04292 
04293 bool KMComposeWin::checkTransport() const
04294 {
04295   if ( KMail::TransportManager::transportNames().isEmpty() ) {
04296     KMessageBox::information( mMainWidget,
04297                               i18n("Please create an account for sending and try again.") );
04298     return false;
04299   }
04300   return true;
04301 
04302 }
04303 
04304 //----------------------------------------------------------------------------
04305 void KMComposeWin::slotSendLater()
04306 {
04307   if ( !checkTransport() )
04308     return;
04309   if ( !checkRecipientNumber() )
04310     return;
04311   if ( mEditor->checkExternalEditorFinished() )
04312     doSend( KMail::MessageSender::SendLater );
04313 }
04314 
04315 
04316 //----------------------------------------------------------------------------
04317 void KMComposeWin::slotSaveDraft() {
04318   if ( mEditor->checkExternalEditorFinished() )
04319     doSend( KMail::MessageSender::SendLater, KMComposeWin::Drafts );
04320 }
04321 
04322 //----------------------------------------------------------------------------
04323 void KMComposeWin::slotSaveTemplate() {
04324   if ( mEditor->checkExternalEditorFinished() )
04325     doSend( KMail::MessageSender::SendLater, KMComposeWin::Templates );
04326 }
04327 
04328 //----------------------------------------------------------------------------
04329 void KMComposeWin::slotSendNowVia( int item )
04330 {
04331   QStringList availTransports= KMail::TransportManager::transportNames();
04332   QString customTransport = availTransports[ item ];
04333 
04334   mTransport->setCurrentText( customTransport );
04335   slotSendNow();
04336 }
04337 
04338 //----------------------------------------------------------------------------
04339 void KMComposeWin::slotSendLaterVia( int item )
04340 {
04341   QStringList availTransports= KMail::TransportManager::transportNames();
04342   QString customTransport = availTransports[ item ];
04343 
04344   mTransport->setCurrentText( customTransport );
04345   slotSendLater();
04346 }
04347 
04348 
04349 //----------------------------------------------------------------------------
04350 void KMComposeWin::slotSendNow() {
04351   if ( !mEditor->checkExternalEditorFinished() )
04352     return;
04353   if ( !checkTransport() )
04354     return;
04355   if ( !checkRecipientNumber() )
04356     return;
04357   if ( GlobalSettings::self()->confirmBeforeSend() )
04358   {
04359     int rc = KMessageBox::warningYesNoCancel( mMainWidget,
04360                                         i18n("About to send email..."),
04361                                         i18n("Send Confirmation"),
04362                                         i18n("&Send Now"),
04363                                         i18n("Send &Later") );
04364 
04365     if ( rc == KMessageBox::Yes )
04366       doSend( KMail::MessageSender::SendImmediate );
04367     else if ( rc == KMessageBox::No )
04368       doSend( KMail::MessageSender::SendLater );
04369   }
04370   else
04371     doSend( KMail::MessageSender::SendImmediate );
04372 }
04373 
04374 
04375 //----------------------------------------------------------------------------
04376 bool KMComposeWin::checkRecipientNumber() const
04377 {
04378   int thresHold = GlobalSettings::self()->recipientThreshold();
04379   if ( mCheckForRecipients &&
04380        GlobalSettings::self()->tooManyRecipients() &&
04381        mRecipientsEditor->recipients().count() > thresHold ) {
04382     if ( KMessageBox::questionYesNo( mMainWidget,
04383                                i18n("You are trying to send the mail to more than %1 recipients. Send message anyway?").arg(thresHold),
04384                                i18n("Too many receipients"),
04385                                i18n("&Send as Is"),
04386                                i18n("&Edit Recipients")) == KMessageBox::No ) {
04387       return false;
04388     }
04389   }
04390   return true;
04391 }
04392 
04393 
04394 //----------------------------------------------------------------------------
04395 void KMComposeWin::slotAppendSignature()
04396 {
04397     insertSignature();
04398 }
04399 
04400 //----------------------------------------------------------------------------
04401 void KMComposeWin::slotPrependSignature()
04402 {
04403     insertSignature( false );
04404 }
04405 
04406 //----------------------------------------------------------------------------
04407 void KMComposeWin::slotInsertSignatureAtCursor()
04408 {
04409     insertSignature( false, mEditor->currentLine() );
04410 }
04411 
04412 //----------------------------------------------------------------------------
04413 void KMComposeWin::insertSignature( bool append, int pos )
04414 {
04415    bool mod = mEditor->isModified();
04416 
04417    const KPIM::Identity &ident =
04418      kmkernel->identityManager()->
04419      identityForUoidOrDefault( mIdentity->currentIdentity() );
04420 
04421    mOldSigText = GlobalSettings::self()->prependSignature()? ident.signature().rawText() : ident.signatureText();
04422 
04423    if( !mOldSigText.isEmpty() )
04424    {
04425       mEditor->sync();
04426       if ( append ) {
04427          mEditor->setText( mEditor->text() + mOldSigText );
04428     } else {
04429        mOldSigText = "\n\n"+mOldSigText+"\n";
04430        mEditor->insertAt(mOldSigText, pos, 0);
04431     }
04432     mEditor->update();
04433     mEditor->setModified(mod);
04434 
04435     if (  mPreserveUserCursorPosition ) {
04436       mEditor->setCursorPositionFromStart( (unsigned int) mMsg->getCursorPos() );
04437       // Only keep the cursor from the mMsg *once* based on the
04438       // preserve-cursor-position setting; this handles the case where
04439       // the message comes from a template with a specific cursor
04440       // position set and the signature is appended automatically.
04441       mPreserveUserCursorPosition = false;
04442     } else {
04443       // for append and prepend, move the cursor to 0,0, for insertAt,
04444       // keep it in the same row, but move to first column
04445       mEditor->setCursorPosition( pos, 0 );
04446       if ( !append && pos == 0 )
04447         mEditor->setContentsPos( 0, 0 );
04448     }
04449     mEditor->sync();
04450   }
04451 }
04452 
04453 //-----------------------------------------------------------------------------
04454 void KMComposeWin::slotHelp()
04455 {
04456   kapp->invokeHelp();
04457 }
04458 
04459 //-----------------------------------------------------------------------------
04460 void KMComposeWin::slotCleanSpace()
04461 {
04462   // Originally we simply used the KEdit::cleanWhiteSpace() method,
04463   // but that code doesn't handle quoted-lines or signatures, so instead
04464   // we now simply use regexp's to squeeze sequences of tabs and spaces
04465   // into a single space, and make sure all our lines are single-spaced.
04466   //
04467   // Yes, extra space in a quote string is squeezed.
04468   // Signatures are respected (i.e. not cleaned).
04469 
04470   QString s;
04471   if ( mEditor->hasMarkedText() ) {
04472     s = mEditor->markedText();
04473     if( s.isEmpty() )
04474       return;
04475   } else {
04476     s = mEditor->text();
04477   }
04478 
04479   // Remove the signature for now.
04480   QString sig;
04481   bool restore = false;
04482   const KPIM::Identity & ident =
04483     kmkernel->identityManager()->identityForUoid( mId );
04484   if ( !ident.isNull() ) {
04485     sig = ident.signatureText();
04486     if( !sig.isEmpty() ) {
04487       if( s.endsWith( sig ) ) {
04488         s.truncate( s.length() - sig.length() );
04489         restore = true;
04490       }
04491     }
04492   }
04493 
04494   // Squeeze tabs and spaces
04495   QRegExp squeeze( "[\t ]+" );
04496   s.replace( squeeze, QChar( ' ' ) );
04497 
04498   // Remove trailing whitespace
04499   QRegExp trailing( "\\s+$" );
04500   s.replace( trailing, QChar( '\n' ) );
04501 
04502   // Single space lines
04503   QRegExp singleSpace( "[\n]{2,}" );
04504   s.replace( singleSpace, QChar( '\n' ) );
04505 
04506   // Restore the signature
04507   if ( restore )
04508     s.append( sig );
04509 
04510   // Put the new text in place.
04511   // The lines below do not clear the undo history, but unfortuately cause
04512   // the side-effect that you need to press Ctrl-Z twice (first Ctrl-Z will
04513   // show cleared text area) to get back the original, pre-cleaned text.
04514   // If you use mEditor->setText( s ) then the undo history is cleared so
04515   // that isn't a good solution either.
04516   // TODO: is Qt4 better at handling the undo history??
04517   if ( !mEditor->hasMarkedText() )
04518     mEditor->clear();
04519   mEditor->insert( s );
04520 }
04521 
04522 //-----------------------------------------------------------------------------
04523 void KMComposeWin::slotToggleMarkup()
04524 {
04525  if ( markupAction->isChecked() ) {
04526     mHtmlMarkup = true;
04527     toolBar("htmlToolBar")->show();
04528    // markup will be toggled as soon as markup is actually used
04529    fontChanged( mEditor->currentFont() ); // set buttons in correct position
04530    mSaveFont = mEditor->currentFont();
04531  }
04532  else
04533    toggleMarkup(false);
04534 
04535 }
04536 //-----------------------------------------------------------------------------
04537 void KMComposeWin::toggleMarkup(bool markup)
04538 {
04539   if ( markup ) {
04540     if ( !mUseHTMLEditor ) {
04541       kdDebug(5006) << "setting RichText editor" << endl;
04542       mUseHTMLEditor = true; // set it directly to true. setColor hits another toggleMarkup
04543       mHtmlMarkup = true;
04544 
04545       // set all highlighted text caused by spelling back to black
04546       int paraFrom, indexFrom, paraTo, indexTo;
04547       mEditor->getSelection ( &paraFrom, &indexFrom, &paraTo, &indexTo);
04548       mEditor->selectAll();
04549       // save the buttonstates because setColor calls fontChanged
04550       bool _bold = textBoldAction->isChecked();
04551       bool _italic = textItalicAction->isChecked();
04552       mEditor->setColor(QColor(0,0,0));
04553       textBoldAction->setChecked(_bold);
04554       textItalicAction->setChecked(_italic);
04555       mEditor->setSelection ( paraFrom, indexFrom, paraTo, indexTo);
04556 
04557       mEditor->setTextFormat(Qt::RichText);
04558       mEditor->setModified(true);
04559       markupAction->setChecked(true);
04560       toolBar( "htmlToolBar" )->show();
04561       mEditor->deleteAutoSpellChecking();
04562       mAutoSpellCheckingAction->setChecked(false);
04563       slotAutoSpellCheckingToggled(false);
04564     }
04565   } else { // markup is to be turned off
04566     kdDebug(5006) << "setting PlainText editor" << endl;
04567     mHtmlMarkup = false;
04568     toolBar("htmlToolBar")->hide();
04569     if ( mUseHTMLEditor ) { // it was turned on
04570       mUseHTMLEditor = false;
04571       mEditor->setTextFormat(Qt::PlainText);
04572       QString text = mEditor->text();
04573       mEditor->setText(text); // otherwise the text still looks formatted
04574       mEditor->setModified(true);
04575       slotAutoSpellCheckingToggled(true);
04576     }
04577   }
04578 }
04579 
04580 void KMComposeWin::htmlToolBarVisibilityChanged( bool visible )
04581 {
04582   // disable markup if the user hides the HTML toolbar
04583   if ( !visible ) {
04584     markupAction->setChecked( false );
04585     toggleMarkup( false );
04586   }
04587 }
04588 
04589 void KMComposeWin::slotSubjectTextSpellChecked()
04590 {
04591   mSubjectTextWasSpellChecked = true;
04592 }
04593 
04594 //-----------------------------------------------------------------------------
04595 void KMComposeWin::slotAutoSpellCheckingToggled( bool on )
04596 {
04597   if ( mEditor->autoSpellChecking(on) == -1 ) {
04598     mAutoSpellCheckingAction->setChecked(false); // set it to false again
04599   }
04600 
04601   QString temp;
04602   if ( on )
04603     temp = i18n( "Spellcheck: on" );
04604   else
04605     temp = i18n( "Spellcheck: off" );
04606   statusBar()->changeItem( temp, 3 );
04607 }
04608 //-----------------------------------------------------------------------------
04609 void KMComposeWin::slotSpellcheck()
04610 {
04611   if (mSpellCheckInProgress) return;
04612   mSubjectTextWasSpellChecked = false;
04613   mSpellCheckInProgress=true;
04614   /*
04615     connect (mEditor, SIGNAL (spellcheck_progress (unsigned)),
04616     this, SLOT (spell_progress (unsigned)));
04617     */
04618 
04619   mEditor->spellcheck();
04620 }
04621 //-----------------------------------------------------------------------------
04622 void KMComposeWin::slotUpdateSignatureActions()
04623 {
04624   //Check if an identity has signature or not and turn on/off actions in the
04625   //edit menu accordingly.
04626   const KPIM::Identity & ident =
04627     kmkernel->identityManager()->identityForUoidOrDefault( mIdentity->currentIdentity() );
04628   QString sig = ident.signatureText();
04629 
04630   if ( sig.isEmpty() ) {
04631      mAppendSignatureAction->setEnabled( false );
04632      mPrependSignatureAction->setEnabled( false );
04633      mInsertSignatureAction->setEnabled( false );
04634   }
04635   else {
04636       mAppendSignatureAction->setEnabled( true );
04637       mPrependSignatureAction->setEnabled( true );
04638       mInsertSignatureAction->setEnabled( true );
04639   }
04640 }
04641 
04642 void KMComposeWin::polish()
04643 {
04644   // Ensure the html toolbar is appropriately shown/hidden
04645   markupAction->setChecked(mHtmlMarkup);
04646   if (mHtmlMarkup)
04647     toolBar("htmlToolBar")->show();
04648   else
04649     toolBar("htmlToolBar")->hide();
04650   KMail::Composer::polish();
04651 }
04652 
04653 //-----------------------------------------------------------------------------
04654 void KMComposeWin::slotSpellcheckDone(int result)
04655 {
04656   kdDebug(5006) << "spell check complete: result = " << result << endl;
04657   mSpellCheckInProgress=false;
04658 
04659   switch( result )
04660   {
04661     case KS_CANCEL:
04662       statusBar()->changeItem(i18n(" Spell check canceled."),0);
04663       break;
04664     case KS_STOP:
04665       statusBar()->changeItem(i18n(" Spell check stopped."),0);
04666       break;
04667     default:
04668       statusBar()->changeItem(i18n(" Spell check complete."),0);
04669       break;
04670   }
04671   QTimer::singleShot( 2000, this, SLOT(slotSpellcheckDoneClearStatus()) );
04672 }
04673 
04674 void KMComposeWin::slotSpellcheckDoneClearStatus()
04675 {
04676   statusBar()->changeItem("", 0);
04677 }
04678 
04679 
04680 //-----------------------------------------------------------------------------
04681 void KMComposeWin::slotIdentityChanged( uint uoid )
04682 {
04683   const KPIM::Identity & ident =
04684     kmkernel->identityManager()->identityForUoid( uoid );
04685   if( ident.isNull() ) return;
04686 
04687   //Turn on/off signature actions if identity has no signature.
04688   slotUpdateSignatureActions();
04689 
04690   if( !ident.fullEmailAddr().isNull() )
04691     mEdtFrom->setText(ident.fullEmailAddr());
04692   // make sure the From field is shown if it does not contain a valid email address
04693   if ( KPIM::getFirstEmailAddress( from() ).isEmpty() )
04694     mShowHeaders |= HDR_FROM;
04695   if ( mEdtReplyTo ) mEdtReplyTo->setText(ident.replyToAddr());
04696 
04697   if ( mRecipientsEditor ) {
04698     // remove BCC of old identity and add BCC of new identity (if they differ)
04699     const KPIM::Identity & oldIdentity =
04700       kmkernel->identityManager()->identityForUoidOrDefault( mId );
04701     if ( oldIdentity.bcc() != ident.bcc() ) {
04702       mRecipientsEditor->removeRecipient( oldIdentity.bcc(), Recipient::Bcc );
04703       mRecipientsEditor->addRecipient( ident.bcc(), Recipient::Bcc );
04704       mRecipientsEditor->setFocusBottom();
04705     }
04706   }
04707 
04708   // don't overwrite the BCC field under certain circomstances
04709   // NOT edited and preset BCC from the identity
04710   if( mEdtBcc && !mEdtBcc->edited() && !ident.bcc().isEmpty() ) {
04711     // BCC NOT empty AND contains a diff adress then the preset BCC
04712     // of the new identity
04713     if( !mEdtBcc->text().isEmpty() && mEdtBcc->text() != ident.bcc() && !mEdtBcc->edited() ) {
04714       mEdtBcc->setText( ident.bcc() );
04715     } else {
04716       // user type into the editbox an address that != to the preset bcc
04717       // of the identity, we assume that since the user typed it
04718       // they want to keep it
04719       if ( mEdtBcc->text() != ident.bcc() && !mEdtBcc->text().isEmpty() ) {
04720         QString temp_string( mEdtBcc->text() + QString::fromLatin1(",") + ident.bcc() );
04721         mEdtBcc->setText( temp_string );
04722       } else {
04723         // if the user typed the same address as the preset BCC
04724         // from the identity we will overwrite it to avoid duplicates.
04725         mEdtBcc->setText( ident.bcc() );
04726       }
04727     }
04728   }
04729   // user edited the bcc box and has a preset bcc in the identity
04730   // we will append whatever the user typed to the preset address
04731   // allowing the user to keep all addresses
04732   if( mEdtBcc && mEdtBcc->edited() && !ident.bcc().isEmpty() ) {
04733     if( !mEdtBcc->text().isEmpty() ) {
04734       QString temp_string ( mEdtBcc->text() + QString::fromLatin1(",") + ident.bcc() );
04735       mEdtBcc->setText( temp_string );
04736     } else {
04737       mEdtBcc->setText( ident.bcc() );
04738     }
04739   }
04740   // user typed nothing and the identity does not have a preset bcc
04741   // we then reset the value to get rid of any previous
04742   // values if the user changed identity mid way through.
04743   if( mEdtBcc && !mEdtBcc->edited() && ident.bcc().isEmpty() ) {
04744     mEdtBcc->setText( ident.bcc() );
04745   }
04746   // make sure the BCC field is shown because else it's ignored
04747   if ( !ident.bcc().isEmpty() ) {
04748     mShowHeaders |= HDR_BCC;
04749   }
04750 
04751   if ( ident.organization().isEmpty() )
04752     mMsg->removeHeaderField("Organization");
04753   else
04754     mMsg->setHeaderField("Organization", ident.organization());
04755 
04756   if (!ident.isXFaceEnabled() || ident.xface().isEmpty())
04757     mMsg->removeHeaderField("X-Face");
04758   else
04759   {
04760     QString xface = ident.xface();
04761     if (!xface.isEmpty())
04762     {
04763       int numNL = ( xface.length() - 1 ) / 70;
04764       for ( int i = numNL; i > 0; --i )
04765         xface.insert( i*70, "\n\t" );
04766       mMsg->setHeaderField("X-Face", xface);
04767     }
04768   }
04769 
04770   if ( !mBtnTransport->isChecked() ) {
04771     QString transp = ident.transport();
04772     if ( transp.isEmpty() )
04773     {
04774       mMsg->removeHeaderField("X-KMail-Transport");
04775       transp = GlobalSettings::self()->defaultTransport();
04776     }
04777     else
04778       mMsg->setHeaderField("X-KMail-Transport", transp);
04779     setTransport( transp );
04780   }
04781 
04782   mDictionaryCombo->setCurrentByDictionary( ident.dictionary() );
04783 
04784   if ( !mBtnFcc->isChecked() && !mPreventFccOverwrite ) {
04785     setFcc( ident.fcc() );
04786   }
04787 
04788   QString edtText = mEditor->text();
04789 
04790   if ( mOldSigText.isEmpty() ) {
04791     const KPIM::Identity &id =
04792       kmkernel->
04793       identityManager()->
04794       identityForUoidOrDefault( mMsg->headerField( "X-KMail-Identity" ).
04795                                 stripWhiteSpace().toUInt() );
04796     mOldSigText = GlobalSettings::self()->prependSignature() ? id.signature().rawText() : id.signatureText();
04797   }
04798 
04799 
04800   if ( !GlobalSettings::prependSignature() ) {
04801     // try to truncate the old sig
04802     // First remove any trailing whitespace
04803     while ( !edtText.isEmpty() && edtText[edtText.length()-1].isSpace() )
04804       edtText.truncate( edtText.length() - 1 );
04805     // From the sig too, just in case
04806     while ( !mOldSigText.isEmpty() && mOldSigText[mOldSigText.length()-1].isSpace() )
04807       mOldSigText.truncate( mOldSigText.length() - 1 );
04808 
04809     if ( edtText.endsWith( mOldSigText ) )
04810       edtText.truncate( edtText.length() - mOldSigText.length() );
04811 
04812     // now append the new sig
04813     mOldSigText = ident.signatureText();
04814     if( ( !mOldSigText.isEmpty() ) &&
04815         ( GlobalSettings::self()->autoTextSignature() == "auto" ) ) {
04816       edtText.append( mOldSigText );
04817     }
04818     mEditor->setText( edtText );
04819   } else {
04820     const int pos = edtText.find( mOldSigText );
04821     if ( pos >= 0 && !mOldSigText.isEmpty() ) {
04822       const int oldLength = mOldSigText.length();
04823       mOldSigText = "\n\n"+ ident.signature().rawText() + "\n"; // see insertSignature()
04824       edtText = edtText.replace( pos, oldLength, mOldSigText );
04825       mEditor->setText( edtText );
04826     } else {
04827       insertSignature( false );
04828     }
04829   }
04830 
04831   // disable certain actions if there is no PGP user identity set
04832   // for this profile
04833   bool bNewIdentityHasSigningKey = !ident.pgpSigningKey().isEmpty() || !ident.smimeSigningKey().isEmpty();
04834   bool bNewIdentityHasEncryptionKey = !ident.pgpSigningKey().isEmpty() || !ident.smimeSigningKey().isEmpty();
04835   mAttachMPK->setEnabled( Kleo::CryptoBackendFactory::instance()->openpgp() &&
04836               !ident.pgpEncryptionKey().isEmpty() );
04837   // save the state of the sign and encrypt button
04838   if ( !bNewIdentityHasEncryptionKey && mLastIdentityHasEncryptionKey ) {
04839     mLastEncryptActionState = mEncryptAction->isChecked();
04840     setEncryption( false );
04841   }
04842   if ( !bNewIdentityHasSigningKey && mLastIdentityHasSigningKey ) {
04843     mLastSignActionState = mSignAction->isChecked();
04844     setSigning( false );
04845   }
04846   // restore the last state of the sign and encrypt button
04847   if ( bNewIdentityHasEncryptionKey && !mLastIdentityHasEncryptionKey )
04848       setEncryption( mLastEncryptActionState );
04849   if ( bNewIdentityHasSigningKey && !mLastIdentityHasSigningKey )
04850     setSigning( mLastSignActionState );
04851 
04852   mLastIdentityHasSigningKey = bNewIdentityHasSigningKey;
04853   mLastIdentityHasEncryptionKey = bNewIdentityHasEncryptionKey;
04854 
04855   setModified( true );
04856   mId = uoid;
04857 
04858   // make sure the From and BCC fields are shown if necessary
04859   rethinkFields( false );
04860 }
04861 
04862 //-----------------------------------------------------------------------------
04863 void KMComposeWin::slotSpellcheckConfig()
04864 {
04865   KDialogBase dlg(KDialogBase::Plain, i18n("Spellchecker"),
04866                   KDialogBase::Ok|KDialogBase::Cancel, KDialogBase::Ok,
04867                   this, 0, true, true );
04868   KWin kwin;
04869   QTabDialog qtd (this, "tabdialog", true);
04870   KSpellConfig mKSpellConfig (&qtd);
04871   mKSpellConfig.layout()->setMargin( KDialog::marginHint() );
04872 
04873   qtd.addTab (&mKSpellConfig, i18n("Spellchecker"));
04874   qtd.setCancelButton ();
04875 
04876   kwin.setIcons (qtd.winId(), kapp->icon(), kapp->miniIcon());
04877   qtd.setCancelButton(KStdGuiItem::cancel().text());
04878   qtd.setOkButton(KStdGuiItem::ok().text());
04879 
04880   if (qtd.exec())
04881     mKSpellConfig.writeGlobalSettings();
04882 }
04883 
04884 //-----------------------------------------------------------------------------
04885 void KMComposeWin::slotStatusMessage(const QString &message)
04886 {
04887     statusBar()->changeItem( message, 0 );
04888 }
04889 
04890 void KMComposeWin::slotEditToolbars()
04891 {
04892   saveMainWindowSettings(KMKernel::config(), "Composer");
04893   KEditToolbar dlg(guiFactory(), this);
04894 
04895   connect( &dlg, SIGNAL(newToolbarConfig()),
04896            SLOT(slotUpdateToolbars()) );
04897 
04898   dlg.exec();
04899 }
04900 
04901 void KMComposeWin::slotUpdateToolbars()
04902 {
04903   createGUI("kmcomposerui.rc");
04904   applyMainWindowSettings(KMKernel::config(), "Composer");
04905 }
04906 
04907 void KMComposeWin::slotEditKeys()
04908 {
04909   KKeyDialog::configure( actionCollection(),
04910                          false /*don't allow one-letter shortcuts*/
04911                          );
04912 }
04913 
04914 void KMComposeWin::setReplyFocus( bool hasMessage )
04915 {
04916   mEditor->setFocus();
04917   if ( hasMessage ) {
04918     if( mMsg->getCursorPos() ) {
04919       mEditor->setCursorPositionFromStart( (unsigned int) mMsg->getCursorPos() );
04920     } else {
04921       mEditor->setCursorPosition( 1, 0 );
04922     }
04923   }
04924 }
04925 
04926 void KMComposeWin::setFocusToSubject()
04927 {
04928   mEdtSubject->setFocus();
04929 }
04930 
04931 int KMComposeWin::autoSaveInterval() const
04932 {
04933   return GlobalSettings::self()->autosaveInterval() * 1000 * 60;
04934 }
04935 
04936 void KMComposeWin::initAutoSave()
04937 {
04938   kdDebug(5006) << k_funcinfo << endl;
04939   // make sure the autosave folder exists
04940   KMFolderMaildir::createMaildirFolders( KMKernel::localDataPath() + "autosave" );
04941   if ( mAutoSaveFilename.isEmpty() ) {
04942     mAutoSaveFilename = KMFolderMaildir::constructValidFileName();
04943   }
04944 
04945   updateAutoSave();
04946 }
04947 
04948 void KMComposeWin::updateAutoSave()
04949 {
04950   if ( autoSaveInterval() == 0 ) {
04951     delete mAutoSaveTimer; mAutoSaveTimer = 0;
04952   }
04953   else {
04954     if ( !mAutoSaveTimer ) {
04955       mAutoSaveTimer = new QTimer( this, "mAutoSaveTimer" );
04956       connect( mAutoSaveTimer, SIGNAL( timeout() ),
04957                this, SLOT( autoSaveMessage() ) );
04958     }
04959     mAutoSaveTimer->start( autoSaveInterval() );
04960   }
04961 }
04962 
04963 void KMComposeWin::setAutoSaveFilename( const QString & filename )
04964 {
04965   if ( !mAutoSaveFilename.isEmpty() )
04966     KMFolderMaildir::removeFile( KMKernel::localDataPath() + "autosave",
04967                                  mAutoSaveFilename );
04968   mAutoSaveFilename = filename;
04969 }
04970 
04971 void KMComposeWin::cleanupAutoSave()
04972 {
04973   delete mAutoSaveTimer; mAutoSaveTimer = 0;
04974   if ( !mAutoSaveFilename.isEmpty() ) {
04975     kdDebug(5006) << k_funcinfo << "deleting autosave file "
04976                   << mAutoSaveFilename << endl;
04977     KMFolderMaildir::removeFile( KMKernel::localDataPath() + "autosave",
04978                                  mAutoSaveFilename );
04979     mAutoSaveFilename = QString();
04980   }
04981 }
04982 
04983 void KMComposeWin::slotCompletionModeChanged( KGlobalSettings::Completion mode)
04984 {
04985   GlobalSettings::self()->setCompletionMode( (int) mode );
04986 
04987   // sync all the lineedits to the same completion mode
04988   mEdtFrom->setCompletionMode( mode );
04989   mEdtReplyTo->setCompletionMode( mode );
04990   if ( mClassicalRecipients ) {
04991     mEdtTo->setCompletionMode( mode );
04992     mEdtCc->setCompletionMode( mode );
04993     mEdtBcc->setCompletionMode( mode );
04994   }else
04995     mRecipientsEditor->setCompletionMode( mode );
04996 }
04997 
04998 void KMComposeWin::slotConfigChanged()
04999 {
05000   readConfig( true /*reload*/);
05001   updateAutoSave();
05002   rethinkFields();
05003   slotWordWrapToggled( mWordWrapAction->isChecked() );
05004 }
05005 
05006 /*
05007 * checks if the drafts-folder has been deleted
05008 * that is not nice so we set the system-drafts-folder
05009 */
05010 void KMComposeWin::slotFolderRemoved(KMFolder* folder)
05011 {
05012   // TODO: need to handle templates here?
05013   if ( (mFolder) && (folder->idString() == mFolder->idString()) )
05014   {
05015     mFolder = kmkernel->draftsFolder();
05016     kdDebug(5006) << "restoring drafts to " << mFolder->idString() << endl;
05017   }
05018   if (mMsg) mMsg->setParent(0);
05019 }
05020 
05021 
05022 void KMComposeWin::editorFocusChanged(bool gained)
05023 {
05024   mPasteQuotation->setEnabled(gained);
05025 }
05026 
05027 void KMComposeWin::slotSetAlwaysSend( bool bAlways )
05028 {
05029     mAlwaysSend = bAlways;
05030 }
05031 
05032 void KMComposeWin::slotListAction( const QString& style )
05033 {
05034     toggleMarkup(true);
05035     if ( style == i18n( "Standard" ) )
05036        mEditor->setParagType( QStyleSheetItem::DisplayBlock, QStyleSheetItem::ListDisc );
05037     else if ( style == i18n( "Bulleted List (Disc)" ) )
05038        mEditor->setParagType( QStyleSheetItem::DisplayListItem, QStyleSheetItem::ListDisc );
05039     else if ( style == i18n( "Bulleted List (Circle)" ) )
05040        mEditor->setParagType( QStyleSheetItem::DisplayListItem, QStyleSheetItem::ListCircle );
05041     else if ( style == i18n( "Bulleted List (Square)" ) )
05042        mEditor->setParagType( QStyleSheetItem::DisplayListItem, QStyleSheetItem::ListSquare );
05043     else if ( style == i18n( "Ordered List (Decimal)" ))
05044        mEditor->setParagType( QStyleSheetItem::DisplayListItem, QStyleSheetItem::ListDecimal );
05045     else if ( style == i18n( "Ordered List (Alpha lower)" ) )
05046        mEditor->setParagType( QStyleSheetItem::DisplayListItem, QStyleSheetItem::ListLowerAlpha );
05047     else if ( style == i18n( "Ordered List (Alpha upper)" ) )
05048        mEditor->setParagType( QStyleSheetItem::DisplayListItem, QStyleSheetItem::ListUpperAlpha );
05049     mEditor->viewport()->setFocus();
05050 }
05051 
05052 void KMComposeWin::slotFontAction( const QString& font)
05053 {
05054     toggleMarkup(true);
05055     mEditor->QTextEdit::setFamily( font );
05056     mEditor->viewport()->setFocus();
05057 }
05058 
05059 void KMComposeWin::slotSizeAction( int size )
05060 {
05061     toggleMarkup(true);
05062     mEditor->setPointSize( size );
05063     mEditor->viewport()->setFocus();
05064 }
05065 
05066 void KMComposeWin::slotAlignLeft()
05067 {
05068     toggleMarkup(true);
05069     mEditor->QTextEdit::setAlignment( AlignLeft );
05070 }
05071 
05072 void KMComposeWin::slotAlignCenter()
05073 {
05074     toggleMarkup(true);
05075     mEditor->QTextEdit::setAlignment( AlignHCenter );
05076 }
05077 
05078 void KMComposeWin::slotAlignRight()
05079 {
05080     toggleMarkup(true);
05081     mEditor->QTextEdit::setAlignment( AlignRight );
05082 }
05083 
05084 void KMComposeWin::slotTextBold()
05085 {
05086     toggleMarkup(true);
05087     mEditor->QTextEdit::setBold( textBoldAction->isChecked() );
05088 }
05089 
05090 void KMComposeWin::slotTextItalic()
05091 {
05092     toggleMarkup(true);
05093     mEditor->QTextEdit::setItalic( textItalicAction->isChecked() );
05094 }
05095 
05096 void KMComposeWin::slotTextUnder()
05097 {
05098     toggleMarkup(true);
05099     mEditor->QTextEdit::setUnderline( textUnderAction->isChecked() );
05100 }
05101 
05102 void KMComposeWin::slotFormatReset()
05103 {
05104   mEditor->setColor(mForeColor);
05105   mEditor->setCurrentFont( mSaveFont ); // fontChanged is called now
05106 }
05107 void KMComposeWin::slotTextColor()
05108 {
05109   QColor color = mEditor->color();
05110 
05111   if ( KColorDialog::getColor( color, this ) ) {
05112     toggleMarkup(true);
05113     mEditor->setColor( color );
05114   }
05115 }
05116 
05117 void KMComposeWin::fontChanged( const QFont &f )
05118 {
05119   QFont fontTemp = f;
05120   fontTemp.setBold( true );
05121   fontTemp.setItalic( true );
05122   QFontInfo fontInfo( fontTemp );
05123 
05124   if ( fontInfo.bold() ) {
05125     textBoldAction->setChecked( f.bold() );
05126     textBoldAction->setEnabled( true ) ;
05127   } else {
05128     textBoldAction->setEnabled( false );
05129   }
05130 
05131   if ( fontInfo.italic() ) {
05132     textItalicAction->setChecked( f.italic() );
05133     textItalicAction->setEnabled( true ) ;
05134   } else {
05135     textItalicAction->setEnabled( false );
05136   }
05137 
05138   textUnderAction->setChecked( f.underline() );
05139 
05140   fontAction->setFont( f.family() );
05141   fontSizeAction->setFontSize( f.pointSize() );
05142 }
05143 
05144 void KMComposeWin::alignmentChanged( int a )
05145 {
05146     //toggleMarkup();
05147     alignLeftAction->setChecked( ( a == AlignAuto ) || ( a & AlignLeft ) );
05148     alignCenterAction->setChecked( ( a & AlignHCenter ) );
05149     alignRightAction->setChecked( ( a & AlignRight ) );
05150 }
05151 
05152 namespace {
05153   class KToggleActionResetter {
05154     KToggleAction * mAction;
05155     bool mOn;
05156   public:
05157     KToggleActionResetter( KToggleAction * action, bool on )
05158       : mAction( action ),  mOn( on ) {}
05159     ~KToggleActionResetter() {
05160       if ( mAction )
05161         mAction->setChecked( mOn );
05162     }
05163     void disable() { mAction = 0; }
05164   };
05165 }
05166 
05167 void KMComposeWin::slotEncryptChiasmusToggled( bool on ) {
05168   mEncryptWithChiasmus = false;
05169 
05170   if ( !on )
05171     return;
05172 
05173   KToggleActionResetter resetter( mEncryptChiasmusAction, false );
05174 
05175   const Kleo::CryptoBackend::Protocol * chiasmus =
05176     Kleo::CryptoBackendFactory::instance()->protocol( "Chiasmus" );
05177 
05178   if ( !chiasmus ) {
05179     const QString msg = Kleo::CryptoBackendFactory::instance()->knowsAboutProtocol( "Chiasmus" )
05180       ? i18n( "Please configure a Crypto Backend to use for "
05181               "Chiasmus encryption first.\n"
05182               "You can do this in the Crypto Backends tab of "
05183               "the configure dialog's Security page." )
05184       : i18n( "It looks as though libkleopatra was compiled without "
05185               "Chiasmus support. You might want to recompile "
05186               "libkleopatra with --enable-chiasmus.");
05187     KMessageBox::information( this, msg, i18n("No Chiasmus Backend Configured" ) );
05188     return;
05189   }
05190 
05191   STD_NAMESPACE_PREFIX auto_ptr<Kleo::SpecialJob> job( chiasmus->specialJob( "x-obtain-keys", QMap<QString,QVariant>() ) );
05192   if ( !job.get() ) {
05193     const QString msg = i18n( "Chiasmus backend does not offer the "
05194                               "\"x-obtain-keys\" function. Please report this bug." );
05195     KMessageBox::error( this, msg, i18n( "Chiasmus Backend Error" ) );
05196     return;
05197   }
05198 
05199   if ( job->exec() ) {
05200     job->showErrorDialog( this, i18n( "Chiasmus Backend Error" ) );
05201     return;
05202   }
05203 
05204   const QVariant result = job->property( "result" );
05205   if ( result.type() != QVariant::StringList ) {
05206     const QString msg = i18n( "Unexpected return value from Chiasmus backend: "
05207                               "The \"x-obtain-keys\" function did not return a "
05208                               "string list. Please report this bug." );
05209     KMessageBox::error( this, msg, i18n( "Chiasmus Backend Error" ) );
05210     return;
05211   }
05212 
05213   const QStringList keys = result.toStringList();
05214   if ( keys.empty() ) {
05215     const QString msg = i18n( "No keys have been found. Please check that a "
05216                               "valid key path has been set in the Chiasmus "
05217                               "configuration." );
05218     KMessageBox::information( this, msg, i18n( "No Chiasmus Keys Found" ) );
05219     return;
05220   }
05221 
05222   ChiasmusKeySelector selectorDlg( this, i18n( "Chiasmus Encryption Key Selection" ),
05223                                    keys, GlobalSettings::chiasmusKey(),
05224                                    GlobalSettings::chiasmusOptions() );
05225   if ( selectorDlg.exec() != QDialog::Accepted )
05226     return;
05227 
05228   GlobalSettings::setChiasmusOptions( selectorDlg.options() );
05229   GlobalSettings::setChiasmusKey( selectorDlg.key() );
05230   assert( !GlobalSettings::chiasmusKey().isEmpty() );
05231   mEncryptWithChiasmus = true;
05232   resetter.disable();
05233 }
05234 
05235 void KMComposeWin::slotEditDone(KMail::EditorWatcher * watcher)
05236 {
05237   kdDebug(5006) << k_funcinfo << endl;
05238   KMMessagePart *part = mEditorMap[ watcher ];
05239   KTempFile *tf = mEditorTempFiles[ watcher ];
05240   mEditorMap.remove( watcher );
05241   mEditorTempFiles.remove( watcher );
05242   if ( !watcher->fileChanged() )
05243     return;
05244 
05245   tf->file()->reset();
05246   QByteArray data = tf->file()->readAll();
05247   part->setBodyEncodedBinary( data );
05248 }
05249 
05250 
05251 void KMComposeWin::slotUpdateSignatureAndEncrypionStateIndicators()
05252 {
05253     const bool showIndicatorsAlways = false; // FIXME config option?
05254     mSignatureStateIndicator->setText( mSignAction->isChecked()? i18n("Message will be signed") : i18n("Message will not be signed") );
05255     mEncryptionStateIndicator->setText( mEncryptAction->isChecked()? i18n("Message will be encrypted") : i18n("Message will not be encrypted") );
05256     if ( !showIndicatorsAlways ) {
05257       mSignatureStateIndicator->setShown( mSignAction->isChecked() );
05258       mEncryptionStateIndicator->setShown( mEncryptAction->isChecked() );
05259     }
05260 }
05261 
05262 void KMComposeWin::slotAttachmentDragStarted()
05263 {
05264   kdDebug(5006) << k_funcinfo << endl;
05265   int idx = 0;
05266   QStringList filenames;
05267   for ( QPtrListIterator<QListViewItem> it(mAtmItemList); *it; ++it, ++idx ) {
05268     if ( (*it)->isSelected() ) {
05269       KMMessagePart* msgPart = mAtmList.at(idx);
05270       KTempDir * tempDir = new KTempDir(); // will be deleted on composer close
05271       tempDir->setAutoDelete( true );
05272       mTempDirs.insert( tempDir );
05273       const QString fileName = tempDir->name() + "/" + msgPart->name();
05274       KPIM::kByteArrayToFile(msgPart->bodyDecodedBinary(),
05275                              fileName,
05276                              false, false, false);
05277       KURL url;
05278       url.setPath( fileName );
05279       filenames << url.path();
05280     }
05281   }
05282   if ( filenames.isEmpty() ) return;
05283 
05284   QUriDrag *drag  = new QUriDrag( mAtmListView );
05285   drag->setFileNames( filenames );
05286   drag->dragCopy();
05287 }
05288 
05289 void KMComposeWin::recipientEditorSizeHintChanged()
05290 {
05291   QTimer::singleShot( 1, this, SLOT(setMaximumHeaderSize()) );
05292 }
05293 
05294 void KMComposeWin::setMaximumHeaderSize()
05295 {
05296   mHeadersArea->setMaximumHeight( mHeadersArea->sizeHint().height() );
05297 }
05298