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