kmail

kmreaderwin.cpp

00001 // -*- mode: C++; c-file-style: "gnu" -*-
00002 // kmreaderwin.cpp
00003 // Author: Markus Wuebben <markus.wuebben@kde.org>
00004 
00005 // define this to copy all html that is written to the readerwindow to
00006 // filehtmlwriter.out in the current working directory
00007 //#define KMAIL_READER_HTML_DEBUG 1
00008 
00009 #include <config.h>
00010 
00011 #include "kmreaderwin.h"
00012 
00013 #include "globalsettings.h"
00014 #include "kmversion.h"
00015 #include "kmmainwidget.h"
00016 #include "kmreadermainwin.h"
00017 #include <libkdepim/kfileio.h>
00018 #include "kmfolderindex.h"
00019 #include "kmcommands.h"
00020 #include "kmmsgpartdlg.h"
00021 #include "mailsourceviewer.h"
00022 using KMail::MailSourceViewer;
00023 #include "partNode.h"
00024 #include "kmmsgdict.h"
00025 #include "messagesender.h"
00026 #include "kcursorsaver.h"
00027 #include "kmfolder.h"
00028 #include "vcardviewer.h"
00029 using KMail::VCardViewer;
00030 #include "objecttreeparser.h"
00031 using KMail::ObjectTreeParser;
00032 #include "partmetadata.h"
00033 using KMail::PartMetaData;
00034 #include "attachmentstrategy.h"
00035 using KMail::AttachmentStrategy;
00036 #include "headerstrategy.h"
00037 using KMail::HeaderStrategy;
00038 #include "headerstyle.h"
00039 using KMail::HeaderStyle;
00040 #include "khtmlparthtmlwriter.h"
00041 using KMail::HtmlWriter;
00042 using KMail::KHtmlPartHtmlWriter;
00043 #include "htmlstatusbar.h"
00044 using KMail::HtmlStatusBar;
00045 #include "folderjob.h"
00046 using KMail::FolderJob;
00047 #include "csshelper.h"
00048 using KMail::CSSHelper;
00049 #include "isubject.h"
00050 using KMail::ISubject;
00051 #include "urlhandlermanager.h"
00052 using KMail::URLHandlerManager;
00053 #include "interfaces/observable.h"
00054 #include "util.h"
00055 #include "kmheaders.h"
00056 
00057 #include "broadcaststatus.h"
00058 
00059 #include <kmime_mdn.h>
00060 using namespace KMime;
00061 #ifdef KMAIL_READER_HTML_DEBUG
00062 #include "filehtmlwriter.h"
00063 using KMail::FileHtmlWriter;
00064 #include "teehtmlwriter.h"
00065 using KMail::TeeHtmlWriter;
00066 #endif
00067 
00068 #include <kasciistringtools.h>
00069 #include <kstringhandler.h>
00070 
00071 #include <mimelib/mimepp.h>
00072 #include <mimelib/body.h>
00073 #include <mimelib/utility.h>
00074 
00075 #include <kleo/specialjob.h>
00076 #include <kleo/cryptobackend.h>
00077 #include <kleo/cryptobackendfactory.h>
00078 
00079 // KABC includes
00080 #include <kabc/addressee.h>
00081 #include <kabc/vcardconverter.h>
00082 
00083 // khtml headers
00084 #include <khtml_part.h>
00085 #include <khtmlview.h> // So that we can get rid of the frames
00086 #include <dom/html_element.h>
00087 #include <dom/html_block.h>
00088 #include <dom/html_document.h>
00089 #include <dom/dom_string.h>
00090 
00091 
00092 #include <kapplication.h>
00093 // for the click on attachment stuff (dnaber):
00094 #include <kuserprofile.h>
00095 #include <kcharsets.h>
00096 #include <kpopupmenu.h>
00097 #include <kstandarddirs.h>  // Sven's : for access and getpid
00098 #include <kcursor.h>
00099 #include <kdebug.h>
00100 #include <kfiledialog.h>
00101 #include <klocale.h>
00102 #include <kmessagebox.h>
00103 #include <kglobalsettings.h>
00104 #include <krun.h>
00105 #include <ktempfile.h>
00106 #include <kprocess.h>
00107 #include <kdialog.h>
00108 #include <kaction.h>
00109 #include <kiconloader.h>
00110 #include <kmdcodec.h>
00111 #include <kasciistricmp.h>
00112 #include <kurldrag.h>
00113 
00114 #include <qclipboard.h>
00115 #include <qhbox.h>
00116 #include <qtextcodec.h>
00117 #include <qpaintdevicemetrics.h>
00118 #include <qlayout.h>
00119 #include <qlabel.h>
00120 #include <qsplitter.h>
00121 #include <qstyle.h>
00122 
00123 // X headers...
00124 #undef Never
00125 #undef Always
00126 
00127 #include <unistd.h>
00128 #include <stdlib.h>
00129 #include <sys/stat.h>
00130 #include <errno.h>
00131 #include <stdio.h>
00132 #include <ctype.h>
00133 #include <string.h>
00134 
00135 #ifdef HAVE_PATHS_H
00136 #include <paths.h>
00137 #endif
00138 
00139 class NewByteArray : public QByteArray
00140 {
00141 public:
00142     NewByteArray &appendNULL();
00143     NewByteArray &operator+=( const char * );
00144     NewByteArray &operator+=( const QByteArray & );
00145     NewByteArray &operator+=( const QCString & );
00146     QByteArray& qByteArray();
00147 };
00148 
00149 NewByteArray& NewByteArray::appendNULL()
00150 {
00151     QByteArray::detach();
00152     uint len1 = size();
00153     if ( !QByteArray::resize( len1 + 1 ) )
00154         return *this;
00155     *(data() + len1) = '\0';
00156     return *this;
00157 }
00158 NewByteArray& NewByteArray::operator+=( const char * newData )
00159 {
00160     if ( !newData )
00161         return *this;
00162     QByteArray::detach();
00163     uint len1 = size();
00164     uint len2 = qstrlen( newData );
00165     if ( !QByteArray::resize( len1 + len2 ) )
00166         return *this;
00167     memcpy( data() + len1, newData, len2 );
00168     return *this;
00169 }
00170 NewByteArray& NewByteArray::operator+=( const QByteArray & newData )
00171 {
00172     if ( newData.isNull() )
00173         return *this;
00174     QByteArray::detach();
00175     uint len1 = size();
00176     uint len2 = newData.size();
00177     if ( !QByteArray::resize( len1 + len2 ) )
00178         return *this;
00179     memcpy( data() + len1, newData.data(), len2 );
00180     return *this;
00181 }
00182 NewByteArray& NewByteArray::operator+=( const QCString & newData )
00183 {
00184     if ( newData.isEmpty() )
00185         return *this;
00186     QByteArray::detach();
00187     uint len1 = size();
00188     uint len2 = newData.length(); // forget about the trailing 0x00 !
00189     if ( !QByteArray::resize( len1 + len2 ) )
00190         return *this;
00191     memcpy( data() + len1, newData.data(), len2 );
00192     return *this;
00193 }
00194 QByteArray& NewByteArray::qByteArray()
00195 {
00196     return *((QByteArray*)this);
00197 }
00198 
00199 // This function returns the complete data that were in this
00200 // message parts - *after* all encryption has been removed that
00201 // could be removed.
00202 // - This is used to store the message in decrypted form.
00203 void KMReaderWin::objectTreeToDecryptedMsg( partNode* node,
00204                                             NewByteArray& resultingData,
00205                                             KMMessage& theMessage,
00206                                             bool weAreReplacingTheRootNode,
00207                                             int recCount )
00208 {
00209   kdDebug(5006) << QString("-------------------------------------------------" ) << endl;
00210   kdDebug(5006) << QString("KMReaderWin::objectTreeToDecryptedMsg( %1 )  START").arg( recCount ) << endl;
00211   if( node ) {
00212 
00213     kdDebug(5006) << node->typeString() << '/' << node->subTypeString() << endl;
00214 
00215     partNode* curNode = node;
00216     partNode* dataNode = curNode;
00217     partNode * child = node->firstChild();
00218     const bool bIsMultipart = node->type() == DwMime::kTypeMultipart ;
00219     bool bKeepPartAsIs = false;
00220 
00221     switch( curNode->type() ){
00222       case DwMime::kTypeMultipart: {
00223           switch( curNode->subType() ){
00224           case DwMime::kSubtypeSigned: {
00225               bKeepPartAsIs = true;
00226             }
00227             break;
00228           case DwMime::kSubtypeEncrypted: {
00229               if ( child )
00230                   dataNode = child;
00231             }
00232             break;
00233           }
00234         }
00235         break;
00236       case DwMime::kTypeMessage: {
00237           switch( curNode->subType() ){
00238           case DwMime::kSubtypeRfc822: {
00239               if ( child )
00240                 dataNode = child;
00241             }
00242             break;
00243           }
00244         }
00245         break;
00246       case DwMime::kTypeApplication: {
00247           switch( curNode->subType() ){
00248           case DwMime::kSubtypeOctetStream: {
00249               if ( child )
00250                 dataNode = child;
00251             }
00252             break;
00253           case DwMime::kSubtypePkcs7Signature: {
00254               // note: subtype Pkcs7Signature specifies a signature part
00255               //       which we do NOT want to remove!
00256               bKeepPartAsIs = true;
00257             }
00258             break;
00259           case DwMime::kSubtypePkcs7Mime: {
00260               // note: subtype Pkcs7Mime can also be signed
00261               //       and we do NOT want to remove the signature!
00262               if ( child && curNode->encryptionState() != KMMsgNotEncrypted )
00263                 dataNode = child;
00264             }
00265             break;
00266           }
00267         }
00268         break;
00269     }
00270 
00271 
00272     DwHeaders& rootHeaders( theMessage.headers() );
00273     DwBodyPart * part = dataNode->dwPart() ? dataNode->dwPart() : 0;
00274     DwHeaders * headers(
00275         (part && part->hasHeaders())
00276         ? &part->Headers()
00277         : (  (weAreReplacingTheRootNode || !dataNode->parentNode())
00278             ? &rootHeaders
00279             : 0 ) );
00280     if( dataNode == curNode ) {
00281 kdDebug(5006) << "dataNode == curNode:  Save curNode without replacing it." << endl;
00282 
00283       // A) Store the headers of this part IF curNode is not the root node
00284       //    AND we are not replacing a node that already *has* replaced
00285       //    the root node in previous recursion steps of this function...
00286       if( headers ) {
00287         if( dataNode->parentNode() && !weAreReplacingTheRootNode ) {
00288 kdDebug(5006) << "dataNode is NOT replacing the root node:  Store the headers." << endl;
00289           resultingData += headers->AsString().c_str();
00290         } else if( weAreReplacingTheRootNode && part && part->hasHeaders() ){
00291 kdDebug(5006) << "dataNode replace the root node:  Do NOT store the headers but change" << endl;
00292 kdDebug(5006) << "                                 the Message's headers accordingly." << endl;
00293 kdDebug(5006) << "              old Content-Type = " << rootHeaders.ContentType().AsString().c_str() << endl;
00294 kdDebug(5006) << "              new Content-Type = " << headers->ContentType(   ).AsString().c_str() << endl;
00295           rootHeaders.ContentType()             = headers->ContentType();
00296           theMessage.setContentTransferEncodingStr(
00297               headers->HasContentTransferEncoding()
00298             ? headers->ContentTransferEncoding().AsString().c_str()
00299             : "" );
00300           rootHeaders.ContentDescription() = headers->ContentDescription();
00301           rootHeaders.ContentDisposition() = headers->ContentDisposition();
00302           theMessage.setNeedsAssembly();
00303         }
00304       }
00305 
00306       if ( bKeepPartAsIs ) {
00307           resultingData += dataNode->encodedBody();
00308       } else {
00309 
00310       // B) Store the body of this part.
00311       if( headers && bIsMultipart && dataNode->firstChild() )  {
00312 kdDebug(5006) << "is valid Multipart, processing children:" << endl;
00313         QCString boundary = headers->ContentType().Boundary().c_str();
00314         curNode = dataNode->firstChild();
00315         // store children of multipart
00316         while( curNode ) {
00317 kdDebug(5006) << "--boundary" << endl;
00318           if( resultingData.size() &&
00319               ( '\n' != resultingData.at( resultingData.size()-1 ) ) )
00320             resultingData += QCString( "\n" );
00321           resultingData += QCString( "\n" );
00322           resultingData += "--";
00323           resultingData += boundary;
00324           resultingData += "\n";
00325           // note: We are processing a harmless multipart that is *not*
00326           //       to be replaced by one of it's children, therefor
00327           //       we set their doStoreHeaders to true.
00328           objectTreeToDecryptedMsg( curNode,
00329                                     resultingData,
00330                                     theMessage,
00331                                     false,
00332                                     recCount + 1 );
00333           curNode = curNode->nextSibling();
00334         }
00335 kdDebug(5006) << "--boundary--" << endl;
00336         resultingData += "\n--";
00337         resultingData += boundary;
00338         resultingData += "--\n\n";
00339 kdDebug(5006) << "Multipart processing children - DONE" << endl;
00340       } else if( part ){
00341         // store simple part
00342 kdDebug(5006) << "is Simple part or invalid Multipart, storing body data .. DONE" << endl;
00343         resultingData += part->Body().AsString().c_str();
00344       }
00345       }
00346     } else {
00347 kdDebug(5006) << "dataNode != curNode:  Replace curNode by dataNode." << endl;
00348       bool rootNodeReplaceFlag = weAreReplacingTheRootNode || !curNode->parentNode();
00349       if( rootNodeReplaceFlag ) {
00350 kdDebug(5006) << "                      Root node will be replaced." << endl;
00351       } else {
00352 kdDebug(5006) << "                      Root node will NOT be replaced." << endl;
00353       }
00354       // store special data to replace the current part
00355       // (e.g. decrypted data or embedded RfC 822 data)
00356       objectTreeToDecryptedMsg( dataNode,
00357                                 resultingData,
00358                                 theMessage,
00359                                 rootNodeReplaceFlag,
00360                                 recCount + 1 );
00361     }
00362   }
00363   kdDebug(5006) << QString("\nKMReaderWin::objectTreeToDecryptedMsg( %1 )  END").arg( recCount ) << endl;
00364 }
00365 
00366 
00367 /*
00368  ===========================================================================
00369 
00370 
00371         E N D    O F     T E M P O R A R Y     M I M E     C O D E
00372 
00373 
00374  ===========================================================================
00375 */
00376 
00377 
00378 
00379 
00380 
00381 
00382 
00383 
00384 
00385 
00386 
00387 void KMReaderWin::createWidgets() {
00388   QVBoxLayout * vlay = new QVBoxLayout( this );
00389   mSplitter = new QSplitter( Qt::Vertical, this, "mSplitter" );
00390   vlay->addWidget( mSplitter );
00391   mMimePartTree = new KMMimePartTree( this, mSplitter, "mMimePartTree" );
00392   mBox = new QHBox( mSplitter, "mBox" );
00393   setStyleDependantFrameWidth();
00394   mBox->setFrameStyle( mMimePartTree->frameStyle() );
00395   mColorBar = new HtmlStatusBar( mBox, "mColorBar" );
00396   mViewer = new KHTMLPart( mBox, "mViewer" );
00397   mSplitter->setOpaqueResize( KGlobalSettings::opaqueResize() );
00398   mSplitter->setResizeMode( mMimePartTree, QSplitter::KeepSize );
00399 }
00400 
00401 const int KMReaderWin::delay = 150;
00402 
00403 //-----------------------------------------------------------------------------
00404 KMReaderWin::KMReaderWin(QWidget *aParent,
00405              QWidget *mainWindow,
00406              KActionCollection* actionCollection,
00407                          const char *aName,
00408                          int aFlags )
00409   : QWidget(aParent, aName, aFlags | Qt::WDestructiveClose),
00410     mSerNumOfOriginalMessage( 0 ),
00411     mNodeIdOffset( -1 ),
00412     mAttachmentStrategy( 0 ),
00413     mHeaderStrategy( 0 ),
00414     mHeaderStyle( 0 ),
00415     mUpdateReaderWinTimer( 0, "mUpdateReaderWinTimer" ),
00416     mResizeTimer( 0, "mResizeTimer" ),
00417     mDelayedMarkTimer( 0, "mDelayedMarkTimer" ),
00418     mOldGlobalOverrideEncoding( "---" ), // init with dummy value
00419     mCSSHelper( 0 ),
00420     mRootNode( 0 ),
00421     mMainWindow( mainWindow ),
00422     mActionCollection( actionCollection ),
00423     mMailToComposeAction( 0 ),
00424     mMailToReplyAction( 0 ),
00425     mMailToForwardAction( 0 ),
00426     mAddAddrBookAction( 0 ),
00427     mOpenAddrBookAction( 0 ),
00428     mCopyAction( 0 ),
00429     mCopyURLAction( 0 ),
00430     mUrlOpenAction( 0 ),
00431     mUrlSaveAsAction( 0 ),
00432     mAddBookmarksAction( 0 ),
00433     mStartIMChatAction( 0 ),
00434     mSelectAllAction( 0 ),
00435     mHeaderOnlyAttachmentsAction( 0 ),
00436     mSelectEncodingAction( 0 ),
00437     mToggleFixFontAction( 0 ),
00438     mCanStartDrag( false ),
00439     mHtmlWriter( 0 ),
00440     mSavedRelativePosition( 0 ),
00441     mDecrytMessageOverwrite( false ),
00442     mShowSignatureDetails( false ),
00443     mShowAttachmentQuicklist( true ),
00444     mShowRawToltecMail( false )
00445 {
00446   mExternalWindow  = (aParent == mainWindow );
00447   mSplitterSizes << 180 << 100;
00448   mMimeTreeMode = 1;
00449   mMimeTreeAtBottom = true;
00450   mAutoDelete = false;
00451   mLastSerNum = 0;
00452   mWaitingForSerNum = 0;
00453   mMessage = 0;
00454   mMsgDisplay = true;
00455   mPrinting = false;
00456   mShowColorbar = false;
00457   mAtmUpdate = false;
00458 
00459   createWidgets();
00460   createActions( actionCollection );
00461   initHtmlWidget();
00462   readConfig();
00463 
00464   mHtmlOverride = false;
00465   mHtmlLoadExtOverride = false;
00466 
00467   mLevelQuote = GlobalSettings::self()->collapseQuoteLevelSpin() - 1;
00468 
00469   connect( &mUpdateReaderWinTimer, SIGNAL(timeout()),
00470        this, SLOT(updateReaderWin()) );
00471   connect( &mResizeTimer, SIGNAL(timeout()),
00472        this, SLOT(slotDelayedResize()) );
00473   connect( &mDelayedMarkTimer, SIGNAL(timeout()),
00474            this, SLOT(slotTouchMessage()) );
00475 
00476 }
00477 
00478 void KMReaderWin::createActions( KActionCollection * ac ) {
00479   if ( !ac )
00480       return;
00481 
00482   KRadioAction *raction = 0;
00483 
00484   // header style
00485   KActionMenu *headerMenu =
00486     new KActionMenu( i18n("View->", "&Headers"), ac, "view_headers" );
00487   headerMenu->setToolTip( i18n("Choose display style of message headers") );
00488 
00489   connect( headerMenu, SIGNAL(activated()),
00490            this, SLOT(slotCycleHeaderStyles()) );
00491 
00492   raction = new KRadioAction( i18n("View->headers->", "&Enterprise Headers"), 0,
00493                               this, SLOT(slotEnterpriseHeaders()),
00494                               ac, "view_headers_enterprise" );
00495   raction->setToolTip( i18n("Show the list of headers in Enterprise style") );
00496   raction->setExclusiveGroup( "view_headers_group" );
00497   headerMenu->insert(raction);
00498 
00499   raction = new KRadioAction( i18n("View->headers->", "&Fancy Headers"), 0,
00500                               this, SLOT(slotFancyHeaders()),
00501                               ac, "view_headers_fancy" );
00502   raction->setToolTip( i18n("Show the list of headers in a fancy format") );
00503   raction->setExclusiveGroup( "view_headers_group" );
00504   headerMenu->insert( raction );
00505 
00506   raction = new KRadioAction( i18n("View->headers->", "&Brief Headers"), 0,
00507                               this, SLOT(slotBriefHeaders()),
00508                               ac, "view_headers_brief" );
00509   raction->setToolTip( i18n("Show brief list of message headers") );
00510   raction->setExclusiveGroup( "view_headers_group" );
00511   headerMenu->insert( raction );
00512 
00513   raction = new KRadioAction( i18n("View->headers->", "&Standard Headers"), 0,
00514                               this, SLOT(slotStandardHeaders()),
00515                               ac, "view_headers_standard" );
00516   raction->setToolTip( i18n("Show standard list of message headers") );
00517   raction->setExclusiveGroup( "view_headers_group" );
00518   headerMenu->insert( raction );
00519 
00520   raction = new KRadioAction( i18n("View->headers->", "&Long Headers"), 0,
00521                               this, SLOT(slotLongHeaders()),
00522                               ac, "view_headers_long" );
00523   raction->setToolTip( i18n("Show long list of message headers") );
00524   raction->setExclusiveGroup( "view_headers_group" );
00525   headerMenu->insert( raction );
00526 
00527   raction = new KRadioAction( i18n("View->headers->", "&All Headers"), 0,
00528                               this, SLOT(slotAllHeaders()),
00529                               ac, "view_headers_all" );
00530   raction->setToolTip( i18n("Show all message headers") );
00531   raction->setExclusiveGroup( "view_headers_group" );
00532   headerMenu->insert( raction );
00533 
00534   // attachment style
00535   KActionMenu *attachmentMenu =
00536     new KActionMenu( i18n("View->", "&Attachments"), ac, "view_attachments" );
00537   attachmentMenu->setToolTip( i18n("Choose display style of attachments") );
00538   connect( attachmentMenu, SIGNAL(activated()),
00539            this, SLOT(slotCycleAttachmentStrategy()) );
00540 
00541   raction = new KRadioAction( i18n("View->attachments->", "&As Icons"), 0,
00542                               this, SLOT(slotIconicAttachments()),
00543                               ac, "view_attachments_as_icons" );
00544   raction->setToolTip( i18n("Show all attachments as icons. Click to see them.") );
00545   raction->setExclusiveGroup( "view_attachments_group" );
00546   attachmentMenu->insert( raction );
00547 
00548   raction = new KRadioAction( i18n("View->attachments->", "&Smart"), 0,
00549                               this, SLOT(slotSmartAttachments()),
00550                               ac, "view_attachments_smart" );
00551   raction->setToolTip( i18n("Show attachments as suggested by sender.") );
00552   raction->setExclusiveGroup( "view_attachments_group" );
00553   attachmentMenu->insert( raction );
00554 
00555   raction = new KRadioAction( i18n("View->attachments->", "&Inline"), 0,
00556                               this, SLOT(slotInlineAttachments()),
00557                               ac, "view_attachments_inline" );
00558   raction->setToolTip( i18n("Show all attachments inline (if possible)") );
00559   raction->setExclusiveGroup( "view_attachments_group" );
00560   attachmentMenu->insert( raction );
00561 
00562   raction = new KRadioAction( i18n("View->attachments->", "&Hide"), 0,
00563                               this, SLOT(slotHideAttachments()),
00564                               ac, "view_attachments_hide" );
00565   raction->setToolTip( i18n("Do not show attachments in the message viewer") );
00566   raction->setExclusiveGroup( "view_attachments_group" );
00567   attachmentMenu->insert( raction );
00568 
00569   mHeaderOnlyAttachmentsAction = new KRadioAction( i18n( "View->attachments->", "In Header &Only" ), 0,
00570                               this, SLOT( slotHeaderOnlyAttachments() ),
00571                               ac, "view_attachments_headeronly" );
00572   mHeaderOnlyAttachmentsAction->setToolTip( i18n( "Show Attachments only in the header of the mail" ) );
00573   mHeaderOnlyAttachmentsAction->setExclusiveGroup( "view_attachments_group" );
00574   attachmentMenu->insert( mHeaderOnlyAttachmentsAction );
00575 
00576   // Set Encoding submenu
00577   mSelectEncodingAction = new KSelectAction( i18n( "&Set Encoding" ), "charset", 0,
00578                                  this, SLOT( slotSetEncoding() ),
00579                                  ac, "encoding" );
00580   QStringList encodings = KMMsgBase::supportedEncodings( false );
00581   encodings.prepend( i18n( "Auto" ) );
00582   mSelectEncodingAction->setItems( encodings );
00583   mSelectEncodingAction->setCurrentItem( 0 );
00584 
00585   mMailToComposeAction = new KAction( i18n("New Message To..."), "mail_new",
00586                                       0, this, SLOT(slotMailtoCompose()), ac,
00587                                       "mailto_compose" );
00588   mMailToReplyAction = new KAction( i18n("Reply To..."), "mail_reply",
00589                                     0, this, SLOT(slotMailtoReply()), ac,
00590                     "mailto_reply" );
00591   mMailToForwardAction = new KAction( i18n("Forward To..."), "mail_forward",
00592                                       0, this, SLOT(slotMailtoForward()), ac,
00593                                       "mailto_forward" );
00594   mAddAddrBookAction = new KAction( i18n("Add to Address Book"),
00595                     0, this, SLOT(slotMailtoAddAddrBook()),
00596                     ac, "add_addr_book" );
00597   mOpenAddrBookAction = new KAction( i18n("Open in Address Book"),
00598                                      0, this, SLOT(slotMailtoOpenAddrBook()),
00599                                      ac, "openin_addr_book" );
00600   mCopyAction = KStdAction::copy( this, SLOT(slotCopySelectedText()), ac, "kmail_copy");
00601   mSelectAllAction = new KAction( i18n("Select All Text"), CTRL+SHIFT+Key_A, this,
00602                                   SLOT(selectAll()), ac, "mark_all_text" );
00603   mCopyURLAction = new KAction( i18n("Copy Link Address"), 0, this,
00604                 SLOT(slotUrlCopy()), ac, "copy_url" );
00605   mUrlOpenAction = new KAction( i18n("Open URL"), 0, this,
00606                                 SLOT(slotUrlOpen()), ac, "open_url" );
00607   mAddBookmarksAction = new KAction( i18n("Bookmark This Link"),
00608                                      "bookmark_add",
00609                                      0, this, SLOT(slotAddBookmarks()),
00610                                      ac, "add_bookmarks" );
00611   mUrlSaveAsAction = new KAction( i18n("Save Link As..."), 0, this,
00612                                   SLOT(slotUrlSave()), ac, "saveas_url" );
00613 
00614   mToggleFixFontAction = new KToggleAction( i18n("Use Fi&xed Font"),
00615                                             Key_X, this, SLOT(slotToggleFixedFont()),
00616                                             ac, "toggle_fixedfont" );
00617 
00618   mStartIMChatAction = new KAction( i18n("Chat &With..."), 0, this,
00619                     SLOT(slotIMChat()), ac, "start_im_chat" );
00620 }
00621 
00622 // little helper function
00623 KRadioAction *KMReaderWin::actionForHeaderStyle( const HeaderStyle * style, const HeaderStrategy * strategy ) {
00624   if ( !mActionCollection )
00625     return 0;
00626   const char * actionName = 0;
00627   if ( style == HeaderStyle::enterprise() )
00628     actionName = "view_headers_enterprise";
00629   if ( style == HeaderStyle::fancy() )
00630     actionName = "view_headers_fancy";
00631   else if ( style == HeaderStyle::brief() )
00632     actionName = "view_headers_brief";
00633   else if ( style == HeaderStyle::plain() ) {
00634     if ( strategy == HeaderStrategy::standard() )
00635       actionName = "view_headers_standard";
00636     else if ( strategy == HeaderStrategy::rich() )
00637       actionName = "view_headers_long";
00638     else if ( strategy == HeaderStrategy::all() )
00639       actionName = "view_headers_all";
00640   }
00641   if ( actionName )
00642     return static_cast<KRadioAction*>(mActionCollection->action(actionName));
00643   else
00644     return 0;
00645 }
00646 
00647 KRadioAction *KMReaderWin::actionForAttachmentStrategy( const AttachmentStrategy * as ) {
00648   if ( !mActionCollection )
00649     return 0;
00650   const char * actionName = 0;
00651   if ( as == AttachmentStrategy::iconic() )
00652     actionName = "view_attachments_as_icons";
00653   else if ( as == AttachmentStrategy::smart() )
00654     actionName = "view_attachments_smart";
00655   else if ( as == AttachmentStrategy::inlined() )
00656     actionName = "view_attachments_inline";
00657   else if ( as == AttachmentStrategy::hidden() )
00658     actionName = "view_attachments_hide";
00659   else if ( as == AttachmentStrategy::headerOnly() )
00660     actionName = "view_attachments_headeronly";
00661 
00662   if ( actionName )
00663     return static_cast<KRadioAction*>(mActionCollection->action(actionName));
00664   else
00665     return 0;
00666 }
00667 
00668 void KMReaderWin::slotEnterpriseHeaders() {
00669   setHeaderStyleAndStrategy( HeaderStyle::enterprise(),
00670                              HeaderStrategy::rich() );
00671   if( !mExternalWindow )
00672      writeConfig();
00673 }
00674 
00675 void KMReaderWin::slotFancyHeaders() {
00676   setHeaderStyleAndStrategy( HeaderStyle::fancy(),
00677                              HeaderStrategy::rich() );
00678   if( !mExternalWindow )
00679      writeConfig();
00680 }
00681 
00682 void KMReaderWin::slotBriefHeaders() {
00683   setHeaderStyleAndStrategy( HeaderStyle::brief(),
00684                              HeaderStrategy::brief() );
00685   if( !mExternalWindow )
00686      writeConfig();
00687 }
00688 
00689 void KMReaderWin::slotStandardHeaders() {
00690   setHeaderStyleAndStrategy( HeaderStyle::plain(),
00691                              HeaderStrategy::standard());
00692   writeConfig();
00693 }
00694 
00695 void KMReaderWin::slotLongHeaders() {
00696   setHeaderStyleAndStrategy( HeaderStyle::plain(),
00697                              HeaderStrategy::rich() );
00698   if( !mExternalWindow )
00699      writeConfig();
00700 }
00701 
00702 void KMReaderWin::slotAllHeaders() {
00703   setHeaderStyleAndStrategy( HeaderStyle::plain(),
00704                              HeaderStrategy::all() );
00705   if( !mExternalWindow )
00706      writeConfig();
00707 }
00708 
00709 void KMReaderWin::slotLevelQuote( int l )
00710 {
00711   mLevelQuote = l;
00712   saveRelativePosition();
00713   update(true);
00714 }
00715 
00716 void KMReaderWin::slotCycleHeaderStyles() {
00717   const HeaderStrategy * strategy = headerStrategy();
00718   const HeaderStyle * style = headerStyle();
00719 
00720   const char * actionName = 0;
00721   if ( style == HeaderStyle::enterprise() ) {
00722     slotFancyHeaders();
00723     actionName = "view_headers_fancy";
00724   }
00725   if ( style == HeaderStyle::fancy() ) {
00726     slotBriefHeaders();
00727     actionName = "view_headers_brief";
00728   } else if ( style == HeaderStyle::brief() ) {
00729     slotStandardHeaders();
00730     actionName = "view_headers_standard";
00731   } else if ( style == HeaderStyle::plain() ) {
00732     if ( strategy == HeaderStrategy::standard() ) {
00733       slotLongHeaders();
00734       actionName = "view_headers_long";
00735     } else if ( strategy == HeaderStrategy::rich() ) {
00736       slotAllHeaders();
00737       actionName = "view_headers_all";
00738     } else if ( strategy == HeaderStrategy::all() ) {
00739       slotEnterpriseHeaders();
00740       actionName = "view_headers_enterprise";
00741     }
00742   }
00743 
00744   if ( actionName )
00745     static_cast<KRadioAction*>( mActionCollection->action( actionName ) )->setChecked( true );
00746 }
00747 
00748 
00749 void KMReaderWin::slotIconicAttachments() {
00750   setAttachmentStrategy( AttachmentStrategy::iconic() );
00751 }
00752 
00753 void KMReaderWin::slotSmartAttachments() {
00754   setAttachmentStrategy( AttachmentStrategy::smart() );
00755 }
00756 
00757 void KMReaderWin::slotInlineAttachments() {
00758   setAttachmentStrategy( AttachmentStrategy::inlined() );
00759 }
00760 
00761 void KMReaderWin::slotHideAttachments() {
00762   setAttachmentStrategy( AttachmentStrategy::hidden() );
00763 }
00764 
00765 void KMReaderWin::slotHeaderOnlyAttachments() {
00766   setAttachmentStrategy( AttachmentStrategy::headerOnly() );
00767 }
00768 
00769 void KMReaderWin::slotCycleAttachmentStrategy() {
00770   setAttachmentStrategy( attachmentStrategy()->next() );
00771   KRadioAction * action = actionForAttachmentStrategy( attachmentStrategy() );
00772   assert( action );
00773   action->setChecked( true );
00774 }
00775 
00776 
00777 //-----------------------------------------------------------------------------
00778 KMReaderWin::~KMReaderWin()
00779 {
00780   clearBodyPartMementos();
00781   delete mHtmlWriter; mHtmlWriter = 0;
00782   delete mCSSHelper;
00783   if (mAutoDelete) delete message();
00784   delete mRootNode; mRootNode = 0;
00785   removeTempFiles();
00786 }
00787 
00788 
00789 //-----------------------------------------------------------------------------
00790 void KMReaderWin::slotMessageArrived( KMMessage *msg )
00791 {
00792   if (msg && ((KMMsgBase*)msg)->isMessage()) {
00793     if ( msg->getMsgSerNum() == mWaitingForSerNum ) {
00794       setMsg( msg, true );
00795     } else {
00796       //kdDebug( 5006 ) <<  "KMReaderWin::slotMessageArrived - ignoring update" << endl;
00797     }
00798   }
00799 }
00800 
00801 //-----------------------------------------------------------------------------
00802 void KMReaderWin::update( KMail::Interface::Observable * observable )
00803 {
00804   if ( !mAtmUpdate ) {
00805     // reparse the msg
00806     //kdDebug(5006) << "KMReaderWin::update - message" << endl;
00807     updateReaderWin();
00808     return;
00809   }
00810 
00811   if ( !mRootNode )
00812     return;
00813 
00814   KMMessage* msg = static_cast<KMMessage*>( observable );
00815   assert( msg != 0 );
00816 
00817   // find our partNode and update it
00818   if ( !msg->lastUpdatedPart() ) {
00819     kdDebug(5006) << "KMReaderWin::update - no updated part" << endl;
00820     return;
00821   }
00822   partNode* node = mRootNode->findNodeForDwPart( msg->lastUpdatedPart() );
00823   if ( !node ) {
00824     kdDebug(5006) << "KMReaderWin::update - can't find node for part" << endl;
00825     return;
00826   }
00827   node->setDwPart( msg->lastUpdatedPart() );
00828 
00829   // update the tmp file
00830   // we have to set it writeable temporarily
00831   ::chmod( QFile::encodeName( mAtmCurrentName ), S_IRWXU );
00832   QByteArray data = node->msgPart().bodyDecodedBinary();
00833   size_t size = data.size();
00834   if ( node->msgPart().type() == DwMime::kTypeText && size) {
00835     size = KMail::Util::crlf2lf( data.data(), size );
00836   }
00837   KPIM::kBytesToFile( data.data(), size, mAtmCurrentName, false, false, false );
00838   ::chmod( QFile::encodeName( mAtmCurrentName ), S_IRUSR );
00839 
00840   mAtmUpdate = false;
00841 }
00842 
00843 //-----------------------------------------------------------------------------
00844 void KMReaderWin::removeTempFiles()
00845 {
00846   for (QStringList::Iterator it = mTempFiles.begin(); it != mTempFiles.end();
00847     it++)
00848   {
00849     QFile::remove(*it);
00850   }
00851   mTempFiles.clear();
00852   for (QStringList::Iterator it = mTempDirs.begin(); it != mTempDirs.end();
00853     it++)
00854   {
00855     QDir(*it).rmdir(*it);
00856   }
00857   mTempDirs.clear();
00858 }
00859 
00860 
00861 //-----------------------------------------------------------------------------
00862 bool KMReaderWin::event(QEvent *e)
00863 {
00864   if (e->type() == QEvent::ApplicationPaletteChange)
00865   {
00866     delete mCSSHelper;
00867     mCSSHelper = new KMail::CSSHelper(  QPaintDeviceMetrics( mViewer->view() ) );
00868     if (message())
00869       message()->readConfig();
00870     update( true ); // Force update
00871     return true;
00872   }
00873   return QWidget::event(e);
00874 }
00875 
00876 
00877 //-----------------------------------------------------------------------------
00878 void KMReaderWin::readConfig(void)
00879 {
00880   const KConfigGroup mdnGroup( KMKernel::config(), "MDN" );
00881   /*should be: const*/ KConfigGroup reader( KMKernel::config(), "Reader" );
00882 
00883   delete mCSSHelper;
00884   mCSSHelper = new KMail::CSSHelper( QPaintDeviceMetrics( mViewer->view() ) );
00885 
00886   mNoMDNsWhenEncrypted = mdnGroup.readBoolEntry( "not-send-when-encrypted", true );
00887 
00888   mUseFixedFont = reader.readBoolEntry( "useFixedFont", false );
00889   if ( mToggleFixFontAction )
00890     mToggleFixFontAction->setChecked( mUseFixedFont );
00891 
00892   mHtmlMail = reader.readBoolEntry( "htmlMail", false );
00893   mHtmlLoadExternal = reader.readBoolEntry( "htmlLoadExternal", false );
00894 
00895   setHeaderStyleAndStrategy( HeaderStyle::create( reader.readEntry( "header-style", "fancy" ) ),
00896                  HeaderStrategy::create( reader.readEntry( "header-set-displayed", "rich" ) ) );
00897   KRadioAction *raction = actionForHeaderStyle( headerStyle(), headerStrategy() );
00898   if ( raction )
00899     raction->setChecked( true );
00900 
00901   setAttachmentStrategy( AttachmentStrategy::create( reader.readEntry( "attachment-strategy", "smart" ) ) );
00902   raction = actionForAttachmentStrategy( attachmentStrategy() );
00903   if ( raction )
00904     raction->setChecked( true );
00905 
00906   // if the user uses OpenPGP then the color bar defaults to enabled
00907   // else it defaults to disabled
00908   mShowColorbar = reader.readBoolEntry( "showColorbar", Kpgp::Module::getKpgp()->usePGP() );
00909   // if the value defaults to enabled and KMail (with color bar) is used for
00910   // the first time the config dialog doesn't know this if we don't save the
00911   // value now
00912   reader.writeEntry( "showColorbar", mShowColorbar );
00913 
00914   mMimeTreeAtBottom = reader.readEntry( "MimeTreeLocation", "bottom" ) != "top";
00915   const QString s = reader.readEntry( "MimeTreeMode", "smart" );
00916   if ( s == "never" )
00917     mMimeTreeMode = 0;
00918   else if ( s == "always" )
00919     mMimeTreeMode = 2;
00920   else
00921     mMimeTreeMode = 1;
00922 
00923   const int mimeH = reader.readNumEntry( "MimePaneHeight", 100 );
00924   const int messageH = reader.readNumEntry( "MessagePaneHeight", 180 );
00925   mSplitterSizes.clear();
00926   if ( mMimeTreeAtBottom )
00927     mSplitterSizes << messageH << mimeH;
00928   else
00929     mSplitterSizes << mimeH << messageH;
00930 
00931   adjustLayout();
00932 
00933   readGlobalOverrideCodec();
00934 
00935   if (message())
00936     update();
00937   KMMessage::readConfig();
00938 }
00939 
00940 
00941 void KMReaderWin::adjustLayout() {
00942   if ( mMimeTreeAtBottom )
00943     mSplitter->moveToLast( mMimePartTree );
00944   else
00945     mSplitter->moveToFirst( mMimePartTree );
00946   mSplitter->setSizes( mSplitterSizes );
00947 
00948   if ( mMimeTreeMode == 2 && mMsgDisplay )
00949     mMimePartTree->show();
00950   else
00951     mMimePartTree->hide();
00952 
00953   if ( mShowColorbar && mMsgDisplay )
00954     mColorBar->show();
00955   else
00956     mColorBar->hide();
00957 }
00958 
00959 
00960 void KMReaderWin::saveSplitterSizes( KConfigBase & c ) const {
00961   if ( !mSplitter || !mMimePartTree )
00962     return;
00963   if ( mMimePartTree->isHidden() )
00964     return; // don't rely on QSplitter maintaining sizes for hidden widgets.
00965 
00966   c.writeEntry( "MimePaneHeight", mSplitter->sizes()[ mMimeTreeAtBottom ? 1 : 0 ] );
00967   c.writeEntry( "MessagePaneHeight", mSplitter->sizes()[ mMimeTreeAtBottom ? 0 : 1 ] );
00968 }
00969 
00970 //-----------------------------------------------------------------------------
00971 void KMReaderWin::writeConfig( bool sync ) const {
00972   KConfigGroup reader( KMKernel::config(), "Reader" );
00973 
00974   reader.writeEntry( "useFixedFont", mUseFixedFont );
00975   if ( headerStyle() )
00976     reader.writeEntry( "header-style", headerStyle()->name() );
00977   if ( headerStrategy() )
00978     reader.writeEntry( "header-set-displayed", headerStrategy()->name() );
00979   if ( attachmentStrategy() )
00980     reader.writeEntry( "attachment-strategy", attachmentStrategy()->name() );
00981 
00982   saveSplitterSizes( reader );
00983 
00984   if ( sync )
00985     kmkernel->slotRequestConfigSync();
00986 }
00987 
00988 //-----------------------------------------------------------------------------
00989 void KMReaderWin::initHtmlWidget(void)
00990 {
00991   mViewer->widget()->setFocusPolicy(WheelFocus);
00992   // Let's better be paranoid and disable plugins (it defaults to enabled):
00993   mViewer->setPluginsEnabled(false);
00994   mViewer->setJScriptEnabled(false); // just make this explicit
00995   mViewer->setJavaEnabled(false);    // just make this explicit
00996   mViewer->setMetaRefreshEnabled(false);
00997   mViewer->setURLCursor(KCursor::handCursor());
00998   // Espen 2000-05-14: Getting rid of thick ugly frames
00999   mViewer->view()->setLineWidth(0);
01000   // register our own event filter for shift-click
01001   mViewer->view()->viewport()->installEventFilter( this );
01002 
01003   if ( !htmlWriter() )
01004 #ifdef KMAIL_READER_HTML_DEBUG
01005     mHtmlWriter = new TeeHtmlWriter( new FileHtmlWriter( QString::null ),
01006                      new KHtmlPartHtmlWriter( mViewer, 0 ) );
01007 #else
01008     mHtmlWriter = new KHtmlPartHtmlWriter( mViewer, 0 );
01009 #endif
01010 
01011   connect(mViewer->browserExtension(),
01012           SIGNAL(openURLRequest(const KURL &, const KParts::URLArgs &)),this,
01013           SLOT(slotUrlOpen(const KURL &)));
01014   connect(mViewer->browserExtension(),
01015           SIGNAL(createNewWindow(const KURL &, const KParts::URLArgs &)),this,
01016           SLOT(slotUrlOpen(const KURL &)));
01017   connect(mViewer,SIGNAL(onURL(const QString &)),this,
01018           SLOT(slotUrlOn(const QString &)));
01019   connect(mViewer,SIGNAL(popupMenu(const QString &, const QPoint &)),
01020           SLOT(slotUrlPopup(const QString &, const QPoint &)));
01021   connect( kmkernel->imProxy(), SIGNAL( sigContactPresenceChanged( const QString & ) ),
01022           this, SLOT( contactStatusChanged( const QString & ) ) );
01023   connect( kmkernel->imProxy(), SIGNAL( sigPresenceInfoExpired() ),
01024           this, SLOT( updateReaderWin() ) );
01025 }
01026 
01027 void KMReaderWin::contactStatusChanged( const QString &uid)
01028 {
01029 //  kdDebug( 5006 ) << k_funcinfo << " got a presence change for " << uid << endl;
01030   // get the list of nodes for this contact from the htmlView
01031   DOM::NodeList presenceNodes = mViewer->htmlDocument()
01032     .getElementsByName( DOM::DOMString( QString::fromLatin1("presence-") + uid ) );
01033   for ( unsigned int i = 0; i < presenceNodes.length(); ++i ) {
01034     DOM::Node n =  presenceNodes.item( i );
01035     kdDebug( 5006 ) << "name is " << n.nodeName().string() << endl;
01036     kdDebug( 5006 ) << "value of content was " << n.firstChild().nodeValue().string() << endl;
01037     QString newPresence = kmkernel->imProxy()->presenceString( uid );
01038     if ( newPresence.isNull() ) // KHTML crashes if you setNodeValue( QString::null )
01039       newPresence = QString::fromLatin1( "ENOIMRUNNING" );
01040     n.firstChild().setNodeValue( newPresence );
01041 //    kdDebug( 5006 ) << "value of content is now " << n.firstChild().nodeValue().string() << endl;
01042   }
01043 //  kdDebug( 5006 ) << "and we updated the above presence nodes" << uid << endl;
01044 }
01045 
01046 void KMReaderWin::setAttachmentStrategy( const AttachmentStrategy * strategy ) {
01047   mAttachmentStrategy = strategy ? strategy : AttachmentStrategy::smart();
01048   update( true );
01049 }
01050 
01051 void KMReaderWin::setHeaderStyleAndStrategy( const HeaderStyle * style,
01052                          const HeaderStrategy * strategy ) {
01053   mHeaderStyle = style ? style : HeaderStyle::fancy();
01054   mHeaderStrategy = strategy ? strategy : HeaderStrategy::rich();
01055   if ( mHeaderOnlyAttachmentsAction ) {
01056     const bool styleHasAttachmentQuickList = mHeaderStyle == HeaderStyle::fancy() ||
01057                                              mHeaderStyle == HeaderStyle::enterprise();
01058     mHeaderOnlyAttachmentsAction->setEnabled( styleHasAttachmentQuickList );
01059     if ( !styleHasAttachmentQuickList && mAttachmentStrategy == AttachmentStrategy::headerOnly() ) {
01060       // Style changed to something without an attachment quick list, need to change attachment
01061       // strategy
01062       setAttachmentStrategy( AttachmentStrategy::smart() );
01063     }
01064   }
01065   update( true );
01066 }
01067 
01068 //-----------------------------------------------------------------------------
01069 void KMReaderWin::setOverrideEncoding( const QString & encoding )
01070 {
01071   if ( encoding == mOverrideEncoding )
01072     return;
01073 
01074   mOverrideEncoding = encoding;
01075   if ( mSelectEncodingAction ) {
01076     if ( encoding.isEmpty() ) {
01077       mSelectEncodingAction->setCurrentItem( 0 );
01078     }
01079     else {
01080       QStringList encodings = mSelectEncodingAction->items();
01081       uint i = 0;
01082       for ( QStringList::const_iterator it = encodings.begin(), end = encodings.end(); it != end; ++it, ++i ) {
01083         if ( KGlobal::charsets()->encodingForName( *it ) == encoding ) {
01084           mSelectEncodingAction->setCurrentItem( i );
01085           break;
01086         }
01087       }
01088       if ( i == encodings.size() ) {
01089         // the value of encoding is unknown => use Auto
01090         kdWarning(5006) << "Unknown override character encoding \"" << encoding
01091                         << "\". Using Auto instead." << endl;
01092         mSelectEncodingAction->setCurrentItem( 0 );
01093         mOverrideEncoding = QString::null;
01094       }
01095     }
01096   }
01097   update( true );
01098 }
01099 
01100 
01101 void KMReaderWin::setPrintFont( const QFont& font )
01102 {
01103 
01104   mCSSHelper->setPrintFont( font );
01105 }
01106 
01107 //-----------------------------------------------------------------------------
01108 const QTextCodec * KMReaderWin::overrideCodec() const
01109 {
01110   if ( mOverrideEncoding.isEmpty() || mOverrideEncoding == "Auto" ) // Auto
01111     return 0;
01112   else
01113     return KMMsgBase::codecForName( mOverrideEncoding.latin1() );
01114 }
01115 
01116 //-----------------------------------------------------------------------------
01117 void KMReaderWin::slotSetEncoding()
01118 {
01119   if ( mSelectEncodingAction->currentItem() == 0 ) // Auto
01120     mOverrideEncoding = QString();
01121   else
01122     mOverrideEncoding = KGlobal::charsets()->encodingForName( mSelectEncodingAction->currentText() );
01123   update( true );
01124 }
01125 
01126 //-----------------------------------------------------------------------------
01127 void KMReaderWin::readGlobalOverrideCodec()
01128 {
01129   // if the global character encoding wasn't changed then there's nothing to do
01130   if ( GlobalSettings::self()->overrideCharacterEncoding() == mOldGlobalOverrideEncoding )
01131     return;
01132 
01133   setOverrideEncoding( GlobalSettings::self()->overrideCharacterEncoding() );
01134   mOldGlobalOverrideEncoding = GlobalSettings::self()->overrideCharacterEncoding();
01135 }
01136 
01137 //-----------------------------------------------------------------------------
01138 void KMReaderWin::setOriginalMsg( unsigned long serNumOfOriginalMessage, int nodeIdOffset )
01139 {
01140   mSerNumOfOriginalMessage = serNumOfOriginalMessage;
01141   mNodeIdOffset = nodeIdOffset;
01142 }
01143 
01144 //-----------------------------------------------------------------------------
01145 void KMReaderWin::setMsg( KMMessage* aMsg, bool force, bool updateOnly )
01146 {
01147   if ( aMsg ) {
01148     kdDebug(5006) << "(" << aMsg->getMsgSerNum() << ", last " << mLastSerNum << ") " << aMsg->subject() << " "
01149                   << aMsg->fromStrip() << ", readyToShow " << (aMsg->readyToShow()) << endl;
01150   }
01151 
01152   // Reset message-transient state
01153   if ( aMsg && aMsg->getMsgSerNum() != mLastSerNum && !updateOnly ){
01154     mLevelQuote = GlobalSettings::self()->collapseQuoteLevelSpin()-1;
01155     mShowRawToltecMail = !GlobalSettings::self()->showToltecReplacementText();
01156     clearBodyPartMementos();
01157   }
01158   if ( mPrinting )
01159     mLevelQuote = -1;
01160 
01161   bool complete = true;
01162   if ( aMsg &&
01163        !aMsg->readyToShow() &&
01164        (aMsg->getMsgSerNum() != mLastSerNum) &&
01165        !aMsg->isComplete() )
01166     complete = false;
01167 
01168   // If not forced and there is aMsg and aMsg is same as mMsg then return
01169   if (!force && aMsg && mLastSerNum != 0 && aMsg->getMsgSerNum() == mLastSerNum)
01170     return;
01171 
01172   // (de)register as observer
01173   if (aMsg && message())
01174     message()->detach( this );
01175   if (aMsg)
01176     aMsg->attach( this );
01177   mAtmUpdate = false;
01178 
01179   // connect to the updates if we have hancy headers
01180 
01181   mDelayedMarkTimer.stop();
01182 
01183   mMessage = 0;
01184   if ( !aMsg ) {
01185     mWaitingForSerNum = 0; // otherwise it has been set
01186     mLastSerNum = 0;
01187   } else {
01188     mLastSerNum = aMsg->getMsgSerNum();
01189     // Check if the serial number can be used to find the assoc KMMessage
01190     // If so, keep only the serial number (and not mMessage), to avoid a dangling mMessage
01191     // when going to another message in the mainwindow.
01192     // Otherwise, keep only mMessage, this is fine for standalone KMReaderMainWins since
01193     // we're working on a copy of the KMMessage, which we own.
01194     if (message() != aMsg) {
01195       mMessage = aMsg;
01196       mLastSerNum = 0;
01197     }
01198   }
01199 
01200   if (aMsg) {
01201     aMsg->setOverrideCodec( overrideCodec() );
01202     aMsg->setDecodeHTML( htmlMail() );
01203     // FIXME: workaround to disable DND for IMAP load-on-demand
01204     if ( !aMsg->isComplete() )
01205       mViewer->setDNDEnabled( false );
01206     else
01207       mViewer->setDNDEnabled( true );
01208   }
01209 
01210   // only display the msg if it is complete
01211   // otherwise we'll get flickering with progressively loaded messages
01212   if ( complete )
01213   {
01214     // Avoid flicker, somewhat of a cludge
01215     if (force) {
01216       // stop the timer to avoid calling updateReaderWin twice
01217       mUpdateReaderWinTimer.stop();
01218       updateReaderWin();
01219     }
01220     else if (mUpdateReaderWinTimer.isActive())
01221       mUpdateReaderWinTimer.changeInterval( delay );
01222     else
01223       mUpdateReaderWinTimer.start( 0, true );
01224   }
01225 
01226   if ( aMsg && (aMsg->isUnread() || aMsg->isNew()) && GlobalSettings::self()->delayedMarkAsRead() ) {
01227     if ( GlobalSettings::self()->delayedMarkTime() != 0 )
01228       mDelayedMarkTimer.start( GlobalSettings::self()->delayedMarkTime() * 1000, true );
01229     else
01230       slotTouchMessage();
01231   }
01232 }
01233 
01234 //-----------------------------------------------------------------------------
01235 void KMReaderWin::clearCache()
01236 {
01237   mUpdateReaderWinTimer.stop();
01238   clear();
01239   mDelayedMarkTimer.stop();
01240   mLastSerNum = 0;
01241   mWaitingForSerNum = 0;
01242   mMessage = 0;
01243 }
01244 
01245 // enter items for the "Important changes" list here:
01246 static const char * const kmailChanges[] = {
01247   ""
01248 };
01249 static const int numKMailChanges =
01250   sizeof kmailChanges / sizeof *kmailChanges;
01251 
01252 // enter items for the "new features" list here, so the main body of
01253 // the welcome page can be left untouched (probably much easier for
01254 // the translators). Note that the <li>...</li> tags are added
01255 // automatically below:
01256 static const char * const kmailNewFeatures[] = {
01257   I18N_NOOP("Full namespace support for IMAP"),
01258   I18N_NOOP("Offline mode"),
01259   I18N_NOOP("Sieve script management and editing"),
01260   I18N_NOOP("Account specific filtering"),
01261   I18N_NOOP("Filtering of incoming mail for online IMAP accounts"),
01262   I18N_NOOP("Online IMAP folders can be used when filtering into folders"),
01263   I18N_NOOP("Automatically delete older mails on POP servers")
01264 };
01265 static const int numKMailNewFeatures =
01266   sizeof kmailNewFeatures / sizeof *kmailNewFeatures;
01267 
01268 
01269 //-----------------------------------------------------------------------------
01270 //static
01271 QString KMReaderWin::newFeaturesMD5()
01272 {
01273   QCString str;
01274   for ( int i = 0 ; i < numKMailChanges ; ++i )
01275     str += kmailChanges[i];
01276   for ( int i = 0 ; i < numKMailNewFeatures ; ++i )
01277     str += kmailNewFeatures[i];
01278   KMD5 md5( str );
01279   return md5.base64Digest();
01280 }
01281 
01282 //-----------------------------------------------------------------------------
01283 void KMReaderWin::displaySplashPage( const QString &info )
01284 {
01285   mMsgDisplay = false;
01286   adjustLayout();
01287 
01288   QString location = locate("data", "kmail/about/main.html");
01289   QString content = KPIM::kFileToString(location);
01290   content = content.arg( locate( "data", "libkdepim/about/kde_infopage.css" ) );
01291   if ( kapp->reverseLayout() )
01292     content = content.arg( "@import \"%1\";" ).arg( locate( "data", "libkdepim/about/kde_infopage_rtl.css" ) );
01293   else
01294     content = content.arg( "" );
01295 
01296   mViewer->begin(KURL( location ));
01297 
01298   QString fontSize = QString::number( pointsToPixel( mCSSHelper->bodyFont().pointSize() ) );
01299   QString appTitle = i18n("KMail");
01300   QString catchPhrase = ""; //not enough space for a catch phrase at default window size i18n("Part of the Kontact Suite");
01301   QString quickDescription = i18n("The email client for the K Desktop Environment.");
01302   mViewer->write(content.arg(fontSize).arg(appTitle).arg(catchPhrase).arg(quickDescription).arg(info));
01303   mViewer->end();
01304 }
01305 
01306 void KMReaderWin::displayBusyPage()
01307 {
01308   QString info =
01309     i18n( "<h2 style='margin-top: 0px;'>Retrieving Folder Contents</h2><p>Please wait . . .</p>&nbsp;" );
01310 
01311   displaySplashPage( info );
01312 }
01313 
01314 void KMReaderWin::displayOfflinePage()
01315 {
01316   QString info =
01317     i18n( "<h2 style='margin-top: 0px;'>Offline</h2><p>KMail is currently in offline mode. "
01318         "Click <a href=\"kmail:goOnline\">here</a> to go online . . .</p>&nbsp;" );
01319 
01320   displaySplashPage( info );
01321 }
01322 
01323 
01324 //-----------------------------------------------------------------------------
01325 void KMReaderWin::displayAboutPage()
01326 {
01327   QString info =
01328     i18n("%1: KMail version; %2: help:// URL; %3: homepage URL; "
01329      "%4: prior KMail version; %5: prior KDE version; "
01330      "%6: generated list of new features; "
01331      "%7: First-time user text (only shown on first start); "
01332          "%8: generated list of important changes; "
01333      "--- end of comment ---",
01334      "<h2 style='margin-top: 0px;'>Welcome to KMail %1</h2><p>KMail is the email client for the K "
01335      "Desktop Environment. It is designed to be fully compatible with "
01336      "Internet mailing standards including MIME, SMTP, POP3 and IMAP."
01337      "</p>\n"
01338      "<ul><li>KMail has many powerful features which are described in the "
01339      "<a href=\"%2\">documentation</a></li>\n"
01340      "<li>The <a href=\"%3\">KMail homepage</A> offers information about "
01341      "new versions of KMail</li></ul>\n"
01342          "%8\n" // important changes
01343      "<p>Some of the new features in this release of KMail include "
01344      "(compared to KMail %4, which is part of KDE %5):</p>\n"
01345      "<ul>\n%6</ul>\n"
01346      "%7\n"
01347      "<p>We hope that you will enjoy KMail.</p>\n"
01348      "<p>Thank you,</p>\n"
01349          "<p style='margin-bottom: 0px'>&nbsp; &nbsp; The KMail Team</p>")
01350     .arg(KMAIL_VERSION) // KMail version
01351     .arg("help:/kmail/index.html") // KMail help:// URL
01352     .arg("http://kontact.kde.org/kmail/") // KMail homepage URL
01353     .arg("1.8").arg("3.4"); // prior KMail and KDE version
01354 
01355   QString featureItems;
01356   for ( int i = 0 ; i < numKMailNewFeatures ; i++ )
01357     featureItems += i18n("<li>%1</li>\n").arg( i18n( kmailNewFeatures[i] ) );
01358 
01359   info = info.arg( featureItems );
01360 
01361   if( kmkernel->firstStart() ) {
01362     info = info.arg( i18n("<p>Please take a moment to fill in the KMail "
01363               "configuration panel at Settings-&gt;Configure "
01364               "KMail.\n"
01365               "You need to create at least a default identity and "
01366               "an incoming as well as outgoing mail account."
01367               "</p>\n") );
01368   } else {
01369     info = info.arg( QString::null );
01370   }
01371 
01372   if ( ( numKMailChanges > 1 ) || ( numKMailChanges == 1 && strlen(kmailChanges[0]) > 0 ) ) {
01373     QString changesText =
01374       i18n("<p><span style='font-size:125%; font-weight:bold;'>"
01375            "Important changes</span> (compared to KMail %1):</p>\n")
01376       .arg("1.8");
01377     changesText += "<ul>\n";
01378     for ( int i = 0 ; i < numKMailChanges ; i++ )
01379       changesText += i18n("<li>%1</li>\n").arg( i18n( kmailChanges[i] ) );
01380     changesText += "</ul>\n";
01381     info = info.arg( changesText );
01382   }
01383   else
01384     info = info.arg(""); // remove the %8
01385 
01386   displaySplashPage( info );
01387 }
01388 
01389 void KMReaderWin::enableMsgDisplay() {
01390   mMsgDisplay = true;
01391   adjustLayout();
01392 }
01393 
01394 
01395 //-----------------------------------------------------------------------------
01396 
01397 void KMReaderWin::updateReaderWin()
01398 {
01399   if (!mMsgDisplay) return;
01400 
01401   mViewer->setOnlyLocalReferences(!htmlLoadExternal());
01402 
01403   htmlWriter()->reset();
01404 
01405   KMFolder* folder = 0;
01406   if (message(&folder))
01407   {
01408     if ( mShowColorbar )
01409       mColorBar->show();
01410     else
01411       mColorBar->hide();
01412     displayMessage();
01413   }
01414   else
01415   {
01416     mColorBar->hide();
01417     mMimePartTree->hide();
01418     mMimePartTree->clear();
01419     htmlWriter()->begin( mCSSHelper->cssDefinitions( isFixedFont() ) );
01420     htmlWriter()->write( mCSSHelper->htmlHead( isFixedFont() ) + "</body></html>" );
01421     htmlWriter()->end();
01422   }
01423 
01424   if (mSavedRelativePosition)
01425   {
01426     QScrollView * scrollview = static_cast<QScrollView *>(mViewer->widget());
01427     scrollview->setContentsPos( 0,
01428       qRound( scrollview->contentsHeight() * mSavedRelativePosition ) );
01429     mSavedRelativePosition = 0;
01430   }
01431 }
01432 
01433 //-----------------------------------------------------------------------------
01434 int KMReaderWin::pointsToPixel(int pointSize) const
01435 {
01436   const QPaintDeviceMetrics pdm(mViewer->view());
01437 
01438   return (pointSize * pdm.logicalDpiY() + 36) / 72;
01439 }
01440 
01441 //-----------------------------------------------------------------------------
01442 void KMReaderWin::showHideMimeTree( bool isPlainTextTopLevel ) {
01443   if ( mMimeTreeMode == 2 ||
01444        ( mMimeTreeMode == 1 && !isPlainTextTopLevel ) )
01445     mMimePartTree->show();
01446   else {
01447     // don't rely on QSplitter maintaining sizes for hidden widgets:
01448     KConfigGroup reader( KMKernel::config(), "Reader" );
01449     saveSplitterSizes( reader );
01450     mMimePartTree->hide();
01451   }
01452 }
01453 
01454 void KMReaderWin::displayMessage() {
01455   KMMessage * msg = message();
01456 
01457   mMimePartTree->clear();
01458   showHideMimeTree( !msg || // treat no message as "text/plain"
01459             ( msg->type() == DwMime::kTypeText
01460               && msg->subtype() == DwMime::kSubtypePlain ) );
01461 
01462   if ( !msg )
01463     return;
01464 
01465   msg->setOverrideCodec( overrideCodec() );
01466 
01467   htmlWriter()->begin( mCSSHelper->cssDefinitions( isFixedFont() ) );
01468   htmlWriter()->queue( mCSSHelper->htmlHead( isFixedFont() ) );
01469 
01470   if (!parent())
01471     setCaption(msg->subject());
01472 
01473   removeTempFiles();
01474 
01475   mColorBar->setNeutralMode();
01476 
01477   parseMsg(msg);
01478 
01479   if( mColorBar->isNeutral() )
01480     mColorBar->setNormalMode();
01481 
01482   htmlWriter()->queue("</body></html>");
01483   htmlWriter()->flush();
01484 
01485   QTimer::singleShot( 1, this, SLOT(injectAttachments()) );
01486 }
01487 
01488 static bool message_was_saved_decrypted_before( const KMMessage * msg ) {
01489   if ( !msg )
01490     return false;
01491   //kdDebug(5006) << "msgId = " << msg->msgId() << endl;
01492   return msg->msgId().stripWhiteSpace().startsWith( "<DecryptedMsg." );
01493 }
01494 
01495 //-----------------------------------------------------------------------------
01496 void KMReaderWin::parseMsg(KMMessage* aMsg)
01497 {
01498   KMMessagePart msgPart;
01499   QCString subtype, contDisp;
01500   QByteArray str;
01501 
01502   assert(aMsg!=0);
01503 
01504   aMsg->setIsBeingParsed( true );
01505 
01506   if ( mRootNode && !mRootNode->processed() )
01507   {
01508     kdWarning() << "The root node is not yet processed! Danger!\n";
01509     return;
01510   } else
01511     delete mRootNode;
01512   mRootNode = partNode::fromMessage( aMsg, this );
01513   const QCString mainCntTypeStr = mRootNode->typeString() + '/' + mRootNode->subTypeString();
01514 
01515   QString cntDesc = aMsg->subject();
01516   if( cntDesc.isEmpty() )
01517     cntDesc = i18n("( body part )");
01518   KIO::filesize_t cntSize = aMsg->msgSize();
01519   QString cntEnc;
01520   if( aMsg->contentTransferEncodingStr().isEmpty() )
01521     cntEnc = "7bit";
01522   else
01523     cntEnc = aMsg->contentTransferEncodingStr();
01524 
01525   // fill the MIME part tree viewer
01526   mRootNode->fillMimePartTree( 0,
01527                    mMimePartTree,
01528                    cntDesc,
01529                    mainCntTypeStr,
01530                    cntEnc,
01531                    cntSize );
01532 
01533   partNode* vCardNode = mRootNode->findType( DwMime::kTypeText, DwMime::kSubtypeXVCard );
01534   bool hasVCard = false;
01535   if( vCardNode ) {
01536     // ### FIXME: We should only do this if the vCard belongs to the sender,
01537     // ### i.e. if the sender's email address is contained in the vCard.
01538     KABC::VCardConverter t;
01539 #if defined(KABC_VCARD_ENCODING_FIX)
01540     const QByteArray vcard = vCardNode->msgPart().bodyDecodedBinary();
01541     if ( !t.parseVCardsRaw( vcard.data() ).empty() ) {
01542 #else
01543     const QString vcard = vCardNode->msgPart().bodyToUnicode( overrideCodec() );
01544     if ( !t.parseVCards( vcard ).empty() ) {
01545 #endif
01546       hasVCard = true;
01547       writeMessagePartToTempFile( &vCardNode->msgPart(), vCardNode->nodeId() );
01548     }
01549   }
01550 
01551   if ( !mRootNode || !mRootNode->isToltecMessage() || mShowRawToltecMail ) {
01552     htmlWriter()->queue( writeMsgHeader(aMsg, hasVCard ? vCardNode : 0, true ) );
01553   }
01554 
01555   // show message content
01556   ObjectTreeParser otp( this );
01557   otp.setAllowAsync( true );
01558   otp.setShowRawToltecMail( mShowRawToltecMail );
01559   otp.parseObjectTree( mRootNode );
01560 
01561   // store encrypted/signed status information in the KMMessage
01562   //  - this can only be done *after* calling parseObjectTree()
01563   KMMsgEncryptionState encryptionState = mRootNode->overallEncryptionState();
01564   KMMsgSignatureState  signatureState  = mRootNode->overallSignatureState();
01565   // Don't crash when switching message while GPG passphrase entry dialog is shown #53185
01566   if (aMsg != message()) {
01567     displayMessage();
01568     return;
01569   }
01570   aMsg->setEncryptionState( encryptionState );
01571   // Don't reset the signature state to "not signed" (e.g. if one canceled the
01572   // decryption of a signed messages which has already been decrypted before).
01573   if ( signatureState != KMMsgNotSigned ||
01574        aMsg->signatureState() == KMMsgSignatureStateUnknown ) {
01575     aMsg->setSignatureState( signatureState );
01576   }
01577 
01578   bool emitReplaceMsgByUnencryptedVersion = false;
01579   const KConfigGroup reader( KMKernel::config(), "Reader" );
01580   if ( reader.readBoolEntry( "store-displayed-messages-unencrypted", false ) ) {
01581 
01582   // Hack to make sure the S/MIME CryptPlugs follows the strict requirement
01583   // of german government:
01584   // --> All received encrypted messages *must* be stored in unencrypted form
01585   //     after they have been decrypted once the user has read them.
01586   //     ( "Aufhebung der Verschluesselung nach dem Lesen" )
01587   //
01588   // note: Since there is no configuration option for this, we do that for
01589   //       all kinds of encryption now - *not* just for S/MIME.
01590   //       This could be changed in the objectTreeToDecryptedMsg() function
01591   //       by deciding when (or when not, resp.) to set the 'dataNode' to
01592   //       something different than 'curNode'.
01593 
01594 
01595 kdDebug(5006) << "\n\n\nKMReaderWin::parseMsg()  -  special post-encryption handling:\n1." << endl;
01596 kdDebug(5006) << "(aMsg == msg) = "                               << (aMsg == message()) << endl;
01597 kdDebug(5006) << "aMsg->parent() && aMsg->parent() != kmkernel->outboxFolder() = " << (aMsg->parent() && aMsg->parent() != kmkernel->outboxFolder()) << endl;
01598 kdDebug(5006) << "message_was_saved_decrypted_before( aMsg ) = " << message_was_saved_decrypted_before( aMsg ) << endl;
01599 kdDebug(5006) << "this->decryptMessage() = " << decryptMessage() << endl;
01600 kdDebug(5006) << "otp.hasPendingAsyncJobs() = " << otp.hasPendingAsyncJobs() << endl;
01601 kdDebug(5006) << "   (KMMsgFullyEncrypted == encryptionState) = "     << (KMMsgFullyEncrypted == encryptionState) << endl;
01602 kdDebug(5006) << "|| (KMMsgPartiallyEncrypted == encryptionState) = " << (KMMsgPartiallyEncrypted == encryptionState) << endl;
01603          // only proceed if we were called the normal way - not by
01604          // double click on the message (==not running in a separate window)
01605   if(    (aMsg == message())
01606          // don't remove encryption in the outbox folder :)
01607       && ( aMsg->parent() && aMsg->parent() != kmkernel->outboxFolder() )
01608          // only proceed if this message was not saved encryptedly before
01609       && !message_was_saved_decrypted_before( aMsg )
01610          // only proceed if the message has actually been decrypted
01611       && decryptMessage()
01612          // only proceed if no pending async jobs are running:
01613       && !otp.hasPendingAsyncJobs()
01614          // only proceed if this message is (at least partially) encrypted
01615       && (    (KMMsgFullyEncrypted == encryptionState)
01616            || (KMMsgPartiallyEncrypted == encryptionState) ) ) {
01617 
01618 kdDebug(5006) << "KMReaderWin  -  calling objectTreeToDecryptedMsg()" << endl;
01619 
01620     NewByteArray decryptedData;
01621     // note: The following call may change the message's headers.
01622     objectTreeToDecryptedMsg( mRootNode, decryptedData, *aMsg );
01623     // add a \0 to the data
01624     decryptedData.appendNULL();
01625     QCString resultString( decryptedData.data() );
01626 kdDebug(5006) << "KMReaderWin  -  resulting data:" << resultString << endl;
01627 
01628     if( !resultString.isEmpty() ) {
01629 kdDebug(5006) << "KMReaderWin  -  composing unencrypted message" << endl;
01630       // try this:
01631       aMsg->setBody( resultString );
01632       KMMessage* unencryptedMessage = new KMMessage( *aMsg );
01633       unencryptedMessage->setParent( 0 );
01634       // because this did not work:
01635       /*
01636       DwMessage dwMsg( aMsg->asDwString() );
01637       dwMsg.Body() = DwBody( DwString( resultString.data() ) );
01638       dwMsg.Body().Parse();
01639       KMMessage* unencryptedMessage = new KMMessage( &dwMsg );
01640       */
01641       //kdDebug(5006) << "KMReaderWin  -  resulting message:" << unencryptedMessage->asString() << endl;
01642       kdDebug(5006) << "KMReaderWin  -  attach unencrypted message to aMsg" << endl;
01643       aMsg->setUnencryptedMsg( unencryptedMessage );
01644       emitReplaceMsgByUnencryptedVersion = true;
01645     }
01646   }
01647   }
01648 
01649   // save current main Content-Type before deleting mRootNode
01650   const int rootNodeCntType = mRootNode ? mRootNode->type() : DwMime::kTypeText;
01651   const int rootNodeCntSubtype = mRootNode ? mRootNode->subType() : DwMime::kSubtypePlain;
01652 
01653   // store message id to avoid endless recursions
01654   setIdOfLastViewedMessage( aMsg->msgId() );
01655 
01656   if( emitReplaceMsgByUnencryptedVersion ) {
01657     kdDebug(5006) << "KMReaderWin  -  invoce saving in decrypted form:" << endl;
01658     emit replaceMsgByUnencryptedVersion();
01659   } else {
01660     kdDebug(5006) << "KMReaderWin  -  finished parsing and displaying of message." << endl;
01661     showHideMimeTree( rootNodeCntType == DwMime::kTypeText &&
01662               rootNodeCntSubtype == DwMime::kSubtypePlain );
01663   }
01664 
01665   aMsg->setIsBeingParsed( false );
01666 }
01667 
01668 
01669 //-----------------------------------------------------------------------------
01670 QString KMReaderWin::writeMsgHeader( KMMessage* aMsg, partNode *vCardNode, bool topLevel )
01671 {
01672   kdFatal( !headerStyle(), 5006 )
01673     << "trying to writeMsgHeader() without a header style set!" << endl;
01674   kdFatal( !headerStrategy(), 5006 )
01675     << "trying to writeMsgHeader() without a header strategy set!" << endl;
01676   QString href;
01677   if ( vCardNode )
01678     href = vCardNode->asHREF( "body" );
01679 
01680   return headerStyle()->format( aMsg, headerStrategy(), href, mPrinting, topLevel );
01681 }
01682 
01683 
01684 
01685 //-----------------------------------------------------------------------------
01686 QString KMReaderWin::writeMessagePartToTempFile( KMMessagePart* aMsgPart,
01687                                                  int aPartNum )
01688 {
01689   QString fileName = aMsgPart->fileName();
01690   if( fileName.isEmpty() )
01691     fileName = aMsgPart->name();
01692 
01693   //--- Sven's save attachments to /tmp start ---
01694   QString fname = createTempDir( QString::number( aPartNum ) );
01695   if ( fname.isEmpty() )
01696     return QString();
01697 
01698   // strip off a leading path
01699   int slashPos = fileName.findRev( '/' );
01700   if( -1 != slashPos )
01701     fileName = fileName.mid( slashPos + 1 );
01702   if( fileName.isEmpty() )
01703     fileName = "unnamed";
01704   fname += "/" + fileName;
01705 
01706   QByteArray data = aMsgPart->bodyDecodedBinary();
01707   size_t size = data.size();
01708   if ( aMsgPart->type() == DwMime::kTypeText && size) {
01709     // convert CRLF to LF before writing text attachments to disk
01710     size = KMail::Util::crlf2lf( data.data(), size );
01711   }
01712   if( !KPIM::kBytesToFile( data.data(), size, fname, false, false, false ) )
01713     return QString::null;
01714 
01715   mTempFiles.append( fname );
01716   // make file read-only so that nobody gets the impression that he might
01717   // edit attached files (cf. bug #52813)
01718   ::chmod( QFile::encodeName( fname ), S_IRUSR );
01719 
01720   return fname;
01721 }
01722 
01723 QString KMReaderWin::createTempDir( const QString &param )
01724 {
01725   KTempFile *tempFile = new KTempFile( QString::null, "." + param );
01726   tempFile->setAutoDelete( true );
01727   QString fname = tempFile->name();
01728   delete tempFile;
01729 
01730   if( ::access( QFile::encodeName( fname ), W_OK ) != 0 )
01731     // Not there or not writable
01732     if( ::mkdir( QFile::encodeName( fname ), 0 ) != 0
01733         || ::chmod( QFile::encodeName( fname ), S_IRWXU ) != 0 )
01734       return QString::null; //failed create
01735 
01736   assert( !fname.isNull() );
01737 
01738   mTempDirs.append( fname );
01739   return fname;
01740 }
01741 
01742 //-----------------------------------------------------------------------------
01743 void KMReaderWin::showVCard( KMMessagePart *msgPart )
01744 {
01745 #if defined(KABC_VCARD_ENCODING_FIX)
01746   const QByteArray vCard = msgPart->bodyDecodedBinary();
01747 #else
01748   const QString vCard = msgPart->bodyToUnicode( overrideCodec() );
01749 #endif
01750   VCardViewer *vcv = new VCardViewer( this, vCard, "vCardDialog" );
01751   vcv->show();
01752 }
01753 
01754 //-----------------------------------------------------------------------------
01755 void KMReaderWin::printMsg()
01756 {
01757   if (!message()) return;
01758   mViewer->view()->print();
01759 }
01760 
01761 
01762 //-----------------------------------------------------------------------------
01763 int KMReaderWin::msgPartFromUrl(const KURL &aUrl)
01764 {
01765   if (aUrl.isEmpty()) return -1;
01766   if (!aUrl.isLocalFile()) return -1;
01767 
01768   QString path = aUrl.path();
01769   uint right = path.findRev('/');
01770   uint left = path.findRev('.', right);
01771 
01772   bool ok;
01773   int res = path.mid(left + 1, right - left - 1).toInt(&ok);
01774   return (ok) ? res : -1;
01775 }
01776 
01777 
01778 //-----------------------------------------------------------------------------
01779 void KMReaderWin::resizeEvent(QResizeEvent *)
01780 {
01781   if( !mResizeTimer.isActive() )
01782   {
01783     //
01784     // Combine all resize operations that are requested as long a
01785     // the timer runs.
01786     //
01787     mResizeTimer.start( 100, true );
01788   }
01789 }
01790 
01791 
01792 //-----------------------------------------------------------------------------
01793 void KMReaderWin::slotDelayedResize()
01794 {
01795   mSplitter->setGeometry(0, 0, width(), height());
01796 }
01797 
01798 
01799 //-----------------------------------------------------------------------------
01800 void KMReaderWin::slotTouchMessage()
01801 {
01802   if ( !message() )
01803     return;
01804 
01805   if ( !message()->isNew() && !message()->isUnread() )
01806     return;
01807 
01808   SerNumList serNums;
01809   serNums.append( message()->getMsgSerNum() );
01810   KMCommand *command = new KMSetStatusCommand( KMMsgStatusRead, serNums );
01811   command->start();
01812 
01813   // should we send an MDN?
01814   if ( mNoMDNsWhenEncrypted &&
01815        message()->encryptionState() != KMMsgNotEncrypted &&
01816        message()->encryptionState() != KMMsgEncryptionStateUnknown )
01817     return;
01818 
01819   KMFolder *folder = message()->parent();
01820   if (folder &&
01821      (folder->isOutbox() || folder->isSent() || folder->isTrash() ||
01822       folder->isDrafts() || folder->isTemplates() ) )
01823     return;
01824 
01825   if ( KMMessage * receipt = message()->createMDN( MDN::ManualAction,
01826                            MDN::Displayed,
01827                            true /* allow GUI */ ) )
01828     if ( !kmkernel->msgSender()->send( receipt ) ) // send or queue
01829       KMessageBox::error( this, i18n("Could not send MDN.") );
01830 }
01831 
01832 
01833 //-----------------------------------------------------------------------------
01834 void KMReaderWin::closeEvent(QCloseEvent *e)
01835 {
01836   QWidget::closeEvent(e);
01837   writeConfig();
01838 }
01839 
01840 
01841 bool foundSMIMEData( const QString aUrl,
01842                      QString& displayName,
01843                      QString& libName,
01844                      QString& keyId )
01845 {
01846   static QString showCertMan("showCertificate#");
01847   displayName = "";
01848   libName = "";
01849   keyId = "";
01850   int i1 = aUrl.find( showCertMan );
01851   if( -1 < i1 ) {
01852     i1 += showCertMan.length();
01853     int i2 = aUrl.find(" ### ", i1);
01854     if( i1 < i2 )
01855     {
01856       displayName = aUrl.mid( i1, i2-i1 );
01857       i1 = i2+5;
01858       i2 = aUrl.find(" ### ", i1);
01859       if( i1 < i2 )
01860       {
01861         libName = aUrl.mid( i1, i2-i1 );
01862         i2 += 5;
01863 
01864         keyId = aUrl.mid( i2 );
01865         /*
01866         int len = aUrl.length();
01867         if( len > i2+1 ) {
01868           keyId = aUrl.mid( i2, 2 );
01869           i2 += 2;
01870           while( len > i2+1 ) {
01871             keyId += ':';
01872             keyId += aUrl.mid( i2, 2 );
01873             i2 += 2;
01874           }
01875         }
01876         */
01877       }
01878     }
01879   }
01880   return !keyId.isEmpty();
01881 }
01882 
01883 
01884 //-----------------------------------------------------------------------------
01885 void KMReaderWin::slotUrlOn(const QString &aUrl)
01886 {
01887   const KURL url(aUrl);
01888 
01889   if ( url.protocol() == "kmail" || url.protocol() == "x-kmail" || url.protocol() == "attachment"
01890        || (url.protocol().isEmpty() && url.path().isEmpty()) ) {
01891     mViewer->setDNDEnabled( false );
01892   } else {
01893     mViewer->setDNDEnabled( true );
01894   }
01895 
01896   if ( aUrl.stripWhiteSpace().isEmpty() ) {
01897     KPIM::BroadcastStatus::instance()->reset();
01898     mHoveredUrl = KURL();
01899     mLastClickImagePath = QString();
01900     return;
01901   }
01902 
01903   mHoveredUrl = url;
01904 
01905   const QString msg = URLHandlerManager::instance()->statusBarMessage( url, this );
01906 
01907   kdWarning( msg.isEmpty(), 5006 ) << "KMReaderWin::slotUrlOn(): Unhandled URL hover!" << endl;
01908   KPIM::BroadcastStatus::instance()->setTransientStatusMsg( msg );
01909 }
01910 
01911 
01912 //-----------------------------------------------------------------------------
01913 void KMReaderWin::slotUrlOpen(const KURL &aUrl, const KParts::URLArgs &)
01914 {
01915   mClickedUrl = aUrl;
01916 
01917   if ( URLHandlerManager::instance()->handleClick( aUrl, this ) )
01918     return;
01919 
01920   kdWarning( 5006 ) << "KMReaderWin::slotOpenUrl(): Unhandled URL click!" << endl;
01921   emit urlClicked( aUrl, Qt::LeftButton );
01922 }
01923 
01924 //-----------------------------------------------------------------------------
01925 void KMReaderWin::slotUrlPopup(const QString &aUrl, const QPoint& aPos)
01926 {
01927   const KURL url( aUrl );
01928   mClickedUrl = url;
01929 
01930   if ( url.protocol() == "mailto" ) {
01931     mCopyURLAction->setText( i18n( "Copy Email Address" ) );
01932   } else {
01933     mCopyURLAction->setText( i18n( "Copy Link Address" ) );
01934   }
01935 
01936   if ( URLHandlerManager::instance()->handleContextMenuRequest( url, aPos, this ) )
01937     return;
01938 
01939   if ( message() ) {
01940     kdWarning( 5006 ) << "KMReaderWin::slotUrlPopup(): Unhandled URL right-click!" << endl;
01941     emitPopupMenu( url, aPos );
01942   }
01943 }
01944 
01945 // Checks if the given node has a parent node that is a DIV which has an ID attribute
01946 // with the value specified here
01947 static bool hasParentDivWithId( const DOM::Node &start, const QString &id )
01948 {
01949   if ( start.isNull() )
01950     return false;
01951 
01952   if ( start.nodeName().string() == "div" ) {
01953     for ( unsigned int i = 0; i < start.attributes().length(); i++ ) {
01954       if ( start.attributes().item( i ).nodeName().string() == "id" &&
01955            start.attributes().item( i ).nodeValue().string() == id )
01956         return true;
01957     }
01958   }
01959 
01960   if ( !start.parentNode().isNull() )
01961     return hasParentDivWithId( start.parentNode(), id );
01962   else return false;
01963 }
01964 
01965 //-----------------------------------------------------------------------------
01966 void KMReaderWin::showAttachmentPopup( int id, const QString & name, const QPoint & p )
01967 {
01968   mAtmCurrent = id;
01969   mAtmCurrentName = name;
01970   KPopupMenu *menu = new KPopupMenu();
01971   menu->insertItem(SmallIcon("fileopen"),i18n("to open", "Open"), 1);
01972   menu->insertItem(i18n("Open With..."), 2);
01973   menu->insertItem(i18n("to view something", "View"), 3);
01974   menu->insertItem(SmallIcon("filesaveas"),i18n("Save As..."), 4);
01975   menu->insertItem(SmallIcon("editcopy"), i18n("Copy"), 9 );
01976   const bool canChange = message()->parent() ? !message()->parent()->isReadOnly() : false;
01977   if ( GlobalSettings::self()->allowAttachmentEditing() && canChange )
01978     menu->insertItem(SmallIcon("edit"), i18n("Edit Attachment"), 8 );
01979   if ( GlobalSettings::self()->allowAttachmentDeletion() && canChange )
01980     menu->insertItem(SmallIcon("editdelete"), i18n("Delete Attachment"), 7 );
01981   if ( name.endsWith( ".xia", false ) &&
01982        Kleo::CryptoBackendFactory::instance()->protocol( "Chiasmus" ) )
01983     menu->insertItem( i18n( "Decrypt With Chiasmus..." ), 6 );
01984   menu->insertItem(i18n("Properties"), 5);
01985 
01986   const bool attachmentInHeader = hasParentDivWithId( mViewer->nodeUnderMouse(), "attachmentInjectionPoint" );
01987   const bool hasScrollbar = mViewer->view()->verticalScrollBar()->isVisible();
01988   if ( attachmentInHeader && hasScrollbar ) {
01989     menu->insertItem( i18n("Scroll To"), 10 );
01990   }
01991 
01992   connect(menu, SIGNAL(activated(int)), this, SLOT(slotHandleAttachment(int)));
01993   menu->exec( p ,0 );
01994   delete menu;
01995 }
01996 
01997 //-----------------------------------------------------------------------------
01998 void KMReaderWin::setStyleDependantFrameWidth()
01999 {
02000   if ( !mBox )
02001     return;
02002   // set the width of the frame to a reasonable value for the current GUI style
02003   int frameWidth;
02004   if( style().isA("KeramikStyle") )
02005     frameWidth = style().pixelMetric( QStyle::PM_DefaultFrameWidth ) - 1;
02006   else
02007     frameWidth = style().pixelMetric( QStyle::PM_DefaultFrameWidth );
02008   if ( frameWidth < 0 )
02009     frameWidth = 0;
02010   if ( frameWidth != mBox->lineWidth() )
02011     mBox->setLineWidth( frameWidth );
02012 }
02013 
02014 //-----------------------------------------------------------------------------
02015 void KMReaderWin::styleChange( QStyle& oldStyle )
02016 {
02017   setStyleDependantFrameWidth();
02018   QWidget::styleChange( oldStyle );
02019 }
02020 
02021 //-----------------------------------------------------------------------------
02022 void KMReaderWin::slotHandleAttachment( int choice )
02023 {
02024   mAtmUpdate = true;
02025   partNode* node = mRootNode ? mRootNode->findId( mAtmCurrent ) : 0;
02026   if ( mAtmCurrentName.isEmpty() && node )
02027     mAtmCurrentName = tempFileUrlFromPartNode( node ).path();
02028   if ( choice < 7 ) {
02029   KMHandleAttachmentCommand* command = new KMHandleAttachmentCommand(
02030       node, message(), mAtmCurrent, mAtmCurrentName,
02031       KMHandleAttachmentCommand::AttachmentAction( choice ), 0, this );
02032   connect( command, SIGNAL( showAttachment( int, const QString& ) ),
02033       this, SLOT( slotAtmView( int, const QString& ) ) );
02034   command->start();
02035   } else if ( choice == 7 ) {
02036     slotDeleteAttachment( node );
02037   } else if ( choice == 8 ) {
02038     slotEditAttachment( node );
02039   } else if ( choice == 9 ) {
02040     if ( !node ) return;
02041     KURL::List urls;
02042     KURL url = tempFileUrlFromPartNode( node );
02043     if (!url.isValid() ) return;
02044     urls.append( url );
02045     KURLDrag* drag = new KURLDrag( urls, this );
02046     QApplication::clipboard()->setData( drag, QClipboard::Clipboard );
02047   } else if ( choice == 10 ) { // Scroll To
02048     scrollToAttachment( node );
02049   }
02050 }
02051 
02052 //-----------------------------------------------------------------------------
02053 void KMReaderWin::slotFind()
02054 {
02055   mViewer->findText();
02056 }
02057 
02058 //-----------------------------------------------------------------------------
02059 void KMReaderWin::slotFindNext()
02060 {
02061   mViewer->findTextNext();
02062 }
02063 
02064 //-----------------------------------------------------------------------------
02065 void KMReaderWin::slotToggleFixedFont()
02066 {
02067   mUseFixedFont = !mUseFixedFont;
02068   saveRelativePosition();
02069   update(true);
02070 }
02071 
02072 
02073 //-----------------------------------------------------------------------------
02074 void KMReaderWin::slotCopySelectedText()
02075 {
02076   kapp->clipboard()->setText( mViewer->selectedText() );
02077 }
02078 
02079 
02080 //-----------------------------------------------------------------------------
02081 void KMReaderWin::atmViewMsg( KMMessagePart* aMsgPart, int nodeId )
02082 {
02083   assert(aMsgPart!=0);
02084   KMMessage* msg = new KMMessage;
02085   msg->fromString(aMsgPart->bodyDecoded());
02086   assert(msg != 0);
02087   msg->setMsgSerNum( 0 ); // because lookups will fail
02088   // some information that is needed for imap messages with LOD
02089   msg->setParent( message()->parent() );
02090   msg->setUID(message()->UID());
02091   msg->setReadyToShow(true);
02092   KMReaderMainWin *win = new KMReaderMainWin();
02093   win->showMsg( overrideEncoding(), msg, message()->getMsgSerNum(), nodeId );
02094   win->show();
02095 }
02096 
02097 
02098 void KMReaderWin::setMsgPart( partNode * node ) {
02099   htmlWriter()->reset();
02100   mColorBar->hide();
02101   htmlWriter()->begin( mCSSHelper->cssDefinitions( isFixedFont() ) );
02102   htmlWriter()->write( mCSSHelper->htmlHead( isFixedFont() ) );
02103   // end ###
02104   if ( node ) {
02105     ObjectTreeParser otp( this, 0, true );
02106     otp.parseObjectTree( node );
02107   }
02108   // ### this, too
02109   htmlWriter()->queue( "</body></html>" );
02110   htmlWriter()->flush();
02111 }
02112 
02113 //-----------------------------------------------------------------------------
02114 void KMReaderWin::setMsgPart( KMMessagePart* aMsgPart, bool aHTML,
02115                   const QString& aFileName, const QString& pname )
02116 {
02117   KCursorSaver busy(KBusyPtr::busy());
02118   if (kasciistricmp(aMsgPart->typeStr(), "message")==0) {
02119       // if called from compose win
02120       KMMessage* msg = new KMMessage;
02121       assert(aMsgPart!=0);
02122       msg->fromString(aMsgPart->bodyDecoded());
02123       mMainWindow->setCaption(msg->subject());
02124       setMsg(msg, true);
02125       setAutoDelete(true);
02126   } else if (kasciistricmp(aMsgPart->typeStr(), "text")==0) {
02127       if (kasciistricmp(aMsgPart->subtypeStr(), "x-vcard") == 0) {
02128         showVCard( aMsgPart );
02129     return;
02130       }
02131       htmlWriter()->begin( mCSSHelper->cssDefinitions( isFixedFont() ) );
02132       htmlWriter()->queue( mCSSHelper->htmlHead( isFixedFont() ) );
02133 
02134       if (aHTML && (kasciistricmp(aMsgPart->subtypeStr(), "html")==0)) { // HTML
02135         // ### this is broken. It doesn't stip off the HTML header and footer!
02136         htmlWriter()->queue( aMsgPart->bodyToUnicode( overrideCodec() ) );
02137         mColorBar->setHtmlMode();
02138       } else { // plain text
02139         const QCString str = aMsgPart->bodyDecoded();
02140         ObjectTreeParser otp( this );
02141         otp.writeBodyStr( str,
02142                           overrideCodec() ? overrideCodec() : aMsgPart->codec(),
02143                           message() ? message()->from() : QString::null );
02144       }
02145       htmlWriter()->queue("</body></html>");
02146       htmlWriter()->flush();
02147       mMainWindow->setCaption(i18n("View Attachment: %1").arg(pname));
02148   } else if (kasciistricmp(aMsgPart->typeStr(), "image")==0 ||
02149              (kasciistricmp(aMsgPart->typeStr(), "application")==0 &&
02150               kasciistricmp(aMsgPart->subtypeStr(), "postscript")==0))
02151   {
02152       if (aFileName.isEmpty()) return;  // prevent crash
02153       // Open the window with a size so the image fits in (if possible):
02154       QImageIO *iio = new QImageIO();
02155       iio->setFileName(aFileName);
02156       if( iio->read() ) {
02157           QImage img = iio->image();
02158           QRect desk = KGlobalSettings::desktopGeometry(mMainWindow);
02159           // determine a reasonable window size
02160           int width, height;
02161           if( img.width() < 50 )
02162               width = 70;
02163           else if( img.width()+20 < desk.width() )
02164               width = img.width()+20;
02165           else
02166               width = desk.width();
02167           if( img.height() < 50 )
02168               height = 70;
02169           else if( img.height()+20 < desk.height() )
02170               height = img.height()+20;
02171           else
02172               height = desk.height();
02173           mMainWindow->resize( width, height );
02174       }
02175       // Just write the img tag to HTML:
02176       htmlWriter()->begin( mCSSHelper->cssDefinitions( isFixedFont() ) );
02177       htmlWriter()->write( mCSSHelper->htmlHead( isFixedFont() ) );
02178       htmlWriter()->write( "<img src=\"file:" +
02179                            KURL::encode_string( aFileName ) +
02180                            "\" border=\"0\">\n"
02181                            "</body></html>\n" );
02182       htmlWriter()->end();
02183       setCaption( i18n("View Attachment: %1").arg( pname ) );
02184       show();
02185       delete iio;
02186   } else {
02187     htmlWriter()->begin( mCSSHelper->cssDefinitions( isFixedFont() ) );
02188     htmlWriter()->queue( mCSSHelper->htmlHead( isFixedFont() ) );
02189     htmlWriter()->queue( "<pre>" );
02190 
02191     QString str = aMsgPart->bodyDecoded();
02192     // A QString cannot handle binary data. So if it's shorter than the
02193     // attachment, we assume the attachment is binary:
02194     if( str.length() < (unsigned) aMsgPart->decodedSize() ) {
02195       str.prepend( i18n("[KMail: Attachment contains binary data. Trying to show first character.]",
02196           "[KMail: Attachment contains binary data. Trying to show first %n characters.]",
02197           str.length()) + QChar('\n') );
02198     }
02199     htmlWriter()->queue( QStyleSheet::escape( str ) );
02200     htmlWriter()->queue( "</pre>" );
02201     htmlWriter()->queue("</body></html>");
02202     htmlWriter()->flush();
02203     mMainWindow->setCaption(i18n("View Attachment: %1").arg(pname));
02204   }
02205   // ---Sven's view text, html and image attachments in html widget end ---
02206 }
02207 
02208 
02209 //-----------------------------------------------------------------------------
02210 void KMReaderWin::slotAtmView( int id, const QString& name )
02211 {
02212   partNode* node = mRootNode ? mRootNode->findId( id ) : 0;
02213   if( node ) {
02214     mAtmCurrent = id;
02215     mAtmCurrentName = name;
02216     if ( mAtmCurrentName.isEmpty() )
02217       mAtmCurrentName = tempFileUrlFromPartNode( node ).path();
02218 
02219     KMMessagePart& msgPart = node->msgPart();
02220     QString pname = msgPart.fileName();
02221     if (pname.isEmpty()) pname=msgPart.name();
02222     if (pname.isEmpty()) pname=msgPart.contentDescription();
02223     if (pname.isEmpty()) pname="unnamed";
02224     // image Attachment is saved already
02225     if (kasciistricmp(msgPart.typeStr(), "message")==0) {
02226       atmViewMsg( &msgPart,id );
02227     } else if ((kasciistricmp(msgPart.typeStr(), "text")==0) &&
02228            (kasciistricmp(msgPart.subtypeStr(), "x-vcard")==0)) {
02229       setMsgPart( &msgPart, htmlMail(), name, pname );
02230     } else {
02231       KMReaderMainWin *win = new KMReaderMainWin(&msgPart, htmlMail(),
02232           name, pname, overrideEncoding() );
02233       win->show();
02234     }
02235   }
02236 }
02237 
02238 //-----------------------------------------------------------------------------
02239 void KMReaderWin::openAttachment( int id, const QString & name )
02240 {
02241   mAtmCurrentName = name;
02242   mAtmCurrent = id;
02243 
02244   QString str, pname, cmd, fileName;
02245 
02246   partNode* node = mRootNode ? mRootNode->findId( id ) : 0;
02247   if( !node ) {
02248     kdWarning(5006) << "KMReaderWin::openAttachment - could not find node " << id << endl;
02249     return;
02250   }
02251   if ( mAtmCurrentName.isEmpty() )
02252     mAtmCurrentName = tempFileUrlFromPartNode( node ).path();
02253 
02254   KMMessagePart& msgPart = node->msgPart();
02255   if (kasciistricmp(msgPart.typeStr(), "message")==0)
02256   {
02257     atmViewMsg( &msgPart, id );
02258     return;
02259   }
02260 
02261   QCString contentTypeStr( msgPart.typeStr() + '/' + msgPart.subtypeStr() );
02262   KPIM::kAsciiToLower( contentTypeStr.data() );
02263 
02264   if ( qstrcmp( contentTypeStr, "text/x-vcard" ) == 0 ) {
02265     showVCard( &msgPart );
02266     return;
02267   }
02268 
02269   // determine the MIME type of the attachment
02270   KMimeType::Ptr mimetype;
02271   // prefer the value of the Content-Type header
02272   mimetype = KMimeType::mimeType( QString::fromLatin1( contentTypeStr ) );
02273   if ( mimetype->name() == "application/octet-stream" ) {
02274     // consider the filename if Content-Type is application/octet-stream
02275     mimetype = KMimeType::findByPath( name, 0, true /* no disk access */ );
02276   }
02277   if ( ( mimetype->name() == "application/octet-stream" )
02278        && msgPart.isComplete() ) {
02279     // consider the attachment's contents if neither the Content-Type header
02280     // nor the filename give us a clue
02281     mimetype = KMimeType::findByFileContent( name );
02282   }
02283 
02284   KService::Ptr offer =
02285     KServiceTypeProfile::preferredService( mimetype->name(), "Application" );
02286 
02287   QString open_text;
02288   QString filenameText = msgPart.fileName();
02289   if ( filenameText.isEmpty() )
02290     filenameText = msgPart.name();
02291   if ( offer ) {
02292     open_text = i18n("&Open with '%1'").arg( offer->name() );
02293   } else {
02294     open_text = i18n("&Open With...");
02295   }
02296   const QString text = i18n("Open attachment '%1'?\n"
02297                             "Note that opening an attachment may compromise "
02298                             "your system's security.")
02299                        .arg( filenameText );
02300   const int choice = KMessageBox::questionYesNoCancel( this, text,
02301       i18n("Open Attachment?"), KStdGuiItem::saveAs(), open_text,
02302       QString::fromLatin1("askSave") + mimetype->name() ); // dontAskAgainName
02303 
02304   if( choice == KMessageBox::Yes ) {        // Save
02305     mAtmUpdate = true;
02306     KMHandleAttachmentCommand* command = new KMHandleAttachmentCommand( node,
02307         message(), mAtmCurrent, mAtmCurrentName, KMHandleAttachmentCommand::Save,
02308         offer, this );
02309     connect( command, SIGNAL( showAttachment( int, const QString& ) ),
02310         this, SLOT( slotAtmView( int, const QString& ) ) );
02311     command->start();
02312   }
02313   else if( choice == KMessageBox::No ) {    // Open
02314     KMHandleAttachmentCommand::AttachmentAction action = ( offer ?
02315         KMHandleAttachmentCommand::Open : KMHandleAttachmentCommand::OpenWith );
02316     mAtmUpdate = true;
02317     KMHandleAttachmentCommand* command = new KMHandleAttachmentCommand( node,
02318         message(), mAtmCurrent, mAtmCurrentName, action, offer, this );
02319     connect( command, SIGNAL( showAttachment( int, const QString& ) ),
02320         this, SLOT( slotAtmView( int, const QString& ) ) );
02321     command->start();
02322   } else {                  // Cancel
02323     kdDebug(5006) << "Canceled opening attachment" << endl;
02324   }
02325 }
02326 
02327 //-----------------------------------------------------------------------------
02328 void KMReaderWin::slotScrollUp()
02329 {
02330   static_cast<QScrollView *>(mViewer->widget())->scrollBy(0, -10);
02331 }
02332 
02333 
02334 //-----------------------------------------------------------------------------
02335 void KMReaderWin::slotScrollDown()
02336 {
02337   static_cast<QScrollView *>(mViewer->widget())->scrollBy(0, 10);
02338 }
02339 
02340 bool KMReaderWin::atBottom() const
02341 {
02342     const QScrollView *view = static_cast<const QScrollView *>(mViewer->widget());
02343     return view->contentsY() + view->visibleHeight() >= view->contentsHeight();
02344 }
02345 
02346 //-----------------------------------------------------------------------------
02347 void KMReaderWin::slotJumpDown()
02348 {
02349     QScrollView *view = static_cast<QScrollView *>(mViewer->widget());
02350     int offs = (view->clipper()->height() < 30) ? view->clipper()->height() : 30;
02351     view->scrollBy( 0, view->clipper()->height() - offs );
02352 }
02353 
02354 //-----------------------------------------------------------------------------
02355 void KMReaderWin::slotScrollPrior()
02356 {
02357   static_cast<QScrollView *>(mViewer->widget())->scrollBy(0, -(int)(height()*0.8));
02358 }
02359 
02360 
02361 //-----------------------------------------------------------------------------
02362 void KMReaderWin::slotScrollNext()
02363 {
02364   static_cast<QScrollView *>(mViewer->widget())->scrollBy(0, (int)(height()*0.8));
02365 }
02366 
02367 //-----------------------------------------------------------------------------
02368 void KMReaderWin::slotDocumentChanged()
02369 {
02370 
02371 }
02372 
02373 
02374 //-----------------------------------------------------------------------------
02375 void KMReaderWin::slotTextSelected(bool)
02376 {
02377   QString temp = mViewer->selectedText();
02378   kapp->clipboard()->setText(temp);
02379 }
02380 
02381 //-----------------------------------------------------------------------------
02382 void KMReaderWin::selectAll()
02383 {
02384   mViewer->selectAll();
02385 }
02386 
02387 //-----------------------------------------------------------------------------
02388 QString KMReaderWin::copyText()
02389 {
02390   QString temp = mViewer->selectedText();
02391   return temp;
02392 }
02393 
02394 
02395 //-----------------------------------------------------------------------------
02396 void KMReaderWin::slotDocumentDone()
02397 {
02398   // mSbVert->setValue(0);
02399 }
02400 
02401 
02402 //-----------------------------------------------------------------------------
02403 void KMReaderWin::setHtmlOverride(bool override)
02404 {
02405   mHtmlOverride = override;
02406   if (message())
02407       message()->setDecodeHTML(htmlMail());
02408 }
02409 
02410 
02411 //-----------------------------------------------------------------------------
02412 void KMReaderWin::setHtmlLoadExtOverride(bool override)
02413 {
02414   mHtmlLoadExtOverride = override;
02415   //if (message())
02416   //    message()->setDecodeHTML(htmlMail());
02417 }
02418 
02419 
02420 //-----------------------------------------------------------------------------
02421 bool KMReaderWin::htmlMail()
02422 {
02423   return ((mHtmlMail && !mHtmlOverride) || (!mHtmlMail && mHtmlOverride));
02424 }
02425 
02426 
02427 //-----------------------------------------------------------------------------
02428 bool KMReaderWin::htmlLoadExternal()
02429 {
02430   return ((mHtmlLoadExternal && !mHtmlLoadExtOverride) ||
02431           (!mHtmlLoadExternal && mHtmlLoadExtOverride));
02432 }
02433 
02434 
02435 //-----------------------------------------------------------------------------
02436 void KMReaderWin::saveRelativePosition()
02437 {
02438   const QScrollView * scrollview = static_cast<QScrollView *>( mViewer->widget() );
02439   mSavedRelativePosition =
02440     static_cast<float>( scrollview->contentsY() ) / scrollview->contentsHeight();
02441 }
02442 
02443 
02444 //-----------------------------------------------------------------------------
02445 void KMReaderWin::update( bool force )
02446 {
02447   KMMessage* msg = message();
02448   if ( msg )
02449     setMsg( msg, force, true /* updateOnly */ );
02450 }
02451 
02452 
02453 //-----------------------------------------------------------------------------
02454 KMMessage* KMReaderWin::message( KMFolder** aFolder ) const
02455 {
02456   KMFolder*  tmpFolder;
02457   KMFolder*& folder = aFolder ? *aFolder : tmpFolder;
02458   folder = 0;
02459   if (mMessage)
02460       return mMessage;
02461   if (mLastSerNum) {
02462     KMMessage *message = 0;
02463     int index;
02464     KMMsgDict::instance()->getLocation( mLastSerNum, &folder, &index );
02465     if (folder )
02466       message = folder->getMsg( index );
02467     if (!message)
02468       kdWarning(5006) << "Attempt to reference invalid serial number " << mLastSerNum << "\n" << endl;
02469     return message;
02470   }
02471   return 0;
02472 }
02473 
02474 
02475 
02476 //-----------------------------------------------------------------------------
02477 void KMReaderWin::slotUrlClicked()
02478 {
02479   KMMainWidget *mainWidget = dynamic_cast<KMMainWidget*>(mMainWindow);
02480   uint identity = 0;
02481   if ( message() && message()->parent() ) {
02482     identity = message()->parent()->identity();
02483   }
02484 
02485   KMCommand *command = new KMUrlClickedCommand( mClickedUrl, identity, this,
02486                         false, mainWidget );
02487   command->start();
02488 }
02489 
02490 //-----------------------------------------------------------------------------
02491 void KMReaderWin::slotMailtoCompose()
02492 {
02493   KMCommand *command = new KMMailtoComposeCommand( mClickedUrl, message() );
02494   command->start();
02495 }
02496 
02497 //-----------------------------------------------------------------------------
02498 void KMReaderWin::slotMailtoForward()
02499 {
02500   KMCommand *command = new KMMailtoForwardCommand( mMainWindow, mClickedUrl,
02501                            message() );
02502   command->start();
02503 }
02504 
02505 //-----------------------------------------------------------------------------
02506 void KMReaderWin::slotMailtoAddAddrBook()
02507 {
02508   KMCommand *command = new KMMailtoAddAddrBookCommand( mClickedUrl,
02509                                mMainWindow);
02510   command->start();
02511 }
02512 
02513 //-----------------------------------------------------------------------------
02514 void KMReaderWin::slotMailtoOpenAddrBook()
02515 {
02516   KMCommand *command = new KMMailtoOpenAddrBookCommand( mClickedUrl,
02517                             mMainWindow );
02518   command->start();
02519 }
02520 
02521 //-----------------------------------------------------------------------------
02522 void KMReaderWin::slotUrlCopy()
02523 {
02524   // we don't necessarily need a mainWidget for KMUrlCopyCommand so
02525   // it doesn't matter if the dynamic_cast fails.
02526   KMCommand *command =
02527     new KMUrlCopyCommand( mClickedUrl,
02528                           dynamic_cast<KMMainWidget*>( mMainWindow ) );
02529   command->start();
02530 }
02531 
02532 //-----------------------------------------------------------------------------
02533 void KMReaderWin::slotUrlOpen( const KURL &url )
02534 {
02535   if ( !url.isEmpty() )
02536     mClickedUrl = url;
02537   KMCommand *command = new KMUrlOpenCommand( mClickedUrl, this );
02538   command->start();
02539 }
02540 
02541 //-----------------------------------------------------------------------------
02542 void KMReaderWin::slotAddBookmarks()
02543 {
02544     KMCommand *command = new KMAddBookmarksCommand( mClickedUrl, this );
02545     command->start();
02546 }
02547 
02548 //-----------------------------------------------------------------------------
02549 void KMReaderWin::slotUrlSave()
02550 {
02551   KMCommand *command = new KMUrlSaveCommand( mClickedUrl, mMainWindow );
02552   command->start();
02553 }
02554 
02555 //-----------------------------------------------------------------------------
02556 void KMReaderWin::slotMailtoReply()
02557 {
02558   KMCommand *command = new KMMailtoReplyCommand( mMainWindow, mClickedUrl,
02559                                                  message(), copyText() );
02560   command->start();
02561 }
02562 
02563 //-----------------------------------------------------------------------------
02564 partNode * KMReaderWin::partNodeFromUrl( const KURL & url ) {
02565   return mRootNode ? mRootNode->findId( msgPartFromUrl( url ) ) : 0 ;
02566 }
02567 
02568 partNode * KMReaderWin::partNodeForId( int id ) {
02569   return mRootNode ? mRootNode->findId( id ) : 0 ;
02570 }
02571 
02572 
02573 KURL KMReaderWin::tempFileUrlFromPartNode( const partNode * node )
02574 {
02575   if (!node) return KURL();
02576   QStringList::const_iterator it = mTempFiles.begin();
02577   QStringList::const_iterator end = mTempFiles.end();
02578 
02579   while ( it != end ) {
02580       QString path = *it;
02581       it++;
02582       uint right = path.findRev('/');
02583       uint left = path.findRev('.', right);
02584 
02585       bool ok;
02586       int res = path.mid(left + 1, right - left - 1).toInt(&ok);
02587       if ( res == node->nodeId() )
02588           return KURL( path );
02589   }
02590   return KURL();
02591 }
02592 
02593 //-----------------------------------------------------------------------------
02594 void KMReaderWin::slotSaveAttachments()
02595 {
02596   mAtmUpdate = true;
02597   KMSaveAttachmentsCommand *saveCommand = new KMSaveAttachmentsCommand( mMainWindow,
02598                                                                         message() );
02599   saveCommand->start();
02600 }
02601 
02602 //-----------------------------------------------------------------------------
02603 void KMReaderWin::saveAttachment( const KURL &tempFileName )
02604 {
02605   mAtmCurrent = msgPartFromUrl( tempFileName );
02606   mAtmCurrentName = mClickedUrl.path();
02607   slotHandleAttachment( KMHandleAttachmentCommand::Save ); // save
02608 }
02609 
02610 //-----------------------------------------------------------------------------
02611 void KMReaderWin::slotSaveMsg()
02612 {
02613   KMSaveMsgCommand *saveCommand = new KMSaveMsgCommand( mMainWindow, message() );
02614 
02615   if (saveCommand->url().isEmpty())
02616     delete saveCommand;
02617   else
02618     saveCommand->start();
02619 }
02620 //-----------------------------------------------------------------------------
02621 void KMReaderWin::slotIMChat()
02622 {
02623   KMCommand *command = new KMIMChatCommand( mClickedUrl, message() );
02624   command->start();
02625 }
02626 
02627 //-----------------------------------------------------------------------------
02628 bool KMReaderWin::eventFilter( QObject *, QEvent *e )
02629 {
02630   if ( e->type() == QEvent::MouseButtonPress ) {
02631     QMouseEvent* me = static_cast<QMouseEvent*>(e);
02632     if ( me->button() == LeftButton && ( me->state() & ShiftButton ) ) {
02633       // special processing for shift+click
02634       URLHandlerManager::instance()->handleShiftClick( mHoveredUrl, this );
02635       return true;
02636     }
02637 
02638     if ( me->button() == LeftButton ) {
02639 
02640       QString imagePath;
02641       const DOM::Node nodeUnderMouse = mViewer->nodeUnderMouse();
02642       if ( !nodeUnderMouse.isNull() ) {
02643         const DOM::NamedNodeMap attributes = nodeUnderMouse.attributes();
02644         if ( !attributes.isNull() ) {
02645           const DOM::Node src = attributes.getNamedItem( DOM::DOMString( "src" ) );
02646           if ( !src.isNull() ) {
02647             imagePath = src.nodeValue().string();
02648           }
02649         }
02650       }
02651 
02652       mCanStartDrag = URLHandlerManager::instance()->willHandleDrag( mHoveredUrl, imagePath, this );
02653       mLastClickPosition = me->pos();
02654       mLastClickImagePath = imagePath;
02655     }
02656   }
02657 
02658   if ( e->type() ==  QEvent::MouseButtonRelease ) {
02659     mCanStartDrag = false;
02660   }
02661 
02662   if ( e->type() == QEvent::MouseMove ) {
02663     QMouseEvent* me = static_cast<QMouseEvent*>( e );
02664 
02665     if ( ( mLastClickPosition - me->pos() ).manhattanLength() > KGlobalSettings::dndEventDelay() ) {
02666       if ( mCanStartDrag && ( !( mHoveredUrl.isEmpty() && mLastClickImagePath.isEmpty() ) ) ) {
02667         if ( URLHandlerManager::instance()->handleDrag( mHoveredUrl, mLastClickImagePath, this ) ) {
02668           mCanStartDrag = false;
02669           slotUrlOn( QString() );
02670           return true;
02671         }
02672       }
02673     }
02674   }
02675 
02676   // standard event processing
02677   return false;
02678 }
02679 
02680 void KMReaderWin::fillCommandInfo( partNode *node, KMMessage **msg, int *nodeId )
02681 {
02682   Q_ASSERT( msg && nodeId );
02683 
02684   if ( mSerNumOfOriginalMessage != 0 ) {
02685     KMFolder *folder = 0;
02686     int index = -1;
02687     KMMsgDict::instance()->getLocation( mSerNumOfOriginalMessage, &folder, &index );
02688     if ( folder && index != -1 )
02689       *msg = folder->getMsg( index );
02690 
02691     if ( !( *msg ) ) {
02692       kdWarning( 5006 ) << "Unable to find the original message, aborting attachment deletion!" << endl;
02693       return;
02694     }
02695 
02696     *nodeId = node->nodeId() + mNodeIdOffset;
02697   }
02698   else {
02699     *nodeId = node->nodeId();
02700     *msg = message();
02701   }
02702 }
02703 
02704 void KMReaderWin::slotDeleteAttachment(partNode * node)
02705 {
02706   if ( KMessageBox::warningContinueCancel( this,
02707        i18n("Deleting an attachment might invalidate any digital signature on this message."),
02708        i18n("Delete Attachment"), KStdGuiItem::del(), "DeleteAttachmentSignatureWarning" )
02709      != KMessageBox::Continue ) {
02710     return;
02711   }
02712 
02713   int nodeId = -1;
02714   KMMessage *msg = 0;
02715   fillCommandInfo( node, &msg, &nodeId );
02716   if ( msg && nodeId != -1 ) {
02717     KMDeleteAttachmentCommand* command = new KMDeleteAttachmentCommand( nodeId, msg, this );
02718     command->start();
02719     connect( command, SIGNAL( completed( KMCommand * ) ),
02720              this, SLOT( updateReaderWin() ) );
02721     connect( command, SIGNAL( completed( KMCommand * ) ),
02722              this, SLOT( disconnectMsgAdded() ) );
02723 
02724     // ### HACK: Since the command will do delete + add, a new message will arrive. However, we don't
02725     // want the selection to change. Therefore, as soon as a new message arrives, select it, and then
02726     // disconnect.
02727     // Of course the are races, another message can arrive before ours, but we take the risk.
02728     // And it won't work properly with multiple main windows
02729     const KMHeaders * const headers = KMKernel::self()->getKMMainWidget()->headers();
02730     connect( headers, SIGNAL( msgAddedToListView( QListViewItem* ) ),
02731              this, SLOT( msgAdded( QListViewItem* ) ) );
02732   }
02733 
02734   // If we are operating on a copy of parts of the message, make sure to update the copy as well.
02735   if ( mSerNumOfOriginalMessage != 0 && message() ) {
02736     message()->deleteBodyPart( node->nodeId() );
02737     update( true );
02738   }
02739 }
02740 
02741 void KMReaderWin::msgAdded( QListViewItem *item )
02742 {
02743   // A new message was added to the message list view. Select it.
02744   // This is only connected right after we started a attachment delete command, so we expect a new
02745   // message. Disconnect right afterwards, we only want this particular message to be selected.
02746   disconnectMsgAdded();
02747   KMHeaders * const headers = KMKernel::self()->getKMMainWidget()->headers();
02748   headers->setCurrentItem( item );
02749   headers->clearSelection();
02750   headers->setSelected( item, true );
02751 }
02752 
02753 void KMReaderWin::disconnectMsgAdded()
02754 {
02755   const KMHeaders *const headers = KMKernel::self()->getKMMainWidget()->headers();
02756   disconnect( headers, SIGNAL( msgAddedToListView( QListViewItem* ) ),
02757               this, SLOT( msgAdded( QListViewItem* ) ) );
02758 }
02759 
02760 void KMReaderWin::slotEditAttachment(partNode * node)
02761 {
02762   if ( KMessageBox::warningContinueCancel( this,
02763         i18n("Modifying an attachment might invalidate any digital signature on this message."),
02764         i18n("Edit Attachment"), KGuiItem( i18n("Edit"), "edit" ), "EditAttachmentSignatureWarning" )
02765         != KMessageBox::Continue ) {
02766     return;
02767   }
02768 
02769   int nodeId = -1;
02770   KMMessage *msg = 0;
02771   fillCommandInfo( node, &msg, &nodeId );
02772   if ( msg && nodeId != -1 ) {
02773     KMEditAttachmentCommand* command = new KMEditAttachmentCommand( nodeId, msg, this );
02774     command->start();
02775   }
02776 
02777   // FIXME: If we are operating on a copy of parts of the message, make sure to update the copy as well.
02778 }
02779 
02780 KMail::CSSHelper* KMReaderWin::cssHelper()
02781 {
02782   return mCSSHelper;
02783 }
02784 
02785 bool KMReaderWin::decryptMessage() const
02786 {
02787   if ( !GlobalSettings::self()->alwaysDecrypt() )
02788     return mDecrytMessageOverwrite;
02789   return true;
02790 }
02791 
02792 void KMReaderWin::scrollToAttachment( const partNode *node )
02793 {
02794   DOM::Document doc = mViewer->htmlDocument();
02795 
02796   // The anchors for this are created in ObjectTreeParser::parseObjectTree()
02797   mViewer->gotoAnchor( QString::fromLatin1( "att%1" ).arg( node->nodeId() ) );
02798 
02799   // Remove any old color markings which might be there
02800   const partNode *root = node->topLevelParent();
02801   for ( int i = 0; i <= root->totalChildCount() + 1; i++ ) {
02802     DOM::Element attachmentDiv = doc.getElementById( QString( "attachmentDiv%1" ).arg( i + 1 ) );
02803     if ( !attachmentDiv.isNull() )
02804       attachmentDiv.removeAttribute( "style" );
02805   }
02806 
02807   // Don't mark hidden nodes, that would just produce a strange yellow line
02808   if ( node->isDisplayedHidden() )
02809     return;
02810 
02811   // Now, color the div of the attachment in yellow, so that the user sees what happened.
02812   // We created a special marked div for this in writeAttachmentMarkHeader() in ObjectTreeParser,
02813   // find and modify that now.
02814   DOM::Element attachmentDiv = doc.getElementById( QString( "attachmentDiv%1" ).arg( node->nodeId() ) );
02815   if ( attachmentDiv.isNull() ) {
02816     kdWarning( 5006 ) << "Could not find attachment div for attachment " << node->nodeId() << endl;
02817     return;
02818   }
02819 
02820   attachmentDiv.setAttribute( "style", QString( "border:2px solid %1" )
02821       .arg( cssHelper()->pgpWarnColor().name() ) );
02822 
02823   // Update rendering, otherwise the rendering is not updated when the user clicks on an attachment
02824   // that causes scrolling and the open attachment dialog
02825   doc.updateRendering();
02826 }
02827 
02828 void KMReaderWin::injectAttachments()
02829 {
02830   // inject attachments in header view
02831   // we have to do that after the otp has run so we also see encrypted parts
02832   DOM::Document doc = mViewer->htmlDocument();
02833   DOM::Element injectionPoint = doc.getElementById( "attachmentInjectionPoint" );
02834   if ( injectionPoint.isNull() )
02835     return;
02836 
02837   QString imgpath( locate("data","kmail/pics/") );
02838   QString visibility;
02839   QString urlHandle;
02840   QString imgSrc;
02841   if( !showAttachmentQuicklist() ) {
02842     urlHandle.append( "kmail:showAttachmentQuicklist" );
02843     imgSrc.append( "attachmentQuicklistClosed.png" );
02844   } else {
02845     urlHandle.append( "kmail:hideAttachmentQuicklist" );
02846     imgSrc.append( "attachmentQuicklistOpened.png" );
02847   }
02848 
02849   QString html = renderAttachments( mRootNode, QApplication::palette().active().background() );
02850   if ( html.isEmpty() )
02851     return;
02852 
02853   QString link("");
02854   if ( headerStyle() == HeaderStyle::fancy() ) {
02855     link += "<div style=\"text-align: left;\"><a href=\"" + urlHandle + "\"><img src=\"" +
02856             imgpath + imgSrc + "\"/></a></div>";
02857     html.prepend( link );
02858     html.prepend( QString::fromLatin1( "<div style=\"float:left;\">%1&nbsp;</div>" ).
02859                   arg( i18n( "Attachments:" ) ) );
02860   } else {
02861     link += "<div style=\"text-align: right;\"><a href=\"" + urlHandle + "\"><img src=\"" +
02862             imgpath + imgSrc + "\"/></a></div>";
02863     html.prepend( link );
02864   }
02865 
02866   assert( injectionPoint.tagName() == "div" );
02867   static_cast<DOM::HTMLElement>( injectionPoint ).setInnerHTML( html );
02868 }
02869 
02870 static QColor nextColor( const QColor & c )
02871 {
02872   int h, s, v;
02873   c.hsv( &h, &s, &v );
02874   return QColor( (h + 50) % 360, QMAX(s, 64), v, QColor::Hsv );
02875 }
02876 
02877 QString KMReaderWin::renderAttachments(partNode * node, const QColor &bgColor )
02878 {
02879   if ( !node )
02880     return QString();
02881 
02882   QString html;
02883   if ( node->firstChild() ) {
02884     QString subHtml = renderAttachments( node->firstChild(), nextColor( bgColor ) );
02885     if ( !subHtml.isEmpty() ) {
02886 
02887       QString visibility;
02888       if ( !showAttachmentQuicklist() ) {
02889         visibility.append( "display:none;" );
02890       }
02891 
02892       QString margin;
02893       if ( node != mRootNode || headerStyle() != HeaderStyle::enterprise() )
02894         margin = "padding:2px; margin:2px; ";
02895       QString align = "left";
02896       if ( headerStyle() == HeaderStyle::enterprise() )
02897         align = "right";
02898       if ( node->msgPart().typeStr().lower() == "message" || node == mRootNode )
02899         html += QString::fromLatin1("<div style=\"background:%1; %2"
02900                 "vertical-align:middle; float:%3; %4\">").arg( bgColor.name() ).arg( margin )
02901                                                          .arg( align ).arg( visibility );
02902       html += subHtml;
02903       if ( node->msgPart().typeStr().lower() == "message" || node == mRootNode )
02904         html += "</div>";
02905     }
02906   } else {
02907     partNode::AttachmentDisplayInfo info = node->attachmentDisplayInfo();
02908     if ( info.displayInHeader ) {
02909       html += "<div style=\"float:left;\">";
02910       html += QString::fromLatin1( "<span style=\"white-space:nowrap; border-width: 0px; border-left-width: 5px; border-color: %1; 2px; border-left-style: solid;\">" ).arg( bgColor.name() );
02911       QString fileName = writeMessagePartToTempFile( &node->msgPart(), node->nodeId() );
02912       QString href = node->asHREF( "header" );
02913       html += QString::fromLatin1( "<a href=\"" ) + href +
02914               QString::fromLatin1( "\">" );
02915       html += "<img style=\"vertical-align:middle;\" src=\"" + info.icon + "\"/>&nbsp;";
02916       if ( headerStyle() == HeaderStyle::enterprise() ) {
02917         QFont bodyFont = mCSSHelper->bodyFont( isFixedFont() );
02918         QFontMetrics fm( bodyFont );
02919         html += KStringHandler::rPixelSqueeze( info.label, fm, 140 );
02920       } else if ( headerStyle() == HeaderStyle::fancy() ) {
02921         QFont bodyFont = mCSSHelper->bodyFont( isFixedFont() );
02922         QFontMetrics fm( bodyFont );
02923         html += KStringHandler::rPixelSqueeze( info.label, fm, 640 );
02924       } else {
02925         html += info.label;
02926       }
02927       html += "</a></span></div> ";
02928     }
02929   }
02930 
02931   html += renderAttachments( node->nextSibling(), nextColor ( bgColor ) );
02932   return html;
02933 }
02934 
02935 using namespace KMail::Interface;
02936 
02937 void KMReaderWin::setBodyPartMemento( const partNode * node, const QCString & which, BodyPartMemento * memento )
02938 {
02939   const QCString index = node->path() + ':' + which.lower();
02940 
02941   const std::map<QCString,BodyPartMemento*>::iterator it = mBodyPartMementoMap.lower_bound( index );
02942   if ( it != mBodyPartMementoMap.end() && it->first == index ) {
02943 
02944     if ( memento && memento == it->second )
02945       return;
02946 
02947     delete it->second;
02948 
02949     if ( memento ) {
02950       it->second = memento;
02951     }
02952     else {
02953       mBodyPartMementoMap.erase( it );
02954     }
02955 
02956   } else {
02957     if ( memento ) {
02958       mBodyPartMementoMap.insert( it, std::make_pair( index, memento ) );
02959     }
02960   }
02961 
02962   if ( Observable * o = memento ? memento->asObservable() : 0 )
02963     o->attach( this );
02964 }
02965 
02966 BodyPartMemento * KMReaderWin::bodyPartMemento( const partNode * node, const QCString & which ) const
02967 {
02968   const QCString index = node->path() + ':' + which.lower();
02969   const std::map<QCString,BodyPartMemento*>::const_iterator it = mBodyPartMementoMap.find( index );
02970   if ( it == mBodyPartMementoMap.end() ) {
02971     return 0;
02972   }
02973   else {
02974     return it->second;
02975   }
02976 }
02977 
02978 static void detach_and_delete( BodyPartMemento * memento, KMReaderWin * obs ) {
02979   if ( Observable * const o = memento ? memento->asObservable() : 0 )
02980     o->detach( obs );
02981   delete memento;
02982 }
02983 
02984 void KMReaderWin::clearBodyPartMementos()
02985 {
02986   for ( std::map<QCString,BodyPartMemento*>::const_iterator it = mBodyPartMementoMap.begin(), end = mBodyPartMementoMap.end() ; it != end ; ++it )
02987     // Detach the memento from the reader. When cancelling it, it might trigger an update of the
02988     // reader, which we are not interested in, and which is dangerous, since half the mementos are
02989     // already deleted.
02990     // https://issues.kolab.org/issue4187
02991     detach_and_delete( it->second, this );
02992 
02993   mBodyPartMementoMap.clear();
02994 }
02995 
02996 #include "kmreaderwin.moc"
02997 
02998 
KDE Home | KDE Accessibility Home | Description of Access Keys