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