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