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