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     return;
01900   }
01901 
01902   mHoveredUrl = url;
01903 
01904   const QString msg = URLHandlerManager::instance()->statusBarMessage( url, this );
01905 
01906   kdWarning( msg.isEmpty(), 5006 ) << "KMReaderWin::slotUrlOn(): Unhandled URL hover!" << endl;
01907   KPIM::BroadcastStatus::instance()->setTransientStatusMsg( msg );
01908 }
01909 
01910 
01911 //-----------------------------------------------------------------------------
01912 void KMReaderWin::slotUrlOpen(const KURL &aUrl, const KParts::URLArgs &)
01913 {
01914   mClickedUrl = aUrl;
01915 
01916   if ( URLHandlerManager::instance()->handleClick( aUrl, this ) )
01917     return;
01918 
01919   kdWarning( 5006 ) << "KMReaderWin::slotOpenUrl(): Unhandled URL click!" << endl;
01920   emit urlClicked( aUrl, Qt::LeftButton );
01921 }
01922 
01923 //-----------------------------------------------------------------------------
01924 void KMReaderWin::slotUrlPopup(const QString &aUrl, const QPoint& aPos)
01925 {
01926   const KURL url( aUrl );
01927   mClickedUrl = url;
01928 
01929   if ( url.protocol() == "mailto" ) {
01930     mCopyURLAction->setText( i18n( "Copy Email Address" ) );
01931   } else {
01932     mCopyURLAction->setText( i18n( "Copy Link Address" ) );
01933   }
01934 
01935   if ( URLHandlerManager::instance()->handleContextMenuRequest( url, aPos, this ) )
01936     return;
01937 
01938   if ( message() ) {
01939     kdWarning( 5006 ) << "KMReaderWin::slotUrlPopup(): Unhandled URL right-click!" << endl;
01940     emitPopupMenu( url, aPos );
01941   }
01942 }
01943 
01944 // Checks if the given node has a parent node that is a DIV which has an ID attribute
01945 // with the value specified here
01946 static bool hasParentDivWithId( const DOM::Node &start, const QString &id )
01947 {
01948   if ( start.isNull() )
01949     return false;
01950 
01951   if ( start.nodeName().string() == "div" ) {
01952     for ( unsigned int i = 0; i < start.attributes().length(); i++ ) {
01953       if ( start.attributes().item( i ).nodeName().string() == "id" &&
01954            start.attributes().item( i ).nodeValue().string() == id )
01955         return true;
01956     }
01957   }
01958 
01959   if ( !start.parentNode().isNull() )
01960     return hasParentDivWithId( start.parentNode(), id );
01961   else return false;
01962 }
01963 
01964 //-----------------------------------------------------------------------------
01965 void KMReaderWin::showAttachmentPopup( int id, const QString & name, const QPoint & p )
01966 {
01967   mAtmCurrent = id;
01968   mAtmCurrentName = name;
01969   KPopupMenu *menu = new KPopupMenu();
01970   menu->insertItem(SmallIcon("fileopen"),i18n("to open", "Open"), 1);
01971   menu->insertItem(i18n("Open With..."), 2);
01972   menu->insertItem(i18n("to view something", "View"), 3);
01973   menu->insertItem(SmallIcon("filesaveas"),i18n("Save As..."), 4);
01974   menu->insertItem(SmallIcon("editcopy"), i18n("Copy"), 9 );
01975   const bool canChange = message()->parent() ? !message()->parent()->isReadOnly() : false;
01976   if ( GlobalSettings::self()->allowAttachmentEditing() && canChange )
01977     menu->insertItem(SmallIcon("edit"), i18n("Edit Attachment"), 8 );
01978   if ( GlobalSettings::self()->allowAttachmentDeletion() && canChange )
01979     menu->insertItem(SmallIcon("editdelete"), i18n("Delete Attachment"), 7 );
01980   if ( name.endsWith( ".xia", false ) &&
01981        Kleo::CryptoBackendFactory::instance()->protocol( "Chiasmus" ) )
01982     menu->insertItem( i18n( "Decrypt With Chiasmus..." ), 6 );
01983   menu->insertItem(i18n("Properties"), 5);
01984 
01985   const bool attachmentInHeader = hasParentDivWithId( mViewer->nodeUnderMouse(), "attachmentInjectionPoint" );
01986   const bool hasScrollbar = mViewer->view()->verticalScrollBar()->isVisible();
01987   if ( attachmentInHeader && hasScrollbar ) {
01988     menu->insertItem( i18n("Scroll To"), 10 );
01989   }
01990 
01991   connect(menu, SIGNAL(activated(int)), this, SLOT(slotHandleAttachment(int)));
01992   menu->exec( p ,0 );
01993   delete menu;
01994 }
01995 
01996 //-----------------------------------------------------------------------------
01997 void KMReaderWin::setStyleDependantFrameWidth()
01998 {
01999   if ( !mBox )
02000     return;
02001   // set the width of the frame to a reasonable value for the current GUI style
02002   int frameWidth;
02003   if( style().isA("KeramikStyle") )
02004     frameWidth = style().pixelMetric( QStyle::PM_DefaultFrameWidth ) - 1;
02005   else
02006     frameWidth = style().pixelMetric( QStyle::PM_DefaultFrameWidth );
02007   if ( frameWidth < 0 )
02008     frameWidth = 0;
02009   if ( frameWidth != mBox->lineWidth() )
02010     mBox->setLineWidth( frameWidth );
02011 }
02012 
02013 //-----------------------------------------------------------------------------
02014 void KMReaderWin::styleChange( QStyle& oldStyle )
02015 {
02016   setStyleDependantFrameWidth();
02017   QWidget::styleChange( oldStyle );
02018 }
02019 
02020 //-----------------------------------------------------------------------------
02021 void KMReaderWin::slotHandleAttachment( int choice )
02022 {
02023   mAtmUpdate = true;
02024   partNode* node = mRootNode ? mRootNode->findId( mAtmCurrent ) : 0;
02025   if ( mAtmCurrentName.isEmpty() && node )
02026     mAtmCurrentName = tempFileUrlFromPartNode( node ).path();
02027   if ( choice < 7 ) {
02028   KMHandleAttachmentCommand* command = new KMHandleAttachmentCommand(
02029       node, message(), mAtmCurrent, mAtmCurrentName,
02030       KMHandleAttachmentCommand::AttachmentAction( choice ), 0, this );
02031   connect( command, SIGNAL( showAttachment( int, const QString& ) ),
02032       this, SLOT( slotAtmView( int, const QString& ) ) );
02033   command->start();
02034   } else if ( choice == 7 ) {
02035     slotDeleteAttachment( node );
02036   } else if ( choice == 8 ) {
02037     slotEditAttachment( node );
02038   } else if ( choice == 9 ) {
02039     if ( !node ) return;
02040     KURL::List urls;
02041     KURL url = tempFileUrlFromPartNode( node );
02042     if (!url.isValid() ) return;
02043     urls.append( url );
02044     KURLDrag* drag = new KURLDrag( urls, this );
02045     QApplication::clipboard()->setData( drag, QClipboard::Clipboard );
02046   } else if ( choice == 10 ) { // Scroll To
02047     scrollToAttachment( node );
02048   }
02049 }
02050 
02051 //-----------------------------------------------------------------------------
02052 void KMReaderWin::slotFind()
02053 {
02054   mViewer->findText();
02055 }
02056 
02057 //-----------------------------------------------------------------------------
02058 void KMReaderWin::slotFindNext()
02059 {
02060   mViewer->findTextNext();
02061 }
02062 
02063 //-----------------------------------------------------------------------------
02064 void KMReaderWin::slotToggleFixedFont()
02065 {
02066   mUseFixedFont = !mUseFixedFont;
02067   saveRelativePosition();
02068   update(true);
02069 }
02070 
02071 
02072 //-----------------------------------------------------------------------------
02073 void KMReaderWin::slotCopySelectedText()
02074 {
02075   kapp->clipboard()->setText( mViewer->selectedText() );
02076 }
02077 
02078 
02079 //-----------------------------------------------------------------------------
02080 void KMReaderWin::atmViewMsg( KMMessagePart* aMsgPart, int nodeId )
02081 {
02082   assert(aMsgPart!=0);
02083   KMMessage* msg = new KMMessage;
02084   msg->fromString(aMsgPart->bodyDecoded());
02085   assert(msg != 0);
02086   msg->setMsgSerNum( 0 ); // because lookups will fail
02087   // some information that is needed for imap messages with LOD
02088   msg->setParent( message()->parent() );
02089   msg->setUID(message()->UID());
02090   msg->setReadyToShow(true);
02091   KMReaderMainWin *win = new KMReaderMainWin();
02092   win->showMsg( overrideEncoding(), msg, message()->getMsgSerNum(), nodeId );
02093   win->show();
02094 }
02095 
02096 
02097 void KMReaderWin::setMsgPart( partNode * node ) {
02098   htmlWriter()->reset();
02099   mColorBar->hide();
02100   htmlWriter()->begin( mCSSHelper->cssDefinitions( isFixedFont() ) );
02101   htmlWriter()->write( mCSSHelper->htmlHead( isFixedFont() ) );
02102   // end ###
02103   if ( node ) {
02104     ObjectTreeParser otp( this, 0, true );
02105     otp.parseObjectTree( node );
02106   }
02107   // ### this, too
02108   htmlWriter()->queue( "</body></html>" );
02109   htmlWriter()->flush();
02110 }
02111 
02112 //-----------------------------------------------------------------------------
02113 void KMReaderWin::setMsgPart( KMMessagePart* aMsgPart, bool aHTML,
02114                   const QString& aFileName, const QString& pname )
02115 {
02116   KCursorSaver busy(KBusyPtr::busy());
02117   if (kasciistricmp(aMsgPart->typeStr(), "message")==0) {
02118       // if called from compose win
02119       KMMessage* msg = new KMMessage;
02120       assert(aMsgPart!=0);
02121       msg->fromString(aMsgPart->bodyDecoded());
02122       mMainWindow->setCaption(msg->subject());
02123       setMsg(msg, true);
02124       setAutoDelete(true);
02125   } else if (kasciistricmp(aMsgPart->typeStr(), "text")==0) {
02126       if (kasciistricmp(aMsgPart->subtypeStr(), "x-vcard") == 0) {
02127         showVCard( aMsgPart );
02128     return;
02129       }
02130       htmlWriter()->begin( mCSSHelper->cssDefinitions( isFixedFont() ) );
02131       htmlWriter()->queue( mCSSHelper->htmlHead( isFixedFont() ) );
02132 
02133       if (aHTML && (kasciistricmp(aMsgPart->subtypeStr(), "html")==0)) { // HTML
02134         // ### this is broken. It doesn't stip off the HTML header and footer!
02135         htmlWriter()->queue( aMsgPart->bodyToUnicode( overrideCodec() ) );
02136         mColorBar->setHtmlMode();
02137       } else { // plain text
02138         const QCString str = aMsgPart->bodyDecoded();
02139         ObjectTreeParser otp( this );
02140         otp.writeBodyStr( str,
02141                           overrideCodec() ? overrideCodec() : aMsgPart->codec(),
02142                           message() ? message()->from() : QString::null );
02143       }
02144       htmlWriter()->queue("</body></html>");
02145       htmlWriter()->flush();
02146       mMainWindow->setCaption(i18n("View Attachment: %1").arg(pname));
02147   } else if (kasciistricmp(aMsgPart->typeStr(), "image")==0 ||
02148              (kasciistricmp(aMsgPart->typeStr(), "application")==0 &&
02149               kasciistricmp(aMsgPart->subtypeStr(), "postscript")==0))
02150   {
02151       if (aFileName.isEmpty()) return;  // prevent crash
02152       // Open the window with a size so the image fits in (if possible):
02153       QImageIO *iio = new QImageIO();
02154       iio->setFileName(aFileName);
02155       if( iio->read() ) {
02156           QImage img = iio->image();
02157           QRect desk = KGlobalSettings::desktopGeometry(mMainWindow);
02158           // determine a reasonable window size
02159           int width, height;
02160           if( img.width() < 50 )
02161               width = 70;
02162           else if( img.width()+20 < desk.width() )
02163               width = img.width()+20;
02164           else
02165               width = desk.width();
02166           if( img.height() < 50 )
02167               height = 70;
02168           else if( img.height()+20 < desk.height() )
02169               height = img.height()+20;
02170           else
02171               height = desk.height();
02172           mMainWindow->resize( width, height );
02173       }
02174       // Just write the img tag to HTML:
02175       htmlWriter()->begin( mCSSHelper->cssDefinitions( isFixedFont() ) );
02176       htmlWriter()->write( mCSSHelper->htmlHead( isFixedFont() ) );
02177       htmlWriter()->write( "<img src=\"file:" +
02178                            KURL::encode_string( aFileName ) +
02179                            "\" border=\"0\">\n"
02180                            "</body></html>\n" );
02181       htmlWriter()->end();
02182       setCaption( i18n("View Attachment: %1").arg( pname ) );
02183       show();
02184       delete iio;
02185   } else {
02186     htmlWriter()->begin( mCSSHelper->cssDefinitions( isFixedFont() ) );
02187     htmlWriter()->queue( mCSSHelper->htmlHead( isFixedFont() ) );
02188     htmlWriter()->queue( "<pre>" );
02189 
02190     QString str = aMsgPart->bodyDecoded();
02191     // A QString cannot handle binary data. So if it's shorter than the
02192     // attachment, we assume the attachment is binary:
02193     if( str.length() < (unsigned) aMsgPart->decodedSize() ) {
02194       str.prepend( i18n("[KMail: Attachment contains binary data. Trying to show first character.]",
02195           "[KMail: Attachment contains binary data. Trying to show first %n characters.]",
02196           str.length()) + QChar('\n') );
02197     }
02198     htmlWriter()->queue( QStyleSheet::escape( str ) );
02199     htmlWriter()->queue( "</pre>" );
02200     htmlWriter()->queue("</body></html>");
02201     htmlWriter()->flush();
02202     mMainWindow->setCaption(i18n("View Attachment: %1").arg(pname));
02203   }
02204   // ---Sven's view text, html and image attachments in html widget end ---
02205 }
02206 
02207 
02208 //-----------------------------------------------------------------------------
02209 void KMReaderWin::slotAtmView( int id, const QString& name )
02210 {
02211   partNode* node = mRootNode ? mRootNode->findId( id ) : 0;
02212   if( node ) {
02213     mAtmCurrent = id;
02214     mAtmCurrentName = name;
02215     if ( mAtmCurrentName.isEmpty() )
02216       mAtmCurrentName = tempFileUrlFromPartNode( node ).path();
02217 
02218     KMMessagePart& msgPart = node->msgPart();
02219     QString pname = msgPart.fileName();
02220     if (pname.isEmpty()) pname=msgPart.name();
02221     if (pname.isEmpty()) pname=msgPart.contentDescription();
02222     if (pname.isEmpty()) pname="unnamed";
02223     // image Attachment is saved already
02224     if (kasciistricmp(msgPart.typeStr(), "message")==0) {
02225       atmViewMsg( &msgPart,id );
02226     } else if ((kasciistricmp(msgPart.typeStr(), "text")==0) &&
02227            (kasciistricmp(msgPart.subtypeStr(), "x-vcard")==0)) {
02228       setMsgPart( &msgPart, htmlMail(), name, pname );
02229     } else {
02230       KMReaderMainWin *win = new KMReaderMainWin(&msgPart, htmlMail(),
02231           name, pname, overrideEncoding() );
02232       win->show();
02233     }
02234   }
02235 }
02236 
02237 //-----------------------------------------------------------------------------
02238 void KMReaderWin::openAttachment( int id, const QString & name )
02239 {
02240   mAtmCurrentName = name;
02241   mAtmCurrent = id;
02242 
02243   QString str, pname, cmd, fileName;
02244 
02245   partNode* node = mRootNode ? mRootNode->findId( id ) : 0;
02246   if( !node ) {
02247     kdWarning(5006) << "KMReaderWin::openAttachment - could not find node " << id << endl;
02248     return;
02249   }
02250   if ( mAtmCurrentName.isEmpty() )
02251     mAtmCurrentName = tempFileUrlFromPartNode( node ).path();
02252 
02253   KMMessagePart& msgPart = node->msgPart();
02254   if (kasciistricmp(msgPart.typeStr(), "message")==0)
02255   {
02256     atmViewMsg( &msgPart, id );
02257     return;
02258   }
02259 
02260   QCString contentTypeStr( msgPart.typeStr() + '/' + msgPart.subtypeStr() );
02261   KPIM::kAsciiToLower( contentTypeStr.data() );
02262 
02263   if ( qstrcmp( contentTypeStr, "text/x-vcard" ) == 0 ) {
02264     showVCard( &msgPart );
02265     return;
02266   }
02267 
02268   // determine the MIME type of the attachment
02269   KMimeType::Ptr mimetype;
02270   // prefer the value of the Content-Type header
02271   mimetype = KMimeType::mimeType( QString::fromLatin1( contentTypeStr ) );
02272   if ( mimetype->name() == "application/octet-stream" ) {
02273     // consider the filename if Content-Type is application/octet-stream
02274     mimetype = KMimeType::findByPath( name, 0, true /* no disk access */ );
02275   }
02276   if ( ( mimetype->name() == "application/octet-stream" )
02277        && msgPart.isComplete() ) {
02278     // consider the attachment's contents if neither the Content-Type header
02279     // nor the filename give us a clue
02280     mimetype = KMimeType::findByFileContent( name );
02281   }
02282 
02283   KService::Ptr offer =
02284     KServiceTypeProfile::preferredService( mimetype->name(), "Application" );
02285 
02286   QString open_text;
02287   QString filenameText = msgPart.fileName();
02288   if ( filenameText.isEmpty() )
02289     filenameText = msgPart.name();
02290   if ( offer ) {
02291     open_text = i18n("&Open with '%1'").arg( offer->name() );
02292   } else {
02293     open_text = i18n("&Open With...");
02294   }
02295   const QString text = i18n("Open attachment '%1'?\n"
02296                             "Note that opening an attachment may compromise "
02297                             "your system's security.")
02298                        .arg( filenameText );
02299   const int choice = KMessageBox::questionYesNoCancel( this, text,
02300       i18n("Open Attachment?"), KStdGuiItem::saveAs(), open_text,
02301       QString::fromLatin1("askSave") + mimetype->name() ); // dontAskAgainName
02302 
02303   if( choice == KMessageBox::Yes ) {        // Save
02304     mAtmUpdate = true;
02305     KMHandleAttachmentCommand* command = new KMHandleAttachmentCommand( node,
02306         message(), mAtmCurrent, mAtmCurrentName, KMHandleAttachmentCommand::Save,
02307         offer, this );
02308     connect( command, SIGNAL( showAttachment( int, const QString& ) ),
02309         this, SLOT( slotAtmView( int, const QString& ) ) );
02310     command->start();
02311   }
02312   else if( choice == KMessageBox::No ) {    // Open
02313     KMHandleAttachmentCommand::AttachmentAction action = ( offer ?
02314         KMHandleAttachmentCommand::Open : KMHandleAttachmentCommand::OpenWith );
02315     mAtmUpdate = true;
02316     KMHandleAttachmentCommand* command = new KMHandleAttachmentCommand( node,
02317         message(), mAtmCurrent, mAtmCurrentName, action, offer, this );
02318     connect( command, SIGNAL( showAttachment( int, const QString& ) ),
02319         this, SLOT( slotAtmView( int, const QString& ) ) );
02320     command->start();
02321   } else {                  // Cancel
02322     kdDebug(5006) << "Canceled opening attachment" << endl;
02323   }
02324 }
02325 
02326 //-----------------------------------------------------------------------------
02327 void KMReaderWin::slotScrollUp()
02328 {
02329   static_cast<QScrollView *>(mViewer->widget())->scrollBy(0, -10);
02330 }
02331 
02332 
02333 //-----------------------------------------------------------------------------
02334 void KMReaderWin::slotScrollDown()
02335 {
02336   static_cast<QScrollView *>(mViewer->widget())->scrollBy(0, 10);
02337 }
02338 
02339 bool KMReaderWin::atBottom() const
02340 {
02341     const QScrollView *view = static_cast<const QScrollView *>(mViewer->widget());
02342     return view->contentsY() + view->visibleHeight() >= view->contentsHeight();
02343 }
02344 
02345 //-----------------------------------------------------------------------------
02346 void KMReaderWin::slotJumpDown()
02347 {
02348     QScrollView *view = static_cast<QScrollView *>(mViewer->widget());
02349     int offs = (view->clipper()->height() < 30) ? view->clipper()->height() : 30;
02350     view->scrollBy( 0, view->clipper()->height() - offs );
02351 }
02352 
02353 //-----------------------------------------------------------------------------
02354 void KMReaderWin::slotScrollPrior()
02355 {
02356   static_cast<QScrollView *>(mViewer->widget())->scrollBy(0, -(int)(height()*0.8));
02357 }
02358 
02359 
02360 //-----------------------------------------------------------------------------
02361 void KMReaderWin::slotScrollNext()
02362 {
02363   static_cast<QScrollView *>(mViewer->widget())->scrollBy(0, (int)(height()*0.8));
02364 }
02365 
02366 //-----------------------------------------------------------------------------
02367 void KMReaderWin::slotDocumentChanged()
02368 {
02369 
02370 }
02371 
02372 
02373 //-----------------------------------------------------------------------------
02374 void KMReaderWin::slotTextSelected(bool)
02375 {
02376   QString temp = mViewer->selectedText();
02377   kapp->clipboard()->setText(temp);
02378 }
02379 
02380 //-----------------------------------------------------------------------------
02381 void KMReaderWin::selectAll()
02382 {
02383   mViewer->selectAll();
02384 }
02385 
02386 //-----------------------------------------------------------------------------
02387 QString KMReaderWin::copyText()
02388 {
02389   QString temp = mViewer->selectedText();
02390   return temp;
02391 }
02392 
02393 
02394 //-----------------------------------------------------------------------------
02395 void KMReaderWin::slotDocumentDone()
02396 {
02397   // mSbVert->setValue(0);
02398 }
02399 
02400 
02401 //-----------------------------------------------------------------------------
02402 void KMReaderWin::setHtmlOverride(bool override)
02403 {
02404   mHtmlOverride = override;
02405   if (message())
02406       message()->setDecodeHTML(htmlMail());
02407 }
02408 
02409 
02410 //-----------------------------------------------------------------------------
02411 void KMReaderWin::setHtmlLoadExtOverride(bool override)
02412 {
02413   mHtmlLoadExtOverride = override;
02414   //if (message())
02415   //    message()->setDecodeHTML(htmlMail());
02416 }
02417 
02418 
02419 //-----------------------------------------------------------------------------
02420 bool KMReaderWin::htmlMail()
02421 {
02422   return ((mHtmlMail && !mHtmlOverride) || (!mHtmlMail && mHtmlOverride));
02423 }
02424 
02425 
02426 //-----------------------------------------------------------------------------
02427 bool KMReaderWin::htmlLoadExternal()
02428 {
02429   return ((mHtmlLoadExternal && !mHtmlLoadExtOverride) ||
02430           (!mHtmlLoadExternal && mHtmlLoadExtOverride));
02431 }
02432 
02433 
02434 //-----------------------------------------------------------------------------
02435 void KMReaderWin::saveRelativePosition()
02436 {
02437   const QScrollView * scrollview = static_cast<QScrollView *>( mViewer->widget() );
02438   mSavedRelativePosition =
02439     static_cast<float>( scrollview->contentsY() ) / scrollview->contentsHeight();
02440 }
02441 
02442 
02443 //-----------------------------------------------------------------------------
02444 void KMReaderWin::update( bool force )
02445 {
02446   KMMessage* msg = message();
02447   if ( msg )
02448     setMsg( msg, force, true /* updateOnly */ );
02449 }
02450 
02451 
02452 //-----------------------------------------------------------------------------
02453 KMMessage* KMReaderWin::message( KMFolder** aFolder ) const
02454 {
02455   KMFolder*  tmpFolder;
02456   KMFolder*& folder = aFolder ? *aFolder : tmpFolder;
02457   folder = 0;
02458   if (mMessage)
02459       return mMessage;
02460   if (mLastSerNum) {
02461     KMMessage *message = 0;
02462     int index;
02463     KMMsgDict::instance()->getLocation( mLastSerNum, &folder, &index );
02464     if (folder )
02465       message = folder->getMsg( index );
02466     if (!message)
02467       kdWarning(5006) << "Attempt to reference invalid serial number " << mLastSerNum << "\n" << endl;
02468     return message;
02469   }
02470   return 0;
02471 }
02472 
02473 
02474 
02475 //-----------------------------------------------------------------------------
02476 void KMReaderWin::slotUrlClicked()
02477 {
02478   KMMainWidget *mainWidget = dynamic_cast<KMMainWidget*>(mMainWindow);
02479   uint identity = 0;
02480   if ( message() && message()->parent() ) {
02481     identity = message()->parent()->identity();
02482   }
02483 
02484   KMCommand *command = new KMUrlClickedCommand( mClickedUrl, identity, this,
02485                         false, mainWidget );
02486   command->start();
02487 }
02488 
02489 //-----------------------------------------------------------------------------
02490 void KMReaderWin::slotMailtoCompose()
02491 {
02492   KMCommand *command = new KMMailtoComposeCommand( mClickedUrl, message() );
02493   command->start();
02494 }
02495 
02496 //-----------------------------------------------------------------------------
02497 void KMReaderWin::slotMailtoForward()
02498 {
02499   KMCommand *command = new KMMailtoForwardCommand( mMainWindow, mClickedUrl,
02500                            message() );
02501   command->start();
02502 }
02503 
02504 //-----------------------------------------------------------------------------
02505 void KMReaderWin::slotMailtoAddAddrBook()
02506 {
02507   KMCommand *command = new KMMailtoAddAddrBookCommand( mClickedUrl,
02508                                mMainWindow);
02509   command->start();
02510 }
02511 
02512 //-----------------------------------------------------------------------------
02513 void KMReaderWin::slotMailtoOpenAddrBook()
02514 {
02515   KMCommand *command = new KMMailtoOpenAddrBookCommand( mClickedUrl,
02516                             mMainWindow );
02517   command->start();
02518 }
02519 
02520 //-----------------------------------------------------------------------------
02521 void KMReaderWin::slotUrlCopy()
02522 {
02523   // we don't necessarily need a mainWidget for KMUrlCopyCommand so
02524   // it doesn't matter if the dynamic_cast fails.
02525   KMCommand *command =
02526     new KMUrlCopyCommand( mClickedUrl,
02527                           dynamic_cast<KMMainWidget*>( mMainWindow ) );
02528   command->start();
02529 }
02530 
02531 //-----------------------------------------------------------------------------
02532 void KMReaderWin::slotUrlOpen( const KURL &url )
02533 {
02534   if ( !url.isEmpty() )
02535     mClickedUrl = url;
02536   KMCommand *command = new KMUrlOpenCommand( mClickedUrl, this );
02537   command->start();
02538 }
02539 
02540 //-----------------------------------------------------------------------------
02541 void KMReaderWin::slotAddBookmarks()
02542 {
02543     KMCommand *command = new KMAddBookmarksCommand( mClickedUrl, this );
02544     command->start();
02545 }
02546 
02547 //-----------------------------------------------------------------------------
02548 void KMReaderWin::slotUrlSave()
02549 {
02550   KMCommand *command = new KMUrlSaveCommand( mClickedUrl, mMainWindow );
02551   command->start();
02552 }
02553 
02554 //-----------------------------------------------------------------------------
02555 void KMReaderWin::slotMailtoReply()
02556 {
02557   KMCommand *command = new KMMailtoReplyCommand( mMainWindow, mClickedUrl,
02558                                                  message(), copyText() );
02559   command->start();
02560 }
02561 
02562 //-----------------------------------------------------------------------------
02563 partNode * KMReaderWin::partNodeFromUrl( const KURL & url ) {
02564   return mRootNode ? mRootNode->findId( msgPartFromUrl( url ) ) : 0 ;
02565 }
02566 
02567 partNode * KMReaderWin::partNodeForId( int id ) {
02568   return mRootNode ? mRootNode->findId( id ) : 0 ;
02569 }
02570 
02571 
02572 KURL KMReaderWin::tempFileUrlFromPartNode( const partNode * node )
02573 {
02574   if (!node) return KURL();
02575   QStringList::const_iterator it = mTempFiles.begin();
02576   QStringList::const_iterator end = mTempFiles.end();
02577 
02578   while ( it != end ) {
02579       QString path = *it;
02580       it++;
02581       uint right = path.findRev('/');
02582       uint left = path.findRev('.', right);
02583 
02584       bool ok;
02585       int res = path.mid(left + 1, right - left - 1).toInt(&ok);
02586       if ( res == node->nodeId() )
02587           return KURL( path );
02588   }
02589   return KURL();
02590 }
02591 
02592 //-----------------------------------------------------------------------------
02593 void KMReaderWin::slotSaveAttachments()
02594 {
02595   mAtmUpdate = true;
02596   KMSaveAttachmentsCommand *saveCommand = new KMSaveAttachmentsCommand( mMainWindow,
02597                                                                         message() );
02598   saveCommand->start();
02599 }
02600 
02601 //-----------------------------------------------------------------------------
02602 void KMReaderWin::saveAttachment( const KURL &tempFileName )
02603 {
02604   mAtmCurrent = msgPartFromUrl( tempFileName );
02605   mAtmCurrentName = mClickedUrl.path();
02606   slotHandleAttachment( KMHandleAttachmentCommand::Save ); // save
02607 }
02608 
02609 //-----------------------------------------------------------------------------
02610 void KMReaderWin::slotSaveMsg()
02611 {
02612   KMSaveMsgCommand *saveCommand = new KMSaveMsgCommand( mMainWindow, message() );
02613 
02614   if (saveCommand->url().isEmpty())
02615     delete saveCommand;
02616   else
02617     saveCommand->start();
02618 }
02619 //-----------------------------------------------------------------------------
02620 void KMReaderWin::slotIMChat()
02621 {
02622   KMCommand *command = new KMIMChatCommand( mClickedUrl, message() );
02623   command->start();
02624 }
02625 
02626 //-----------------------------------------------------------------------------
02627 bool KMReaderWin::eventFilter( QObject *, QEvent *e )
02628 {
02629   if ( e->type() == QEvent::MouseButtonPress ) {
02630     QMouseEvent* me = static_cast<QMouseEvent*>(e);
02631     if ( me->button() == LeftButton && ( me->state() & ShiftButton ) ) {
02632       // special processing for shift+click
02633       URLHandlerManager::instance()->handleShiftClick( mHoveredUrl, this );
02634       return true;
02635     }
02636 
02637     if ( me->button() == LeftButton ) {
02638 
02639       // When the node under the mouse is an IMG node, set the hovered URL to the src of the
02640       // image, so that special URL handlers can deal with it, for example the InternalImageURLHandler
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             mHoveredUrl = src.nodeValue().string();
02648           }
02649         }
02650       }
02651 
02652       mCanStartDrag = URLHandlerManager::instance()->willHandleDrag( mHoveredUrl, this );
02653       mLastClickPosition = me->pos();
02654     }
02655   }
02656 
02657   if ( e->type() ==  QEvent::MouseButtonRelease ) {
02658     mCanStartDrag = false;
02659   }
02660 
02661   if ( e->type() == QEvent::MouseMove ) {
02662     QMouseEvent* me = static_cast<QMouseEvent*>( e );
02663 
02664     if ( ( mLastClickPosition - me->pos() ).manhattanLength() > KGlobalSettings::dndEventDelay() ) {
02665       if ( mCanStartDrag && !mHoveredUrl.isEmpty() ) {
02666         if ( URLHandlerManager::instance()->handleDrag( mHoveredUrl, this ) ) {
02667           mCanStartDrag = false;
02668           slotUrlOn( QString() );
02669           return true;
02670         }
02671       }
02672     }
02673   }
02674 
02675   // standard event processing
02676   return false;
02677 }
02678 
02679 void KMReaderWin::fillCommandInfo( partNode *node, KMMessage **msg, int *nodeId )
02680 {
02681   Q_ASSERT( msg && nodeId );
02682 
02683   if ( mSerNumOfOriginalMessage != 0 ) {
02684     KMFolder *folder = 0;
02685     int index = -1;
02686     KMMsgDict::instance()->getLocation( mSerNumOfOriginalMessage, &folder, &index );
02687     if ( folder && index != -1 )
02688       *msg = folder->getMsg( index );
02689 
02690     if ( !( *msg ) ) {
02691       kdWarning( 5006 ) << "Unable to find the original message, aborting attachment deletion!" << endl;
02692       return;
02693     }
02694 
02695     *nodeId = node->nodeId() + mNodeIdOffset;
02696   }
02697   else {
02698     *nodeId = node->nodeId();
02699     *msg = message();
02700   }
02701 }
02702 
02703 void KMReaderWin::slotDeleteAttachment(partNode * node)
02704 {
02705   if ( KMessageBox::warningContinueCancel( this,
02706        i18n("Deleting an attachment might invalidate any digital signature on this message."),
02707        i18n("Delete Attachment"), KStdGuiItem::del(), "DeleteAttachmentSignatureWarning" )
02708      != KMessageBox::Continue ) {
02709     return;
02710   }
02711 
02712   int nodeId = -1;
02713   KMMessage *msg = 0;
02714   fillCommandInfo( node, &msg, &nodeId );
02715   if ( msg && nodeId != -1 ) {
02716     KMDeleteAttachmentCommand* command = new KMDeleteAttachmentCommand( nodeId, msg, this );
02717     command->start();
02718     connect( command, SIGNAL( completed( KMCommand * ) ),
02719              this, SLOT( updateReaderWin() ) );
02720     connect( command, SIGNAL( completed( KMCommand * ) ),
02721              this, SLOT( disconnectMsgAdded() ) );
02722 
02723     // ### HACK: Since the command will do delete + add, a new message will arrive. However, we don't
02724     // want the selection to change. Therefore, as soon as a new message arrives, select it, and then
02725     // disconnect.
02726     // Of course the are races, another message can arrive before ours, but we take the risk.
02727     // And it won't work properly with multiple main windows
02728     const KMHeaders * const headers = KMKernel::self()->getKMMainWidget()->headers();
02729     connect( headers, SIGNAL( msgAddedToListView( QListViewItem* ) ),
02730              this, SLOT( msgAdded( QListViewItem* ) ) );
02731   }
02732 
02733   // If we are operating on a copy of parts of the message, make sure to update the copy as well.
02734   if ( mSerNumOfOriginalMessage != 0 && message() ) {
02735     message()->deleteBodyPart( node->nodeId() );
02736     update( true );
02737   }
02738 }
02739 
02740 void KMReaderWin::msgAdded( QListViewItem *item )
02741 {
02742   // A new message was added to the message list view. Select it.
02743   // This is only connected right after we started a attachment delete command, so we expect a new
02744   // message. Disconnect right afterwards, we only want this particular message to be selected.
02745   disconnectMsgAdded();
02746   KMHeaders * const headers = KMKernel::self()->getKMMainWidget()->headers();
02747   headers->setCurrentItem( item );
02748   headers->clearSelection();
02749   headers->setSelected( item, true );
02750 }
02751 
02752 void KMReaderWin::disconnectMsgAdded()
02753 {
02754   const KMHeaders *const headers = KMKernel::self()->getKMMainWidget()->headers();
02755   disconnect( headers, SIGNAL( msgAddedToListView( QListViewItem* ) ),
02756               this, SLOT( msgAdded( QListViewItem* ) ) );
02757 }
02758 
02759 void KMReaderWin::slotEditAttachment(partNode * node)
02760 {
02761   if ( KMessageBox::warningContinueCancel( this,
02762         i18n("Modifying an attachment might invalidate any digital signature on this message."),
02763         i18n("Edit Attachment"), KGuiItem( i18n("Edit"), "edit" ), "EditAttachmentSignatureWarning" )
02764         != KMessageBox::Continue ) {
02765     return;
02766   }
02767 
02768   int nodeId = -1;
02769   KMMessage *msg = 0;
02770   fillCommandInfo( node, &msg, &nodeId );
02771   if ( msg && nodeId != -1 ) {
02772     KMEditAttachmentCommand* command = new KMEditAttachmentCommand( nodeId, msg, this );
02773     command->start();
02774   }
02775 
02776   // FIXME: If we are operating on a copy of parts of the message, make sure to update the copy as well.
02777 }
02778 
02779 KMail::CSSHelper* KMReaderWin::cssHelper()
02780 {
02781   return mCSSHelper;
02782 }
02783 
02784 bool KMReaderWin::decryptMessage() const
02785 {
02786   if ( !GlobalSettings::self()->alwaysDecrypt() )
02787     return mDecrytMessageOverwrite;
02788   return true;
02789 }
02790 
02791 void KMReaderWin::scrollToAttachment( const partNode *node )
02792 {
02793   DOM::Document doc = mViewer->htmlDocument();
02794 
02795   // The anchors for this are created in ObjectTreeParser::parseObjectTree()
02796   mViewer->gotoAnchor( QString::fromLatin1( "att%1" ).arg( node->nodeId() ) );
02797 
02798   // Remove any old color markings which might be there
02799   const partNode *root = node->topLevelParent();
02800   for ( int i = 0; i <= root->totalChildCount() + 1; i++ ) {
02801     DOM::Element attachmentDiv = doc.getElementById( QString( "attachmentDiv%1" ).arg( i + 1 ) );
02802     if ( !attachmentDiv.isNull() )
02803       attachmentDiv.removeAttribute( "style" );
02804   }
02805 
02806   // Don't mark hidden nodes, that would just produce a strange yellow line
02807   if ( node->isDisplayedHidden() )
02808     return;
02809 
02810   // Now, color the div of the attachment in yellow, so that the user sees what happened.
02811   // We created a special marked div for this in writeAttachmentMarkHeader() in ObjectTreeParser,
02812   // find and modify that now.
02813   DOM::Element attachmentDiv = doc.getElementById( QString( "attachmentDiv%1" ).arg( node->nodeId() ) );
02814   if ( attachmentDiv.isNull() ) {
02815     kdWarning( 5006 ) << "Could not find attachment div for attachment " << node->nodeId() << endl;
02816     return;
02817   }
02818 
02819   attachmentDiv.setAttribute( "style", QString( "border:2px solid %1" )
02820       .arg( cssHelper()->pgpWarnColor().name() ) );
02821 
02822   // Update rendering, otherwise the rendering is not updated when the user clicks on an attachment
02823   // that causes scrolling and the open attachment dialog
02824   doc.updateRendering();
02825 }
02826 
02827 void KMReaderWin::injectAttachments()
02828 {
02829   // inject attachments in header view
02830   // we have to do that after the otp has run so we also see encrypted parts
02831   DOM::Document doc = mViewer->htmlDocument();
02832   DOM::Element injectionPoint = doc.getElementById( "attachmentInjectionPoint" );
02833   if ( injectionPoint.isNull() )
02834     return;
02835 
02836   QString imgpath( locate("data","kmail/pics/") );
02837   QString visibility;
02838   QString urlHandle;
02839   QString imgSrc;
02840   if( !showAttachmentQuicklist() )
02841     {
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=\""+imgpath+imgSrc+"\"/></a></div>";
02856       html.prepend( link );
02857       html.prepend( QString::fromLatin1("<div style=\"float:left;\">%1&nbsp;</div>" ).arg(i18n("Attachments:")) );
02858     } else {
02859       link += "<div style=\"text-align: right;\"><a href=\""+urlHandle+"\"><img src=\""+imgpath+imgSrc+"\"/></a></div>";
02860       html.prepend( link );
02861     }
02862 
02863     assert( injectionPoint.tagName() == "div" );
02864     static_cast<DOM::HTMLElement>( injectionPoint ).setInnerHTML( html );
02865 }
02866 
02867 static QColor nextColor( const QColor & c )
02868 {
02869   int h, s, v;
02870   c.hsv( &h, &s, &v );
02871   return QColor( (h + 50) % 360, QMAX(s, 64), v, QColor::Hsv );
02872 }
02873 
02874 QString KMReaderWin::renderAttachments(partNode * node, const QColor &bgColor )
02875 {
02876   if ( !node )
02877     return QString();
02878 
02879   QString html;
02880   if ( node->firstChild() ) {
02881     QString subHtml = renderAttachments( node->firstChild(), nextColor( bgColor ) );
02882     if ( !subHtml.isEmpty() ) {
02883 
02884       QString visibility;
02885       if ( !showAttachmentQuicklist() ) {
02886         visibility.append( "display:none;" );
02887       }
02888 
02889       QString margin;
02890       if ( node != mRootNode || headerStyle() != HeaderStyle::enterprise() )
02891         margin = "padding:2px; margin:2px; ";
02892       QString align = "left";
02893       if ( headerStyle() == HeaderStyle::enterprise() )
02894         align = "right";
02895       if ( node->msgPart().typeStr().lower() == "message" || node == mRootNode )
02896         html += QString::fromLatin1("<div style=\"background:%1; %2"
02897                 "vertical-align:middle; float:%3; %4\">").arg( bgColor.name() ).arg( margin )
02898                                                          .arg( align ).arg( visibility );
02899       html += subHtml;
02900       if ( node->msgPart().typeStr().lower() == "message" || node == mRootNode )
02901         html += "</div>";
02902     }
02903   } else {
02904     partNode::AttachmentDisplayInfo info = node->attachmentDisplayInfo();
02905     if ( info.displayInHeader ) {
02906       html += "<div style=\"float:left;\">";
02907       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() );
02908       QString fileName = writeMessagePartToTempFile( &node->msgPart(), node->nodeId() );
02909       QString href = node->asHREF( "header" );
02910       html += QString::fromLatin1( "<a href=\"" ) + href +
02911               QString::fromLatin1( "\">" );
02912       html += "<img style=\"vertical-align:middle;\" src=\"" + info.icon + "\"/>&nbsp;";
02913       if ( headerStyle() == HeaderStyle::enterprise() ) {
02914         QFont bodyFont = mCSSHelper->bodyFont( isFixedFont() );
02915         QFontMetrics fm( bodyFont );
02916         html += KStringHandler::rPixelSqueeze( info.label, fm, 140 );
02917       } else if ( headerStyle() == HeaderStyle::fancy() ) {
02918         QFont bodyFont = mCSSHelper->bodyFont( isFixedFont() );
02919         QFontMetrics fm( bodyFont );
02920         html += KStringHandler::rPixelSqueeze( info.label, fm, 1000 );
02921       } else {
02922         html += info.label;
02923       }
02924       html += "</a></span></div> ";
02925     }
02926   }
02927 
02928   html += renderAttachments( node->nextSibling(), nextColor ( bgColor ) );
02929   return html;
02930 }
02931 
02932 using namespace KMail::Interface;
02933 
02934 void KMReaderWin::setBodyPartMemento( const partNode * node, const QCString & which, BodyPartMemento * memento )
02935 {
02936   const QCString index = node->path() + ':' + which.lower();
02937 
02938   const std::map<QCString,BodyPartMemento*>::iterator it = mBodyPartMementoMap.lower_bound( index );
02939   if ( it != mBodyPartMementoMap.end() && it->first == index ) {
02940 
02941     if ( memento && memento == it->second )
02942       return;
02943 
02944     delete it->second;
02945 
02946     if ( memento ) {
02947       it->second = memento;
02948     }
02949     else {
02950       mBodyPartMementoMap.erase( it );
02951     }
02952 
02953   } else {
02954     if ( memento ) {
02955       mBodyPartMementoMap.insert( it, std::make_pair( index, memento ) );
02956     }
02957   }
02958 
02959   if ( Observable * o = memento ? memento->asObservable() : 0 )
02960     o->attach( this );
02961 }
02962 
02963 BodyPartMemento * KMReaderWin::bodyPartMemento( const partNode * node, const QCString & which ) const
02964 {
02965   const QCString index = node->path() + ':' + which.lower();
02966   const std::map<QCString,BodyPartMemento*>::const_iterator it = mBodyPartMementoMap.find( index );
02967   if ( it == mBodyPartMementoMap.end() ) {
02968     return 0;
02969   }
02970   else {
02971     return it->second;
02972   }
02973 }
02974 
02975 static void detach_and_delete( BodyPartMemento * memento, KMReaderWin * obs ) {
02976   if ( Observable * const o = memento ? memento->asObservable() : 0 )
02977     o->detach( obs );
02978   delete memento;
02979 }
02980 
02981 void KMReaderWin::clearBodyPartMementos()
02982 {
02983   for ( std::map<QCString,BodyPartMemento*>::const_iterator it = mBodyPartMementoMap.begin(), end = mBodyPartMementoMap.end() ; it != end ; ++it )
02984     // Detach the memento from the reader. When cancelling it, it might trigger an update of the
02985     // reader, which we are not interested in, and which is dangerous, since half the mementos are
02986     // already deleted.
02987     // https://issues.kolab.org/issue4187
02988     detach_and_delete( it->second, this );
02989 
02990   mBodyPartMementoMap.clear();
02991 }
02992 
02993 #include "kmreaderwin.moc"
02994 
02995 
KDE Home | KDE Accessibility Home | Description of Access Keys