kmail

kmcomposewin.cpp

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