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     const QString vcard = vCardNode->msgPart().bodyToUnicode( overrideCodec() );
01515     KABC::VCardConverter t;
01516     if ( !t.parseVCards( vcard ).empty() ) {
01517       hasVCard = true;
01518       writeMessagePartToTempFile( &vCardNode->msgPart(), vCardNode->nodeId() );
01519     }
01520   }
01521 
01522   if ( !mRootNode || !mRootNode->isToltecMessage() || mShowRawToltecMail ) {
01523     htmlWriter()->queue( writeMsgHeader(aMsg, hasVCard ? vCardNode : 0, true ) );
01524   }
01525 
01526   // show message content
01527   ObjectTreeParser otp( this );
01528   otp.setAllowAsync( true );
01529   otp.setShowRawToltecMail( mShowRawToltecMail );
01530   otp.parseObjectTree( mRootNode );
01531 
01532   // store encrypted/signed status information in the KMMessage
01533   //  - this can only be done *after* calling parseObjectTree()
01534   KMMsgEncryptionState encryptionState = mRootNode->overallEncryptionState();
01535   KMMsgSignatureState  signatureState  = mRootNode->overallSignatureState();
01536   // Don't crash when switching message while GPG passphrase entry dialog is shown #53185
01537   if (aMsg != message()) {
01538     displayMessage();
01539     return;
01540   }
01541   aMsg->setEncryptionState( encryptionState );
01542   // Don't reset the signature state to "not signed" (e.g. if one canceled the
01543   // decryption of a signed messages which has already been decrypted before).
01544   if ( signatureState != KMMsgNotSigned ||
01545        aMsg->signatureState() == KMMsgSignatureStateUnknown ) {
01546     aMsg->setSignatureState( signatureState );
01547   }
01548 
01549   bool emitReplaceMsgByUnencryptedVersion = false;
01550   const KConfigGroup reader( KMKernel::config(), "Reader" );
01551   if ( reader.readBoolEntry( "store-displayed-messages-unencrypted", false ) ) {
01552 
01553   // Hack to make sure the S/MIME CryptPlugs follows the strict requirement
01554   // of german government:
01555   // --> All received encrypted messages *must* be stored in unencrypted form
01556   //     after they have been decrypted once the user has read them.
01557   //     ( "Aufhebung der Verschluesselung nach dem Lesen" )
01558   //
01559   // note: Since there is no configuration option for this, we do that for
01560   //       all kinds of encryption now - *not* just for S/MIME.
01561   //       This could be changed in the objectTreeToDecryptedMsg() function
01562   //       by deciding when (or when not, resp.) to set the 'dataNode' to
01563   //       something different than 'curNode'.
01564 
01565 
01566 kdDebug(5006) << "\n\n\nKMReaderWin::parseMsg()  -  special post-encryption handling:\n1." << endl;
01567 kdDebug(5006) << "(aMsg == msg) = "                               << (aMsg == message()) << endl;
01568 kdDebug(5006) << "aMsg->parent() && aMsg->parent() != kmkernel->outboxFolder() = " << (aMsg->parent() && aMsg->parent() != kmkernel->outboxFolder()) << endl;
01569 kdDebug(5006) << "message_was_saved_decrypted_before( aMsg ) = " << message_was_saved_decrypted_before( aMsg ) << endl;
01570 kdDebug(5006) << "this->decryptMessage() = " << decryptMessage() << endl;
01571 kdDebug(5006) << "otp.hasPendingAsyncJobs() = " << otp.hasPendingAsyncJobs() << endl;
01572 kdDebug(5006) << "   (KMMsgFullyEncrypted == encryptionState) = "     << (KMMsgFullyEncrypted == encryptionState) << endl;
01573 kdDebug(5006) << "|| (KMMsgPartiallyEncrypted == encryptionState) = " << (KMMsgPartiallyEncrypted == encryptionState) << endl;
01574          // only proceed if we were called the normal way - not by
01575          // double click on the message (==not running in a separate window)
01576   if(    (aMsg == message())
01577          // don't remove encryption in the outbox folder :)
01578       && ( aMsg->parent() && aMsg->parent() != kmkernel->outboxFolder() )
01579          // only proceed if this message was not saved encryptedly before
01580       && !message_was_saved_decrypted_before( aMsg )
01581          // only proceed if the message has actually been decrypted
01582       && decryptMessage()
01583          // only proceed if no pending async jobs are running:
01584       && !otp.hasPendingAsyncJobs()
01585          // only proceed if this message is (at least partially) encrypted
01586       && (    (KMMsgFullyEncrypted == encryptionState)
01587            || (KMMsgPartiallyEncrypted == encryptionState) ) ) {
01588 
01589 kdDebug(5006) << "KMReaderWin  -  calling objectTreeToDecryptedMsg()" << endl;
01590 
01591     NewByteArray decryptedData;
01592     // note: The following call may change the message's headers.
01593     objectTreeToDecryptedMsg( mRootNode, decryptedData, *aMsg );
01594     // add a \0 to the data
01595     decryptedData.appendNULL();
01596     QCString resultString( decryptedData.data() );
01597 kdDebug(5006) << "KMReaderWin  -  resulting data:" << resultString << endl;
01598 
01599     if( !resultString.isEmpty() ) {
01600 kdDebug(5006) << "KMReaderWin  -  composing unencrypted message" << endl;
01601       // try this:
01602       aMsg->setBody( resultString );
01603       KMMessage* unencryptedMessage = new KMMessage( *aMsg );
01604       unencryptedMessage->setParent( 0 );
01605       // because this did not work:
01606       /*
01607       DwMessage dwMsg( aMsg->asDwString() );
01608       dwMsg.Body() = DwBody( DwString( resultString.data() ) );
01609       dwMsg.Body().Parse();
01610       KMMessage* unencryptedMessage = new KMMessage( &dwMsg );
01611       */
01612       //kdDebug(5006) << "KMReaderWin  -  resulting message:" << unencryptedMessage->asString() << endl;
01613       kdDebug(5006) << "KMReaderWin  -  attach unencrypted message to aMsg" << endl;
01614       aMsg->setUnencryptedMsg( unencryptedMessage );
01615       emitReplaceMsgByUnencryptedVersion = true;
01616     }
01617   }
01618   }
01619 
01620   // save current main Content-Type before deleting mRootNode
01621   const int rootNodeCntType = mRootNode ? mRootNode->type() : DwMime::kTypeText;
01622   const int rootNodeCntSubtype = mRootNode ? mRootNode->subType() : DwMime::kSubtypePlain;
01623 
01624   // store message id to avoid endless recursions
01625   setIdOfLastViewedMessage( aMsg->msgId() );
01626 
01627   if( emitReplaceMsgByUnencryptedVersion ) {
01628     kdDebug(5006) << "KMReaderWin  -  invoce saving in decrypted form:" << endl;
01629     emit replaceMsgByUnencryptedVersion();
01630   } else {
01631     kdDebug(5006) << "KMReaderWin  -  finished parsing and displaying of message." << endl;
01632     showHideMimeTree( rootNodeCntType == DwMime::kTypeText &&
01633               rootNodeCntSubtype == DwMime::kSubtypePlain );
01634   }
01635 
01636   aMsg->setIsBeingParsed( false );
01637 }
01638 
01639 
01640 //-----------------------------------------------------------------------------
01641 QString KMReaderWin::writeMsgHeader( KMMessage* aMsg, partNode *vCardNode, bool topLevel )
01642 {
01643   kdFatal( !headerStyle(), 5006 )
01644     << "trying to writeMsgHeader() without a header style set!" << endl;
01645   kdFatal( !headerStrategy(), 5006 )
01646     << "trying to writeMsgHeader() without a header strategy set!" << endl;
01647   QString href;
01648   if ( vCardNode )
01649     href = vCardNode->asHREF( "body" );
01650 
01651   return headerStyle()->format( aMsg, headerStrategy(), href, mPrinting, topLevel );
01652 }
01653 
01654 
01655 
01656 //-----------------------------------------------------------------------------
01657 QString KMReaderWin::writeMessagePartToTempFile( KMMessagePart* aMsgPart,
01658                                                  int aPartNum )
01659 {
01660   QString fileName = aMsgPart->fileName();
01661   if( fileName.isEmpty() )
01662     fileName = aMsgPart->name();
01663 
01664   //--- Sven's save attachments to /tmp start ---
01665   QString fname = createTempDir( QString::number( aPartNum ) );
01666   if ( fname.isEmpty() )
01667     return QString();
01668 
01669   // strip off a leading path
01670   int slashPos = fileName.findRev( '/' );
01671   if( -1 != slashPos )
01672     fileName = fileName.mid( slashPos + 1 );
01673   if( fileName.isEmpty() )
01674     fileName = "unnamed";
01675   fname += "/" + fileName;
01676 
01677   QByteArray data = aMsgPart->bodyDecodedBinary();
01678   size_t size = data.size();
01679   if ( aMsgPart->type() == DwMime::kTypeText && size) {
01680     // convert CRLF to LF before writing text attachments to disk
01681     size = KMail::Util::crlf2lf( data.data(), size );
01682   }
01683   if( !KPIM::kBytesToFile( data.data(), size, fname, false, false, false ) )
01684     return QString::null;
01685 
01686   mTempFiles.append( fname );
01687   // make file read-only so that nobody gets the impression that he might
01688   // edit attached files (cf. bug #52813)
01689   ::chmod( QFile::encodeName( fname ), S_IRUSR );
01690 
01691   return fname;
01692 }
01693 
01694 QString KMReaderWin::createTempDir( const QString &param )
01695 {
01696   KTempFile *tempFile = new KTempFile( QString::null, "." + param );
01697   tempFile->setAutoDelete( true );
01698   QString fname = tempFile->name();
01699   delete tempFile;
01700 
01701   if( ::access( QFile::encodeName( fname ), W_OK ) != 0 )
01702     // Not there or not writable
01703     if( ::mkdir( QFile::encodeName( fname ), 0 ) != 0
01704         || ::chmod( QFile::encodeName( fname ), S_IRWXU ) != 0 )
01705       return QString::null; //failed create
01706 
01707   assert( !fname.isNull() );
01708 
01709   mTempDirs.append( fname );
01710   return fname;
01711 }
01712 
01713 //-----------------------------------------------------------------------------
01714 void KMReaderWin::showVCard( KMMessagePart * msgPart ) {
01715   const QString vCard = msgPart->bodyToUnicode( overrideCodec() );
01716 
01717   VCardViewer *vcv = new VCardViewer(this, vCard, "vCardDialog");
01718   vcv->show();
01719 }
01720 
01721 //-----------------------------------------------------------------------------
01722 void KMReaderWin::printMsg()
01723 {
01724   if (!message()) return;
01725   mViewer->view()->print();
01726 }
01727 
01728 
01729 //-----------------------------------------------------------------------------
01730 int KMReaderWin::msgPartFromUrl(const KURL &aUrl)
01731 {
01732   if (aUrl.isEmpty()) return -1;
01733   if (!aUrl.isLocalFile()) return -1;
01734 
01735   QString path = aUrl.path();
01736   uint right = path.findRev('/');
01737   uint left = path.findRev('.', right);
01738 
01739   bool ok;
01740   int res = path.mid(left + 1, right - left - 1).toInt(&ok);
01741   return (ok) ? res : -1;
01742 }
01743 
01744 
01745 //-----------------------------------------------------------------------------
01746 void KMReaderWin::resizeEvent(QResizeEvent *)
01747 {
01748   if( !mResizeTimer.isActive() )
01749   {
01750     //
01751     // Combine all resize operations that are requested as long a
01752     // the timer runs.
01753     //
01754     mResizeTimer.start( 100, true );
01755   }
01756 }
01757 
01758 
01759 //-----------------------------------------------------------------------------
01760 void KMReaderWin::slotDelayedResize()
01761 {
01762   mSplitter->setGeometry(0, 0, width(), height());
01763 }
01764 
01765 
01766 //-----------------------------------------------------------------------------
01767 void KMReaderWin::slotTouchMessage()
01768 {
01769   if ( !message() )
01770     return;
01771 
01772   if ( !message()->isNew() && !message()->isUnread() )
01773     return;
01774 
01775   SerNumList serNums;
01776   serNums.append( message()->getMsgSerNum() );
01777   KMCommand *command = new KMSetStatusCommand( KMMsgStatusRead, serNums );
01778   command->start();
01779 
01780   // should we send an MDN?
01781   if ( mNoMDNsWhenEncrypted &&
01782        message()->encryptionState() != KMMsgNotEncrypted &&
01783        message()->encryptionState() != KMMsgEncryptionStateUnknown )
01784     return;
01785 
01786   KMFolder *folder = message()->parent();
01787   if (folder &&
01788      (folder->isOutbox() || folder->isSent() || folder->isTrash() ||
01789       folder->isDrafts() || folder->isTemplates() ) )
01790     return;
01791 
01792   if ( KMMessage * receipt = message()->createMDN( MDN::ManualAction,
01793                            MDN::Displayed,
01794                            true /* allow GUI */ ) )
01795     if ( !kmkernel->msgSender()->send( receipt ) ) // send or queue
01796       KMessageBox::error( this, i18n("Could not send MDN.") );
01797 }
01798 
01799 
01800 //-----------------------------------------------------------------------------
01801 void KMReaderWin::closeEvent(QCloseEvent *e)
01802 {
01803   QWidget::closeEvent(e);
01804   writeConfig();
01805 }
01806 
01807 
01808 bool foundSMIMEData( const QString aUrl,
01809                      QString& displayName,
01810                      QString& libName,
01811                      QString& keyId )
01812 {
01813   static QString showCertMan("showCertificate#");
01814   displayName = "";
01815   libName = "";
01816   keyId = "";
01817   int i1 = aUrl.find( showCertMan );
01818   if( -1 < i1 ) {
01819     i1 += showCertMan.length();
01820     int i2 = aUrl.find(" ### ", i1);
01821     if( i1 < i2 )
01822     {
01823       displayName = aUrl.mid( i1, i2-i1 );
01824       i1 = i2+5;
01825       i2 = aUrl.find(" ### ", i1);
01826       if( i1 < i2 )
01827       {
01828         libName = aUrl.mid( i1, i2-i1 );
01829         i2 += 5;
01830 
01831         keyId = aUrl.mid( i2 );
01832         /*
01833         int len = aUrl.length();
01834         if( len > i2+1 ) {
01835           keyId = aUrl.mid( i2, 2 );
01836           i2 += 2;
01837           while( len > i2+1 ) {
01838             keyId += ':';
01839             keyId += aUrl.mid( i2, 2 );
01840             i2 += 2;
01841           }
01842         }
01843         */
01844       }
01845     }
01846   }
01847   return !keyId.isEmpty();
01848 }
01849 
01850 
01851 //-----------------------------------------------------------------------------
01852 void KMReaderWin::slotUrlOn(const QString &aUrl)
01853 {
01854   const KURL url(aUrl);
01855 
01856   if ( url.protocol() == "kmail" || url.protocol() == "x-kmail" || url.protocol() == "attachment"
01857        || (url.protocol().isEmpty() && url.path().isEmpty()) ) {
01858     mViewer->setDNDEnabled( false );
01859   } else {
01860     mViewer->setDNDEnabled( true );
01861   }
01862 
01863   if ( aUrl.stripWhiteSpace().isEmpty() ) {
01864     KPIM::BroadcastStatus::instance()->reset();
01865     mHoveredUrl = KURL();
01866     return;
01867   }
01868 
01869   mHoveredUrl = url;
01870 
01871   const QString msg = URLHandlerManager::instance()->statusBarMessage( url, this );
01872 
01873   kdWarning( msg.isEmpty(), 5006 ) << "KMReaderWin::slotUrlOn(): Unhandled URL hover!" << endl;
01874   KPIM::BroadcastStatus::instance()->setTransientStatusMsg( msg );
01875 }
01876 
01877 
01878 //-----------------------------------------------------------------------------
01879 void KMReaderWin::slotUrlOpen(const KURL &aUrl, const KParts::URLArgs &)
01880 {
01881   mClickedUrl = aUrl;
01882 
01883   if ( URLHandlerManager::instance()->handleClick( aUrl, this ) )
01884     return;
01885 
01886   kdWarning( 5006 ) << "KMReaderWin::slotOpenUrl(): Unhandled URL click!" << endl;
01887   emit urlClicked( aUrl, Qt::LeftButton );
01888 }
01889 
01890 //-----------------------------------------------------------------------------
01891 void KMReaderWin::slotUrlPopup(const QString &aUrl, const QPoint& aPos)
01892 {
01893   const KURL url( aUrl );
01894   mClickedUrl = url;
01895 
01896   if ( url.protocol() == "mailto" ) {
01897     mCopyURLAction->setText( i18n( "Copy Email Address" ) );
01898   } else {
01899     mCopyURLAction->setText( i18n( "Copy Link Address" ) );
01900   }
01901 
01902   if ( URLHandlerManager::instance()->handleContextMenuRequest( url, aPos, this ) )
01903     return;
01904 
01905   if ( message() ) {
01906     kdWarning( 5006 ) << "KMReaderWin::slotUrlPopup(): Unhandled URL right-click!" << endl;
01907     emitPopupMenu( url, aPos );
01908   }
01909 }
01910 
01911 // Checks if the given node has a parent node that is a DIV which has an ID attribute
01912 // with the value specified here
01913 static bool hasParentDivWithId( const DOM::Node &start, const QString &id )
01914 {
01915   if ( start.isNull() )
01916     return false;
01917 
01918   if ( start.nodeName().string() == "div" ) {
01919     for ( unsigned int i = 0; i < start.attributes().length(); i++ ) {
01920       if ( start.attributes().item( i ).nodeName().string() == "id" &&
01921            start.attributes().item( i ).nodeValue().string() == id )
01922         return true;
01923     }
01924   }
01925 
01926   if ( !start.parentNode().isNull() )
01927     return hasParentDivWithId( start.parentNode(), id );
01928   else return false;
01929 }
01930 
01931 //-----------------------------------------------------------------------------
01932 void KMReaderWin::showAttachmentPopup( int id, const QString & name, const QPoint & p )
01933 {
01934   mAtmCurrent = id;
01935   mAtmCurrentName = name;
01936   KPopupMenu *menu = new KPopupMenu();
01937   menu->insertItem(SmallIcon("fileopen"),i18n("to open", "Open"), 1);
01938   menu->insertItem(i18n("Open With..."), 2);
01939   menu->insertItem(i18n("to view something", "View"), 3);
01940   menu->insertItem(SmallIcon("filesaveas"),i18n("Save As..."), 4);
01941   menu->insertItem(SmallIcon("editcopy"), i18n("Copy"), 9 );
01942   const bool canChange = message()->parent() ? !message()->parent()->isReadOnly() : false;
01943   if ( GlobalSettings::self()->allowAttachmentEditing() && canChange )
01944     menu->insertItem(SmallIcon("edit"), i18n("Edit Attachment"), 8 );
01945   if ( GlobalSettings::self()->allowAttachmentDeletion() && canChange )
01946     menu->insertItem(SmallIcon("editdelete"), i18n("Delete Attachment"), 7 );
01947   if ( name.endsWith( ".xia", false ) &&
01948        Kleo::CryptoBackendFactory::instance()->protocol( "Chiasmus" ) )
01949     menu->insertItem( i18n( "Decrypt With Chiasmus..." ), 6 );
01950   menu->insertItem(i18n("Properties"), 5);
01951 
01952   const bool attachmentInHeader = hasParentDivWithId( mViewer->nodeUnderMouse(), "attachmentInjectionPoint" );
01953   const bool hasScrollbar = mViewer->view()->verticalScrollBar()->isVisible();
01954   if ( attachmentInHeader && hasScrollbar ) {
01955     menu->insertItem( i18n("Scroll To"), 10 );
01956   }
01957 
01958   connect(menu, SIGNAL(activated(int)), this, SLOT(slotHandleAttachment(int)));
01959   menu->exec( p ,0 );
01960   delete menu;
01961 }
01962 
01963 //-----------------------------------------------------------------------------
01964 void KMReaderWin::setStyleDependantFrameWidth()
01965 {
01966   if ( !mBox )
01967     return;
01968   // set the width of the frame to a reasonable value for the current GUI style
01969   int frameWidth;
01970   if( style().isA("KeramikStyle") )
01971     frameWidth = style().pixelMetric( QStyle::PM_DefaultFrameWidth ) - 1;
01972   else
01973     frameWidth = style().pixelMetric( QStyle::PM_DefaultFrameWidth );
01974   if ( frameWidth < 0 )
01975     frameWidth = 0;
01976   if ( frameWidth != mBox->lineWidth() )
01977     mBox->setLineWidth( frameWidth );
01978 }
01979 
01980 //-----------------------------------------------------------------------------
01981 void KMReaderWin::styleChange( QStyle& oldStyle )
01982 {
01983   setStyleDependantFrameWidth();
01984   QWidget::styleChange( oldStyle );
01985 }
01986 
01987 //-----------------------------------------------------------------------------
01988 void KMReaderWin::slotHandleAttachment( int choice )
01989 {
01990   mAtmUpdate = true;
01991   partNode* node = mRootNode ? mRootNode->findId( mAtmCurrent ) : 0;
01992   if ( mAtmCurrentName.isEmpty() && node )
01993     mAtmCurrentName = tempFileUrlFromPartNode( node ).path();
01994   if ( choice < 7 ) {
01995   KMHandleAttachmentCommand* command = new KMHandleAttachmentCommand(
01996       node, message(), mAtmCurrent, mAtmCurrentName,
01997       KMHandleAttachmentCommand::AttachmentAction( choice ), 0, this );
01998   connect( command, SIGNAL( showAttachment( int, const QString& ) ),
01999       this, SLOT( slotAtmView( int, const QString& ) ) );
02000   command->start();
02001   } else if ( choice == 7 ) {
02002     slotDeleteAttachment( node );
02003   } else if ( choice == 8 ) {
02004     slotEditAttachment( node );
02005   } else if ( choice == 9 ) {
02006     if ( !node ) return;
02007     KURL::List urls;
02008     KURL url = tempFileUrlFromPartNode( node );
02009     if (!url.isValid() ) return;
02010     urls.append( url );
02011     KURLDrag* drag = new KURLDrag( urls, this );
02012     QApplication::clipboard()->setData( drag, QClipboard::Clipboard );
02013   } else if ( choice == 10 ) { // Scroll To
02014     scrollToAttachment( node );
02015   }
02016 }
02017 
02018 //-----------------------------------------------------------------------------
02019 void KMReaderWin::slotFind()
02020 {
02021   mViewer->findText();
02022 }
02023 
02024 //-----------------------------------------------------------------------------
02025 void KMReaderWin::slotFindNext()
02026 {
02027   mViewer->findTextNext();
02028 }
02029 
02030 //-----------------------------------------------------------------------------
02031 void KMReaderWin::slotToggleFixedFont()
02032 {
02033   mUseFixedFont = !mUseFixedFont;
02034   saveRelativePosition();
02035   update(true);
02036 }
02037 
02038 
02039 //-----------------------------------------------------------------------------
02040 void KMReaderWin::slotCopySelectedText()
02041 {
02042   kapp->clipboard()->setText( mViewer->selectedText() );
02043 }
02044 
02045 
02046 //-----------------------------------------------------------------------------
02047 void KMReaderWin::atmViewMsg( KMMessagePart* aMsgPart, int nodeId )
02048 {
02049   assert(aMsgPart!=0);
02050   KMMessage* msg = new KMMessage;
02051   msg->fromString(aMsgPart->bodyDecoded());
02052   assert(msg != 0);
02053   msg->setMsgSerNum( 0 ); // because lookups will fail
02054   // some information that is needed for imap messages with LOD
02055   msg->setParent( message()->parent() );
02056   msg->setUID(message()->UID());
02057   msg->setReadyToShow(true);
02058   KMReaderMainWin *win = new KMReaderMainWin();
02059   win->showMsg( overrideEncoding(), msg, message()->getMsgSerNum(), nodeId );
02060   win->show();
02061 }
02062 
02063 
02064 void KMReaderWin::setMsgPart( partNode * node ) {
02065   htmlWriter()->reset();
02066   mColorBar->hide();
02067   htmlWriter()->begin( mCSSHelper->cssDefinitions( isFixedFont() ) );
02068   htmlWriter()->write( mCSSHelper->htmlHead( isFixedFont() ) );
02069   // end ###
02070   if ( node ) {
02071     ObjectTreeParser otp( this, 0, true );
02072     otp.parseObjectTree( node );
02073   }
02074   // ### this, too
02075   htmlWriter()->queue( "</body></html>" );
02076   htmlWriter()->flush();
02077 }
02078 
02079 //-----------------------------------------------------------------------------
02080 void KMReaderWin::setMsgPart( KMMessagePart* aMsgPart, bool aHTML,
02081                   const QString& aFileName, const QString& pname )
02082 {
02083   KCursorSaver busy(KBusyPtr::busy());
02084   if (kasciistricmp(aMsgPart->typeStr(), "message")==0) {
02085       // if called from compose win
02086       KMMessage* msg = new KMMessage;
02087       assert(aMsgPart!=0);
02088       msg->fromString(aMsgPart->bodyDecoded());
02089       mMainWindow->setCaption(msg->subject());
02090       setMsg(msg, true);
02091       setAutoDelete(true);
02092   } else if (kasciistricmp(aMsgPart->typeStr(), "text")==0) {
02093       if (kasciistricmp(aMsgPart->subtypeStr(), "x-vcard") == 0) {
02094         showVCard( aMsgPart );
02095     return;
02096       }
02097       htmlWriter()->begin( mCSSHelper->cssDefinitions( isFixedFont() ) );
02098       htmlWriter()->queue( mCSSHelper->htmlHead( isFixedFont() ) );
02099 
02100       if (aHTML && (kasciistricmp(aMsgPart->subtypeStr(), "html")==0)) { // HTML
02101         // ### this is broken. It doesn't stip off the HTML header and footer!
02102         htmlWriter()->queue( aMsgPart->bodyToUnicode( overrideCodec() ) );
02103         mColorBar->setHtmlMode();
02104       } else { // plain text
02105         const QCString str = aMsgPart->bodyDecoded();
02106         ObjectTreeParser otp( this );
02107         otp.writeBodyStr( str,
02108                           overrideCodec() ? overrideCodec() : aMsgPart->codec(),
02109                           message() ? message()->from() : QString::null );
02110       }
02111       htmlWriter()->queue("</body></html>");
02112       htmlWriter()->flush();
02113       mMainWindow->setCaption(i18n("View Attachment: %1").arg(pname));
02114   } else if (kasciistricmp(aMsgPart->typeStr(), "image")==0 ||
02115              (kasciistricmp(aMsgPart->typeStr(), "application")==0 &&
02116               kasciistricmp(aMsgPart->subtypeStr(), "postscript")==0))
02117   {
02118       if (aFileName.isEmpty()) return;  // prevent crash
02119       // Open the window with a size so the image fits in (if possible):
02120       QImageIO *iio = new QImageIO();
02121       iio->setFileName(aFileName);
02122       if( iio->read() ) {
02123           QImage img = iio->image();
02124           QRect desk = KGlobalSettings::desktopGeometry(mMainWindow);
02125           // determine a reasonable window size
02126           int width, height;
02127           if( img.width() < 50 )
02128               width = 70;
02129           else if( img.width()+20 < desk.width() )
02130               width = img.width()+20;
02131           else
02132               width = desk.width();
02133           if( img.height() < 50 )
02134               height = 70;
02135           else if( img.height()+20 < desk.height() )
02136               height = img.height()+20;
02137           else
02138               height = desk.height();
02139           mMainWindow->resize( width, height );
02140       }
02141       // Just write the img tag to HTML:
02142       htmlWriter()->begin( mCSSHelper->cssDefinitions( isFixedFont() ) );
02143       htmlWriter()->write( mCSSHelper->htmlHead( isFixedFont() ) );
02144       htmlWriter()->write( "<img src=\"file:" +
02145                            KURL::encode_string( aFileName ) +
02146                            "\" border=\"0\">\n"
02147                            "</body></html>\n" );
02148       htmlWriter()->end();
02149       setCaption( i18n("View Attachment: %1").arg( pname ) );
02150       show();
02151       delete iio;
02152   } else {
02153     htmlWriter()->begin( mCSSHelper->cssDefinitions( isFixedFont() ) );
02154     htmlWriter()->queue( mCSSHelper->htmlHead( isFixedFont() ) );
02155     htmlWriter()->queue( "<pre>" );
02156 
02157     QString str = aMsgPart->bodyDecoded();
02158     // A QString cannot handle binary data. So if it's shorter than the
02159     // attachment, we assume the attachment is binary:
02160     if( str.length() < (unsigned) aMsgPart->decodedSize() ) {
02161       str.prepend( i18n("[KMail: Attachment contains binary data. Trying to show first character.]",
02162           "[KMail: Attachment contains binary data. Trying to show first %n characters.]",
02163           str.length()) + QChar('\n') );
02164     }
02165     htmlWriter()->queue( QStyleSheet::escape( str ) );
02166     htmlWriter()->queue( "</pre>" );
02167     htmlWriter()->queue("</body></html>");
02168     htmlWriter()->flush();
02169     mMainWindow->setCaption(i18n("View Attachment: %1").arg(pname));
02170   }
02171   // ---Sven's view text, html and image attachments in html widget end ---
02172 }
02173 
02174 
02175 //-----------------------------------------------------------------------------
02176 void KMReaderWin::slotAtmView( int id, const QString& name )
02177 {
02178   partNode* node = mRootNode ? mRootNode->findId( id ) : 0;
02179   if( node ) {
02180     mAtmCurrent = id;
02181     mAtmCurrentName = name;
02182     if ( mAtmCurrentName.isEmpty() )
02183       mAtmCurrentName = tempFileUrlFromPartNode( node ).path();
02184 
02185     KMMessagePart& msgPart = node->msgPart();
02186     QString pname = msgPart.fileName();
02187     if (pname.isEmpty()) pname=msgPart.name();
02188     if (pname.isEmpty()) pname=msgPart.contentDescription();
02189     if (pname.isEmpty()) pname="unnamed";
02190     // image Attachment is saved already
02191     if (kasciistricmp(msgPart.typeStr(), "message")==0) {
02192       atmViewMsg( &msgPart,id );
02193     } else if ((kasciistricmp(msgPart.typeStr(), "text")==0) &&
02194            (kasciistricmp(msgPart.subtypeStr(), "x-vcard")==0)) {
02195       setMsgPart( &msgPart, htmlMail(), name, pname );
02196     } else {
02197       KMReaderMainWin *win = new KMReaderMainWin(&msgPart, htmlMail(),
02198           name, pname, overrideEncoding() );
02199       win->show();
02200     }
02201   }
02202 }
02203 
02204 //-----------------------------------------------------------------------------
02205 void KMReaderWin::openAttachment( int id, const QString & name )
02206 {
02207   mAtmCurrentName = name;
02208   mAtmCurrent = id;
02209 
02210   QString str, pname, cmd, fileName;
02211 
02212   partNode* node = mRootNode ? mRootNode->findId( id ) : 0;
02213   if( !node ) {
02214     kdWarning(5006) << "KMReaderWin::openAttachment - could not find node " << id << endl;
02215     return;
02216   }
02217   if ( mAtmCurrentName.isEmpty() )
02218     mAtmCurrentName = tempFileUrlFromPartNode( node ).path();
02219 
02220   KMMessagePart& msgPart = node->msgPart();
02221   if (kasciistricmp(msgPart.typeStr(), "message")==0)
02222   {
02223     atmViewMsg( &msgPart, id );
02224     return;
02225   }
02226 
02227   QCString contentTypeStr( msgPart.typeStr() + '/' + msgPart.subtypeStr() );
02228   KPIM::kAsciiToLower( contentTypeStr.data() );
02229 
02230   if ( qstrcmp( contentTypeStr, "text/x-vcard" ) == 0 ) {
02231     showVCard( &msgPart );
02232     return;
02233   }
02234 
02235   // determine the MIME type of the attachment
02236   KMimeType::Ptr mimetype;
02237   // prefer the value of the Content-Type header
02238   mimetype = KMimeType::mimeType( QString::fromLatin1( contentTypeStr ) );
02239   if ( mimetype->name() == "application/octet-stream" ) {
02240     // consider the filename if Content-Type is application/octet-stream
02241     mimetype = KMimeType::findByPath( name, 0, true /* no disk access */ );
02242   }
02243   if ( ( mimetype->name() == "application/octet-stream" )
02244        && msgPart.isComplete() ) {
02245     // consider the attachment's contents if neither the Content-Type header
02246     // nor the filename give us a clue
02247     mimetype = KMimeType::findByFileContent( name );
02248   }
02249 
02250   KService::Ptr offer =
02251     KServiceTypeProfile::preferredService( mimetype->name(), "Application" );
02252 
02253   QString open_text;
02254   QString filenameText = msgPart.fileName();
02255   if ( filenameText.isEmpty() )
02256     filenameText = msgPart.name();
02257   if ( offer ) {
02258     open_text = i18n("&Open with '%1'").arg( offer->name() );
02259   } else {
02260     open_text = i18n("&Open With...");
02261   }
02262   const QString text = i18n("Open attachment '%1'?\n"
02263                             "Note that opening an attachment may compromise "
02264                             "your system's security.")
02265                        .arg( filenameText );
02266   const int choice = KMessageBox::questionYesNoCancel( this, text,
02267       i18n("Open Attachment?"), KStdGuiItem::saveAs(), open_text,
02268       QString::fromLatin1("askSave") + mimetype->name() ); // dontAskAgainName
02269 
02270   if( choice == KMessageBox::Yes ) {        // Save
02271     mAtmUpdate = true;
02272     KMHandleAttachmentCommand* command = new KMHandleAttachmentCommand( node,
02273         message(), mAtmCurrent, mAtmCurrentName, KMHandleAttachmentCommand::Save,
02274         offer, this );
02275     connect( command, SIGNAL( showAttachment( int, const QString& ) ),
02276         this, SLOT( slotAtmView( int, const QString& ) ) );
02277     command->start();
02278   }
02279   else if( choice == KMessageBox::No ) {    // Open
02280     KMHandleAttachmentCommand::AttachmentAction action = ( offer ?
02281         KMHandleAttachmentCommand::Open : KMHandleAttachmentCommand::OpenWith );
02282     mAtmUpdate = true;
02283     KMHandleAttachmentCommand* command = new KMHandleAttachmentCommand( node,
02284         message(), mAtmCurrent, mAtmCurrentName, action, offer, this );
02285     connect( command, SIGNAL( showAttachment( int, const QString& ) ),
02286         this, SLOT( slotAtmView( int, const QString& ) ) );
02287     command->start();
02288   } else {                  // Cancel
02289     kdDebug(5006) << "Canceled opening attachment" << endl;
02290   }
02291 }
02292 
02293 //-----------------------------------------------------------------------------
02294 void KMReaderWin::slotScrollUp()
02295 {
02296   static_cast<QScrollView *>(mViewer->widget())->scrollBy(0, -10);
02297 }
02298 
02299 
02300 //-----------------------------------------------------------------------------
02301 void KMReaderWin::slotScrollDown()
02302 {
02303   static_cast<QScrollView *>(mViewer->widget())->scrollBy(0, 10);
02304 }
02305 
02306 bool KMReaderWin::atBottom() const
02307 {
02308     const QScrollView *view = static_cast<const QScrollView *>(mViewer->widget());
02309     return view->contentsY() + view->visibleHeight() >= view->contentsHeight();
02310 }
02311 
02312 //-----------------------------------------------------------------------------
02313 void KMReaderWin::slotJumpDown()
02314 {
02315     QScrollView *view = static_cast<QScrollView *>(mViewer->widget());
02316     int offs = (view->clipper()->height() < 30) ? view->clipper()->height() : 30;
02317     view->scrollBy( 0, view->clipper()->height() - offs );
02318 }
02319 
02320 //-----------------------------------------------------------------------------
02321 void KMReaderWin::slotScrollPrior()
02322 {
02323   static_cast<QScrollView *>(mViewer->widget())->scrollBy(0, -(int)(height()*0.8));
02324 }
02325 
02326 
02327 //-----------------------------------------------------------------------------
02328 void KMReaderWin::slotScrollNext()
02329 {
02330   static_cast<QScrollView *>(mViewer->widget())->scrollBy(0, (int)(height()*0.8));
02331 }
02332 
02333 //-----------------------------------------------------------------------------
02334 void KMReaderWin::slotDocumentChanged()
02335 {
02336 
02337 }
02338 
02339 
02340 //-----------------------------------------------------------------------------
02341 void KMReaderWin::slotTextSelected(bool)
02342 {
02343   QString temp = mViewer->selectedText();
02344   kapp->clipboard()->setText(temp);
02345 }
02346 
02347 //-----------------------------------------------------------------------------
02348 void KMReaderWin::selectAll()
02349 {
02350   mViewer->selectAll();
02351 }
02352 
02353 //-----------------------------------------------------------------------------
02354 QString KMReaderWin::copyText()
02355 {
02356   QString temp = mViewer->selectedText();
02357   return temp;
02358 }
02359 
02360 
02361 //-----------------------------------------------------------------------------
02362 void KMReaderWin::slotDocumentDone()
02363 {
02364   // mSbVert->setValue(0);
02365 }
02366 
02367 
02368 //-----------------------------------------------------------------------------
02369 void KMReaderWin::setHtmlOverride(bool override)
02370 {
02371   mHtmlOverride = override;
02372   if (message())
02373       message()->setDecodeHTML(htmlMail());
02374 }
02375 
02376 
02377 //-----------------------------------------------------------------------------
02378 void KMReaderWin::setHtmlLoadExtOverride(bool override)
02379 {
02380   mHtmlLoadExtOverride = override;
02381   //if (message())
02382   //    message()->setDecodeHTML(htmlMail());
02383 }
02384 
02385 
02386 //-----------------------------------------------------------------------------
02387 bool KMReaderWin::htmlMail()
02388 {
02389   return ((mHtmlMail && !mHtmlOverride) || (!mHtmlMail && mHtmlOverride));
02390 }
02391 
02392 
02393 //-----------------------------------------------------------------------------
02394 bool KMReaderWin::htmlLoadExternal()
02395 {
02396   return ((mHtmlLoadExternal && !mHtmlLoadExtOverride) ||
02397           (!mHtmlLoadExternal && mHtmlLoadExtOverride));
02398 }
02399 
02400 
02401 //-----------------------------------------------------------------------------
02402 void KMReaderWin::saveRelativePosition()
02403 {
02404   const QScrollView * scrollview = static_cast<QScrollView *>( mViewer->widget() );
02405   mSavedRelativePosition =
02406     static_cast<float>( scrollview->contentsY() ) / scrollview->contentsHeight();
02407 }
02408 
02409 
02410 //-----------------------------------------------------------------------------
02411 void KMReaderWin::update( bool force )
02412 {
02413   KMMessage* msg = message();
02414   if ( msg )
02415     setMsg( msg, force, true /* updateOnly */ );
02416 }
02417 
02418 
02419 //-----------------------------------------------------------------------------
02420 KMMessage* KMReaderWin::message( KMFolder** aFolder ) const
02421 {
02422   KMFolder*  tmpFolder;
02423   KMFolder*& folder = aFolder ? *aFolder : tmpFolder;
02424   folder = 0;
02425   if (mMessage)
02426       return mMessage;
02427   if (mLastSerNum) {
02428     KMMessage *message = 0;
02429     int index;
02430     KMMsgDict::instance()->getLocation( mLastSerNum, &folder, &index );
02431     if (folder )
02432       message = folder->getMsg( index );
02433     if (!message)
02434       kdWarning(5006) << "Attempt to reference invalid serial number " << mLastSerNum << "\n" << endl;
02435     return message;
02436   }
02437   return 0;
02438 }
02439 
02440 
02441 
02442 //-----------------------------------------------------------------------------
02443 void KMReaderWin::slotUrlClicked()
02444 {
02445   KMMainWidget *mainWidget = dynamic_cast<KMMainWidget*>(mMainWindow);
02446   uint identity = 0;
02447   if ( message() && message()->parent() ) {
02448     identity = message()->parent()->identity();
02449   }
02450 
02451   KMCommand *command = new KMUrlClickedCommand( mClickedUrl, identity, this,
02452                         false, mainWidget );
02453   command->start();
02454 }
02455 
02456 //-----------------------------------------------------------------------------
02457 void KMReaderWin::slotMailtoCompose()
02458 {
02459   KMCommand *command = new KMMailtoComposeCommand( mClickedUrl, message() );
02460   command->start();
02461 }
02462 
02463 //-----------------------------------------------------------------------------
02464 void KMReaderWin::slotMailtoForward()
02465 {
02466   KMCommand *command = new KMMailtoForwardCommand( mMainWindow, mClickedUrl,
02467                            message() );
02468   command->start();
02469 }
02470 
02471 //-----------------------------------------------------------------------------
02472 void KMReaderWin::slotMailtoAddAddrBook()
02473 {
02474   KMCommand *command = new KMMailtoAddAddrBookCommand( mClickedUrl,
02475                                mMainWindow);
02476   command->start();
02477 }
02478 
02479 //-----------------------------------------------------------------------------
02480 void KMReaderWin::slotMailtoOpenAddrBook()
02481 {
02482   KMCommand *command = new KMMailtoOpenAddrBookCommand( mClickedUrl,
02483                             mMainWindow );
02484   command->start();
02485 }
02486 
02487 //-----------------------------------------------------------------------------
02488 void KMReaderWin::slotUrlCopy()
02489 {
02490   // we don't necessarily need a mainWidget for KMUrlCopyCommand so
02491   // it doesn't matter if the dynamic_cast fails.
02492   KMCommand *command =
02493     new KMUrlCopyCommand( mClickedUrl,
02494                           dynamic_cast<KMMainWidget*>( mMainWindow ) );
02495   command->start();
02496 }
02497 
02498 //-----------------------------------------------------------------------------
02499 void KMReaderWin::slotUrlOpen( const KURL &url )
02500 {
02501   if ( !url.isEmpty() )
02502     mClickedUrl = url;
02503   KMCommand *command = new KMUrlOpenCommand( mClickedUrl, this );
02504   command->start();
02505 }
02506 
02507 //-----------------------------------------------------------------------------
02508 void KMReaderWin::slotAddBookmarks()
02509 {
02510     KMCommand *command = new KMAddBookmarksCommand( mClickedUrl, this );
02511     command->start();
02512 }
02513 
02514 //-----------------------------------------------------------------------------
02515 void KMReaderWin::slotUrlSave()
02516 {
02517   KMCommand *command = new KMUrlSaveCommand( mClickedUrl, mMainWindow );
02518   command->start();
02519 }
02520 
02521 //-----------------------------------------------------------------------------
02522 void KMReaderWin::slotMailtoReply()
02523 {
02524   KMCommand *command = new KMMailtoReplyCommand( mMainWindow, mClickedUrl,
02525                                                  message(), copyText() );
02526   command->start();
02527 }
02528 
02529 //-----------------------------------------------------------------------------
02530 partNode * KMReaderWin::partNodeFromUrl( const KURL & url ) {
02531   return mRootNode ? mRootNode->findId( msgPartFromUrl( url ) ) : 0 ;
02532 }
02533 
02534 partNode * KMReaderWin::partNodeForId( int id ) {
02535   return mRootNode ? mRootNode->findId( id ) : 0 ;
02536 }
02537 
02538 
02539 KURL KMReaderWin::tempFileUrlFromPartNode( const partNode * node )
02540 {
02541   if (!node) return KURL();
02542   QStringList::const_iterator it = mTempFiles.begin();
02543   QStringList::const_iterator end = mTempFiles.end();
02544 
02545   while ( it != end ) {
02546       QString path = *it;
02547       it++;
02548       uint right = path.findRev('/');
02549       uint left = path.findRev('.', right);
02550 
02551       bool ok;
02552       int res = path.mid(left + 1, right - left - 1).toInt(&ok);
02553       if ( res == node->nodeId() )
02554           return KURL( path );
02555   }
02556   return KURL();
02557 }
02558 
02559 //-----------------------------------------------------------------------------
02560 void KMReaderWin::slotSaveAttachments()
02561 {
02562   mAtmUpdate = true;
02563   KMSaveAttachmentsCommand *saveCommand = new KMSaveAttachmentsCommand( mMainWindow,
02564                                                                         message() );
02565   saveCommand->start();
02566 }
02567 
02568 //-----------------------------------------------------------------------------
02569 void KMReaderWin::saveAttachment( const KURL &tempFileName )
02570 {
02571   mAtmCurrent = msgPartFromUrl( tempFileName );
02572   mAtmCurrentName = mClickedUrl.path();
02573   slotHandleAttachment( KMHandleAttachmentCommand::Save ); // save
02574 }
02575 
02576 //-----------------------------------------------------------------------------
02577 void KMReaderWin::slotSaveMsg()
02578 {
02579   KMSaveMsgCommand *saveCommand = new KMSaveMsgCommand( mMainWindow, message() );
02580 
02581   if (saveCommand->url().isEmpty())
02582     delete saveCommand;
02583   else
02584     saveCommand->start();
02585 }
02586 //-----------------------------------------------------------------------------
02587 void KMReaderWin::slotIMChat()
02588 {
02589   KMCommand *command = new KMIMChatCommand( mClickedUrl, message() );
02590   command->start();
02591 }
02592 
02593 //-----------------------------------------------------------------------------
02594 bool KMReaderWin::eventFilter( QObject *, QEvent *e )
02595 {
02596   if ( e->type() == QEvent::MouseButtonPress ) {
02597     QMouseEvent* me = static_cast<QMouseEvent*>(e);
02598     if ( me->button() == LeftButton && ( me->state() & ShiftButton ) ) {
02599       // special processing for shift+click
02600       URLHandlerManager::instance()->handleShiftClick( mHoveredUrl, this );
02601       return true;
02602     }
02603 
02604     if ( me->button() == LeftButton ) {
02605 
02606       // When the node under the mouse is an IMG node, set the hovered URL to the src of the
02607       // image, so that special URL handlers can deal with it, for example the InternalImageURLHandler
02608       const DOM::Node nodeUnderMouse = mViewer->nodeUnderMouse();
02609       if ( !nodeUnderMouse.isNull() ) {
02610         const DOM::NamedNodeMap attributes = nodeUnderMouse.attributes();
02611         if ( !attributes.isNull() ) {
02612           const DOM::Node src = attributes.getNamedItem( DOM::DOMString( "src" ) );
02613           if ( !src.isNull() ) {
02614             mHoveredUrl = src.nodeValue().string();
02615           }
02616         }
02617       }
02618 
02619       mCanStartDrag = URLHandlerManager::instance()->willHandleDrag( mHoveredUrl, this );
02620       mLastClickPosition = me->pos();
02621     }
02622   }
02623 
02624   if ( e->type() ==  QEvent::MouseButtonRelease ) {
02625     mCanStartDrag = false;
02626   }
02627 
02628   if ( e->type() == QEvent::MouseMove ) {
02629     QMouseEvent* me = static_cast<QMouseEvent*>( e );
02630 
02631     if ( ( mLastClickPosition - me->pos() ).manhattanLength() > KGlobalSettings::dndEventDelay() ) {
02632       if ( mCanStartDrag && !mHoveredUrl.isEmpty() ) {
02633         if ( URLHandlerManager::instance()->handleDrag( mHoveredUrl, this ) ) {
02634           mCanStartDrag = false;
02635           slotUrlOn( QString() );
02636           return true;
02637         }
02638       }
02639     }
02640   }
02641 
02642   // standard event processing
02643   return false;
02644 }
02645 
02646 void KMReaderWin::fillCommandInfo( partNode *node, KMMessage **msg, int *nodeId )
02647 {
02648   Q_ASSERT( msg && nodeId );
02649 
02650   if ( mSerNumOfOriginalMessage != 0 ) {
02651     KMFolder *folder = 0;
02652     int index = -1;
02653     KMMsgDict::instance()->getLocation( mSerNumOfOriginalMessage, &folder, &index );
02654     if ( folder && index != -1 )
02655       *msg = folder->getMsg( index );
02656 
02657     if ( !( *msg ) ) {
02658       kdWarning( 5006 ) << "Unable to find the original message, aborting attachment deletion!" << endl;
02659       return;
02660     }
02661 
02662     *nodeId = node->nodeId() + mNodeIdOffset;
02663   }
02664   else {
02665     *nodeId = node->nodeId();
02666     *msg = message();
02667   }
02668 }
02669 
02670 void KMReaderWin::slotDeleteAttachment(partNode * node)
02671 {
02672   if ( KMessageBox::warningContinueCancel( this,
02673        i18n("Deleting an attachment might invalidate any digital signature on this message."),
02674        i18n("Delete Attachment"), KStdGuiItem::del(), "DeleteAttachmentSignatureWarning" )
02675      != KMessageBox::Continue ) {
02676     return;
02677   }
02678 
02679   int nodeId = -1;
02680   KMMessage *msg = 0;
02681   fillCommandInfo( node, &msg, &nodeId );
02682   if ( msg && nodeId != -1 ) {
02683     KMDeleteAttachmentCommand* command = new KMDeleteAttachmentCommand( nodeId, msg, this );
02684     command->start();
02685     connect( command, SIGNAL( completed( KMCommand * ) ),
02686              this, SLOT( updateReaderWin() ) );
02687     connect( command, SIGNAL( completed( KMCommand * ) ),
02688              this, SLOT( disconnectMsgAdded() ) );
02689 
02690     // ### HACK: Since the command will do delete + add, a new message will arrive. However, we don't
02691     // want the selection to change. Therefore, as soon as a new message arrives, select it, and then
02692     // disconnect.
02693     // Of course the are races, another message can arrive before ours, but we take the risk.
02694     // And it won't work properly with multiple main windows
02695     const KMHeaders * const headers = KMKernel::self()->getKMMainWidget()->headers();
02696     connect( headers, SIGNAL( msgAddedToListView( QListViewItem* ) ),
02697              this, SLOT( msgAdded( QListViewItem* ) ) );
02698   }
02699 
02700   // If we are operating on a copy of parts of the message, make sure to update the copy as well.
02701   if ( mSerNumOfOriginalMessage != 0 && message() ) {
02702     message()->deleteBodyPart( node->nodeId() );
02703     update( true );
02704   }
02705 }
02706 
02707 void KMReaderWin::msgAdded( QListViewItem *item )
02708 {
02709   // A new message was added to the message list view. Select it.
02710   // This is only connected right after we started a attachment delete command, so we expect a new
02711   // message. Disconnect right afterwards, we only want this particular message to be selected.
02712   disconnectMsgAdded();
02713   KMHeaders * const headers = KMKernel::self()->getKMMainWidget()->headers();
02714   headers->setCurrentItem( item );
02715   headers->clearSelection();
02716   headers->setSelected( item, true );
02717 }
02718 
02719 void KMReaderWin::disconnectMsgAdded()
02720 {
02721   const KMHeaders *const headers = KMKernel::self()->getKMMainWidget()->headers();
02722   disconnect( headers, SIGNAL( msgAddedToListView( QListViewItem* ) ),
02723               this, SLOT( msgAdded( QListViewItem* ) ) );
02724 }
02725 
02726 void KMReaderWin::slotEditAttachment(partNode * node)
02727 {
02728   if ( KMessageBox::warningContinueCancel( this,
02729         i18n("Modifying an attachment might invalidate any digital signature on this message."),
02730         i18n("Edit Attachment"), KGuiItem( i18n("Edit"), "edit" ), "EditAttachmentSignatureWarning" )
02731         != KMessageBox::Continue ) {
02732     return;
02733   }
02734 
02735   int nodeId = -1;
02736   KMMessage *msg = 0;
02737   fillCommandInfo( node, &msg, &nodeId );
02738   if ( msg && nodeId != -1 ) {
02739     KMEditAttachmentCommand* command = new KMEditAttachmentCommand( nodeId, msg, this );
02740     command->start();
02741   }
02742 
02743   // FIXME: If we are operating on a copy of parts of the message, make sure to update the copy as well.
02744 }
02745 
02746 KMail::CSSHelper* KMReaderWin::cssHelper()
02747 {
02748   return mCSSHelper;
02749 }
02750 
02751 bool KMReaderWin::decryptMessage() const
02752 {
02753   if ( !GlobalSettings::self()->alwaysDecrypt() )
02754     return mDecrytMessageOverwrite;
02755   return true;
02756 }
02757 
02758 void KMReaderWin::scrollToAttachment( const partNode *node )
02759 {
02760   DOM::Document doc = mViewer->htmlDocument();
02761 
02762   // The anchors for this are created in ObjectTreeParser::parseObjectTree()
02763   mViewer->gotoAnchor( QString::fromLatin1( "att%1" ).arg( node->nodeId() ) );
02764 
02765   // Remove any old color markings which might be there
02766   const partNode *root = node->topLevelParent();
02767   for ( int i = 0; i <= root->totalChildCount() + 1; i++ ) {
02768     DOM::Element attachmentDiv = doc.getElementById( QString( "attachmentDiv%1" ).arg( i + 1 ) );
02769     if ( !attachmentDiv.isNull() )
02770       attachmentDiv.removeAttribute( "style" );
02771   }
02772 
02773   // Now, color the div of the attachment in yellow, so that the user sees what happened.
02774   // We created a special marked div for this in writeAttachmentMarkHeader() in ObjectTreeParser,
02775   // find and modify that now.
02776   DOM::Element attachmentDiv = doc.getElementById( QString( "attachmentDiv%1" ).arg( node->nodeId() ) );
02777   if ( attachmentDiv.isNull() ) {
02778     kdWarning( 5006 ) << "Could not find attachment div for attachment " << node->nodeId() << endl;
02779     return;
02780   }
02781   attachmentDiv.setAttribute( "style", QString( "border:2px solid %1" )
02782       .arg( cssHelper()->pgpWarnColor().name() ) );
02783 
02784   // Update rendering, otherwise the rendering is not updated when the user clicks on an attachment
02785   // that causes scrolling and the open attachment dialog
02786   doc.updateRendering();
02787 }
02788 
02789 void KMReaderWin::injectAttachments()
02790 {
02791   // inject attachments in header view
02792   // we have to do that after the otp has run so we also see encrypted parts
02793   DOM::Document doc = mViewer->htmlDocument();
02794   DOM::Element injectionPoint = doc.getElementById( "attachmentInjectionPoint" );
02795   if ( injectionPoint.isNull() )
02796     return;
02797 
02798   QString imgpath( locate("data","kmail/pics/") );
02799   QString visibility;
02800   QString urlHandle;
02801   QString imgSrc;
02802   if( !showAttachmentQuicklist() )
02803     {
02804       urlHandle.append( "kmail:showAttachmentQuicklist" );
02805       imgSrc.append( "attachmentQuicklistClosed.png" );
02806     } else {
02807       urlHandle.append( "kmail:hideAttachmentQuicklist" );
02808       imgSrc.append( "attachmentQuicklistOpened.png" );
02809     }
02810 
02811   QString html = renderAttachments( mRootNode, QApplication::palette().active().background() );
02812   if ( html.isEmpty() )
02813     return;
02814 
02815     QString link("");
02816     if ( headerStyle() == HeaderStyle::fancy() ) {
02817       link += "<div style=\"text-align: left;\"><a href=\""+urlHandle+"\"><img src=\""+imgpath+imgSrc+"\"/></a></div>";
02818       html.prepend( link );
02819       html.prepend( QString::fromLatin1("<div style=\"float:left;\">%1&nbsp;</div>" ).arg(i18n("Attachments:")) );
02820     } else {
02821       link += "<div style=\"text-align: right;\"><a href=\""+urlHandle+"\"><img src=\""+imgpath+imgSrc+"\"/></a></div>";
02822       html.prepend( link );
02823     }
02824 
02825     assert( injectionPoint.tagName() == "div" );
02826     static_cast<DOM::HTMLElement>( injectionPoint ).setInnerHTML( html );
02827 }
02828 
02829 static QColor nextColor( const QColor & c )
02830 {
02831   int h, s, v;
02832   c.hsv( &h, &s, &v );
02833   return QColor( (h + 50) % 360, QMAX(s, 64), v, QColor::Hsv );
02834 }
02835 
02836 QString KMReaderWin::renderAttachments(partNode * node, const QColor &bgColor )
02837 {
02838   if ( !node )
02839     return QString();
02840 
02841   QString html;
02842   if ( node->firstChild() ) {
02843     QString subHtml = renderAttachments( node->firstChild(), nextColor( bgColor ) );
02844     if ( !subHtml.isEmpty() ) {
02845 
02846       QString visibility;
02847       if ( !showAttachmentQuicklist() ) {
02848         visibility.append( "display:none;" );
02849       }
02850 
02851       QString margin;
02852       if ( node != mRootNode || headerStyle() != HeaderStyle::enterprise() )
02853         margin = "padding:2px; margin:2px; ";
02854       QString align = "left";
02855       if ( headerStyle() == HeaderStyle::enterprise() )
02856         align = "right";
02857       if ( node->msgPart().typeStr().lower() == "message" || node == mRootNode )
02858         html += QString::fromLatin1("<div style=\"background:%1; %2"
02859                 "vertical-align:middle; float:%3; %4\">").arg( bgColor.name() ).arg( margin )
02860                                                          .arg( align ).arg( visibility );
02861       html += subHtml;
02862       if ( node->msgPart().typeStr().lower() == "message" || node == mRootNode )
02863         html += "</div>";
02864     }
02865   } else {
02866     QString label, icon;
02867     icon = node->msgPart().iconName( KIcon::Small );
02868     label = node->msgPart().contentDescription();
02869     if( label.isEmpty() )
02870       label = node->msgPart().name().stripWhiteSpace();
02871     if( label.isEmpty() )
02872       label = node->msgPart().fileName();
02873     bool typeBlacklisted = node->msgPart().typeStr().lower() == "multipart";
02874     if ( !typeBlacklisted && node->msgPart().typeStr().lower() == "application" ) {
02875       typeBlacklisted = node->msgPart().subtypeStr() == "pgp-encrypted"
02876           || node->msgPart().subtypeStr().lower() == "pgp-signature"
02877           || node->msgPart().subtypeStr().lower() == "pkcs7-mime"
02878           || node->msgPart().subtypeStr().lower() == "pkcs7-signature";
02879     }
02880     typeBlacklisted = typeBlacklisted || node == mRootNode;
02881     bool firstTextChildOfEncapsulatedMsg = node->msgPart().typeStr().lower() == "text" &&
02882                                            node->msgPart().subtypeStr().lower() == "plain" &&
02883                                            node->parentNode() &&
02884                                            node->parentNode()->msgPart().typeStr().lower() == "message";
02885     typeBlacklisted = typeBlacklisted || firstTextChildOfEncapsulatedMsg;
02886     if ( !label.isEmpty() && !icon.isEmpty() && !typeBlacklisted ) {
02887       html += "<div style=\"float:left;\">";
02888       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() );
02889       QString fileName = writeMessagePartToTempFile( &node->msgPart(), node->nodeId() );
02890       QString href = node->asHREF( "header" );
02891       html += QString::fromLatin1( "<a href=\"" ) + href +
02892               QString::fromLatin1( "\">" );
02893       html += "<img style=\"vertical-align:middle;\" src=\"" + icon + "\"/>&nbsp;";
02894       if ( headerStyle() == HeaderStyle::enterprise() ) {
02895         QFont bodyFont = mCSSHelper->bodyFont( isFixedFont() );
02896         QFontMetrics fm( bodyFont );
02897         html += KStringHandler::rPixelSqueeze( label, fm, 140 );
02898       } else if ( headerStyle() == HeaderStyle::fancy() ) {
02899         QFont bodyFont = mCSSHelper->bodyFont( isFixedFont() );
02900         QFontMetrics fm( bodyFont );
02901         html += KStringHandler::rPixelSqueeze( label, fm, 1000 );
02902       } else {
02903         html += label;
02904       }
02905       html += "</a></span></div> ";
02906     }
02907   }
02908 
02909   html += renderAttachments( node->nextSibling(), nextColor ( bgColor ) );
02910   return html;
02911 }
02912 
02913 using namespace KMail::Interface;
02914 
02915 void KMReaderWin::setBodyPartMemento( const partNode * node, const QCString & which, BodyPartMemento * memento )
02916 {
02917   const QCString index = node->path() + ':' + which.lower();
02918 
02919   const std::map<QCString,BodyPartMemento*>::iterator it = mBodyPartMementoMap.lower_bound( index );
02920   if ( it != mBodyPartMementoMap.end() && it->first == index ) {
02921 
02922     if ( memento && memento == it->second )
02923       return;
02924 
02925     delete it->second;
02926 
02927     if ( memento ) {
02928       it->second = memento;
02929     }
02930     else {
02931       mBodyPartMementoMap.erase( it );
02932     }
02933 
02934   } else {
02935     if ( memento ) {
02936       mBodyPartMementoMap.insert( it, std::make_pair( index, memento ) );
02937     }
02938   }
02939 
02940   if ( Observable * o = memento ? memento->asObservable() : 0 )
02941     o->attach( this );
02942 }
02943 
02944 BodyPartMemento * KMReaderWin::bodyPartMemento( const partNode * node, const QCString & which ) const
02945 {
02946   const QCString index = node->path() + ':' + which.lower();
02947   const std::map<QCString,BodyPartMemento*>::const_iterator it = mBodyPartMementoMap.find( index );
02948   if ( it == mBodyPartMementoMap.end() ) {
02949     return 0;
02950   }
02951   else {
02952     return it->second;
02953   }
02954 }
02955 
02956 static void detach_and_delete( BodyPartMemento * memento, KMReaderWin * obs ) {
02957   if ( Observable * const o = memento ? memento->asObservable() : 0 )
02958     o->detach( obs );
02959   delete memento;
02960 }
02961 
02962 void KMReaderWin::clearBodyPartMementos()
02963 {
02964   for ( std::map<QCString,BodyPartMemento*>::const_iterator it = mBodyPartMementoMap.begin(), end = mBodyPartMementoMap.end() ; it != end ; ++it )
02965     // Detach the memento from the reader. When cancelling it, it might trigger an update of the
02966     // reader, which we are not interested in, and which is dangerous, since half the mementos are
02967     // already deleted.
02968     // https://issues.kolab.org/issue4187
02969     detach_and_delete( it->second, this );
02970 
02971   mBodyPartMementoMap.clear();
02972 }
02973 
02974 #include "kmreaderwin.moc"
02975 
02976 
KDE Home | KDE Accessibility Home | Description of Access Keys