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