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