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