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