kmail

kmreaderwin.cpp

Go to the documentation of this file.
00001 // -*- mode: C++; c-file-style: "gnu" -*-
00002 // kmreaderwin.cpp
00003 // Author: Markus Wuebben <markus.wuebben@kde.org>
00004 
00005 // define this to copy all html that is written to the readerwindow to
00006 // filehtmlwriter.out in the current working directory
00007 //#define KMAIL_READER_HTML_DEBUG 1
00008 
00009 #include <config.h>
00010 
00011 #include "kmreaderwin.h"
00012 
00013 #include "globalsettings.h"
00014 #include "kmversion.h"
00015 #include "kmmainwidget.h"
00016 #include "kmreadermainwin.h"
00017 #include <libkdepim/kfileio.h>
00018 #include "kmfolderindex.h"
00019 #include "kmcommands.h"
00020 #include "kmmsgpartdlg.h"
00021 #include "mailsourceviewer.h"
00022 using KMail::MailSourceViewer;
00023 #include "partNode.h"
00024 #include "kmmsgdict.h"
00025 #include "messagesender.h"
00026 #include "kcursorsaver.h"
00027 #include "kmfolder.h"
00028 #include "vcardviewer.h"
00029 using KMail::VCardViewer;
00030 #include "objecttreeparser.h"
00031 using KMail::ObjectTreeParser;
00032 #include "partmetadata.h"
00033 using KMail::PartMetaData;
00034 #include "attachmentstrategy.h"
00035 using KMail::AttachmentStrategy;
00036 #include "headerstrategy.h"
00037 using KMail::HeaderStrategy;
00038 #include "headerstyle.h"
00039 using KMail::HeaderStyle;
00040 #include "khtmlparthtmlwriter.h"
00041 using KMail::HtmlWriter;
00042 using KMail::KHtmlPartHtmlWriter;
00043 #include "htmlstatusbar.h"
00044 using KMail::HtmlStatusBar;
00045 #include "folderjob.h"
00046 using KMail::FolderJob;
00047 #include "csshelper.h"
00048 using KMail::CSSHelper;
00049 #include "isubject.h"
00050 using KMail::ISubject;
00051 #include "urlhandlermanager.h"
00052 using KMail::URLHandlerManager;
00053 #include "interfaces/observable.h"
00054 #include "util.h"
00055 
00056 #include "broadcaststatus.h"
00057 
00058 #include <kmime_mdn.h>
00059 using namespace KMime;
00060 #ifdef KMAIL_READER_HTML_DEBUG
00061 #include "filehtmlwriter.h"
00062 using KMail::FileHtmlWriter;
00063 #include "teehtmlwriter.h"
00064 using KMail::TeeHtmlWriter;
00065 #endif
00066 
00067 #include <kasciistringtools.h>
00068 #include <kstringhandler.h>
00069 
00070 #include <mimelib/mimepp.h>
00071 #include <mimelib/body.h>
00072 #include <mimelib/utility.h>
00073 
00074 #include <kleo/specialjob.h>
00075 #include <kleo/cryptobackend.h>
00076 #include <kleo/cryptobackendfactory.h>
00077 
00078 // KABC includes
00079 #include <kabc/addressee.h>
00080 #include <kabc/vcardconverter.h>
00081 
00082 // khtml headers
00083 #include <khtml_part.h>
00084 #include <khtmlview.h> // So that we can get rid of the frames
00085 #include <dom/html_element.h>
00086 #include <dom/html_block.h>
00087 #include <dom/html_document.h>
00088 #include <dom/dom_string.h>
00089 
00090 
00091 #include <kapplication.h>
00092 // for the click on attachment stuff (dnaber):
00093 #include <kuserprofile.h>
00094 #include <kcharsets.h>
00095 #include <kpopupmenu.h>
00096 #include <kstandarddirs.h>  // Sven's : for access and getpid
00097 #include <kcursor.h>
00098 #include <kdebug.h>
00099 #include <kfiledialog.h>
00100 #include <klocale.h>
00101 #include <kmessagebox.h>
00102 #include <kglobalsettings.h>
00103 #include <krun.h>
00104 #include <ktempfile.h>
00105 #include <kprocess.h>
00106 #include <kdialog.h>
00107 #include <kaction.h>
00108 #include <kiconloader.h>
00109 #include <kmdcodec.h>
00110 #include <kasciistricmp.h>
00111 #include <kurldrag.h>
00112 
00113 #include <qclipboard.h>
00114 #include <qhbox.h>
00115 #include <qtextcodec.h>
00116 #include <qpaintdevicemetrics.h>
00117 #include <qlayout.h>
00118 #include <qlabel.h>
00119 #include <qsplitter.h>
00120 #include <qstyle.h>
00121 
00122 // X headers...
00123 #undef Never
00124 #undef Always
00125 
00126 #include <unistd.h>
00127 #include <stdlib.h>
00128 #include <sys/stat.h>
00129 #include <errno.h>
00130 #include <stdio.h>
00131 #include <ctype.h>
00132 #include <string.h>
00133 
00134 #ifdef HAVE_PATHS_H
00135 #include <paths.h>
00136 #endif
00137 
00138 class NewByteArray : public QByteArray
00139 {
00140 public:
00141     NewByteArray &appendNULL();
00142     NewByteArray &operator+=( const char * );
00143     NewByteArray &operator+=( const QByteArray & );
00144     NewByteArray &operator+=( const QCString & );
00145     QByteArray& qByteArray();
00146 };
00147 
00148 NewByteArray& NewByteArray::appendNULL()
00149 {
00150     QByteArray::detach();
00151     uint len1 = size();
00152     if ( !QByteArray::resize( len1 + 1 ) )
00153         return *this;
00154     *(data() + len1) = '\0';
00155     return *this;
00156 }
00157 NewByteArray& NewByteArray::operator+=( const char * newData )
00158 {
00159     if ( !newData )
00160         return *this;
00161     QByteArray::detach();
00162     uint len1 = size();
00163     uint len2 = qstrlen( newData );
00164     if ( !QByteArray::resize( len1 + len2 ) )
00165         return *this;
00166     memcpy( data() + len1, newData, len2 );
00167     return *this;
00168 }
00169 NewByteArray& NewByteArray::operator+=( const QByteArray & newData )
00170 {
00171     if ( newData.isNull() )
00172         return *this;
00173     QByteArray::detach();
00174     uint len1 = size();
00175     uint len2 = newData.size();
00176     if ( !QByteArray::resize( len1 + len2 ) )
00177         return *this;
00178     memcpy( data() + len1, newData.data(), len2 );
00179     return *this;
00180 }
00181 NewByteArray& NewByteArray::operator+=( const QCString & newData )
00182 {
00183     if ( newData.isEmpty() )
00184         return *this;
00185     QByteArray::detach();
00186     uint len1 = size();
00187     uint len2 = newData.length(); // forget about the trailing 0x00 !
00188     if ( !QByteArray::resize( len1 + len2 ) )
00189         return *this;
00190     memcpy( data() + len1, newData.data(), len2 );
00191     return *this;
00192 }
00193 QByteArray& NewByteArray::qByteArray()
00194 {
00195     return *((QByteArray*)this);
00196 }
00197 
00198 // This function returns the complete data that were in this
00199 // message parts - *after* all encryption has been removed that
00200 // could be removed.
00201 // - This is used to store the message in decrypted form.
00202 void KMReaderWin::objectTreeToDecryptedMsg( partNode* node,
00203                                             NewByteArray& resultingData,
00204                                             KMMessage& theMessage,
00205                                             bool weAreReplacingTheRootNode,
00206                                             int recCount )
00207 {
00208   kdDebug(5006) << QString("-------------------------------------------------" ) << endl;
00209   kdDebug(5006) << QString("KMReaderWin::objectTreeToDecryptedMsg( %1 )  START").arg( recCount ) << endl;
00210   if( node ) {
00211     partNode* curNode = node;
00212     partNode* dataNode = curNode;
00213     partNode * child = node->firstChild();
00214     bool bIsMultipart = false;
00215 
00216     switch( curNode->type() ){
00217       case DwMime::kTypeText: {
00218 kdDebug(5006) << "* text *" << endl;
00219           switch( curNode->subType() ){
00220           case DwMime::kSubtypeHtml:
00221 kdDebug(5006) << "html" << endl;
00222             break;
00223           case DwMime::kSubtypeXVCard:
00224 kdDebug(5006) << "v-card" << endl;
00225             break;
00226           case DwMime::kSubtypeRichtext:
00227 kdDebug(5006) << "rich text" << endl;
00228             break;
00229           case DwMime::kSubtypeEnriched:
00230 kdDebug(5006) << "enriched " << endl;
00231             break;
00232           case DwMime::kSubtypePlain:
00233 kdDebug(5006) << "plain " << endl;
00234             break;
00235           default:
00236 kdDebug(5006) << "default " << endl;
00237             break;
00238           }
00239         }
00240         break;
00241       case DwMime::kTypeMultipart: {
00242 kdDebug(5006) << "* multipart *" << endl;
00243           bIsMultipart = true;
00244           switch( curNode->subType() ){
00245           case DwMime::kSubtypeMixed:
00246 kdDebug(5006) << "mixed" << endl;
00247             break;
00248           case DwMime::kSubtypeAlternative:
00249 kdDebug(5006) << "alternative" << endl;
00250             break;
00251           case DwMime::kSubtypeDigest:
00252 kdDebug(5006) << "digest" << endl;
00253             break;
00254           case DwMime::kSubtypeParallel:
00255 kdDebug(5006) << "parallel" << endl;
00256             break;
00257           case DwMime::kSubtypeSigned:
00258 kdDebug(5006) << "signed" << endl;
00259             break;
00260           case DwMime::kSubtypeEncrypted: {
00261 kdDebug(5006) << "encrypted" << endl;
00262               if ( child ) {
00263                 /*
00264                     ATTENTION: This code is to be replaced by the new 'auto-detect' feature. --------------------------------------
00265                 */
00266                 partNode* data =
00267                   child->findType( DwMime::kTypeApplication, DwMime::kSubtypeOctetStream, false, true );
00268                 if ( !data )
00269                   data = child->findType( DwMime::kTypeApplication, DwMime::kSubtypePkcs7Mime, false, true );
00270                 if ( data && data->firstChild() )
00271                   dataNode = data;
00272               }
00273             }
00274             break;
00275           default :
00276 kdDebug(5006) << "(  unknown subtype  )" << endl;
00277             break;
00278           }
00279         }
00280         break;
00281       case DwMime::kTypeMessage: {
00282 kdDebug(5006) << "* message *" << endl;
00283           switch( curNode->subType() ){
00284           case DwMime::kSubtypeRfc822: {
00285 kdDebug(5006) << "RfC 822" << endl;
00286               if ( child )
00287                 dataNode = child;
00288             }
00289             break;
00290           }
00291         }
00292         break;
00293       case DwMime::kTypeApplication: {
00294 kdDebug(5006) << "* application *" << endl;
00295           switch( curNode->subType() ){
00296           case DwMime::kSubtypePostscript:
00297 kdDebug(5006) << "postscript" << endl;
00298             break;
00299           case DwMime::kSubtypeOctetStream: {
00300 kdDebug(5006) << "octet stream" << endl;
00301               if ( child )
00302                 dataNode = child;
00303             }
00304             break;
00305           case DwMime::kSubtypePgpEncrypted:
00306 kdDebug(5006) << "pgp encrypted" << endl;
00307             break;
00308           case DwMime::kSubtypePgpSignature:
00309 kdDebug(5006) << "pgp signed" << endl;
00310             break;
00311           case DwMime::kSubtypePkcs7Mime: {
00312 kdDebug(5006) << "pkcs7 mime" << endl;
00313               // note: subtype Pkcs7Mime can also be signed
00314               //       and we do NOT want to remove the signature!
00315               if ( child && curNode->encryptionState() != KMMsgNotEncrypted )
00316                 dataNode = child;
00317             }
00318             break;
00319           }
00320         }
00321         break;
00322       case DwMime::kTypeImage: {
00323 kdDebug(5006) << "* image *" << endl;
00324           switch( curNode->subType() ){
00325           case DwMime::kSubtypeJpeg:
00326 kdDebug(5006) << "JPEG" << endl;
00327             break;
00328           case DwMime::kSubtypeGif:
00329 kdDebug(5006) << "GIF" << endl;
00330             break;
00331           }
00332         }
00333         break;
00334       case DwMime::kTypeAudio: {
00335 kdDebug(5006) << "* audio *" << endl;
00336           switch( curNode->subType() ){
00337           case DwMime::kSubtypeBasic:
00338 kdDebug(5006) << "basic" << endl;
00339             break;
00340           }
00341         }
00342         break;
00343       case DwMime::kTypeVideo: {
00344 kdDebug(5006) << "* video *" << endl;
00345           switch( curNode->subType() ){
00346           case DwMime::kSubtypeMpeg:
00347 kdDebug(5006) << "mpeg" << endl;
00348             break;
00349           }
00350         }
00351         break;
00352       case DwMime::kTypeModel:
00353 kdDebug(5006) << "* model *" << endl;
00354         break;
00355     }
00356 
00357 
00358     DwHeaders& rootHeaders( theMessage.headers() );
00359     DwBodyPart * part = dataNode->dwPart() ? dataNode->dwPart() : 0;
00360     DwHeaders * headers(
00361         (part && part->hasHeaders())
00362         ? &part->Headers()
00363         : (  (weAreReplacingTheRootNode || !dataNode->parentNode())
00364             ? &rootHeaders
00365             : 0 ) );
00366     if( dataNode == curNode ) {
00367 kdDebug(5006) << "dataNode == curNode:  Save curNode without replacing it." << endl;
00368 
00369       // A) Store the headers of this part IF curNode is not the root node
00370       //    AND we are not replacing a node that already *has* replaced
00371       //    the root node in previous recursion steps of this function...
00372       if( headers ) {
00373         if( dataNode->parentNode() && !weAreReplacingTheRootNode ) {
00374 kdDebug(5006) << "dataNode is NOT replacing the root node:  Store the headers." << endl;
00375           resultingData += headers->AsString().c_str();
00376         } else if( weAreReplacingTheRootNode && part && part->hasHeaders() ){
00377 kdDebug(5006) << "dataNode replace the root node:  Do NOT store the headers but change" << endl;
00378 kdDebug(5006) << "                                 the Message's headers accordingly." << endl;
00379 kdDebug(5006) << "              old Content-Type = " << rootHeaders.ContentType().AsString().c_str() << endl;
00380 kdDebug(5006) << "              new Content-Type = " << headers->ContentType(   ).AsString().c_str() << endl;
00381           rootHeaders.ContentType()             = headers->ContentType();
00382           theMessage.setContentTransferEncodingStr(
00383               headers->HasContentTransferEncoding()
00384             ? headers->ContentTransferEncoding().AsString().c_str()
00385             : "" );
00386           rootHeaders.ContentDescription() = headers->ContentDescription();
00387           rootHeaders.ContentDisposition() = headers->ContentDisposition();
00388           theMessage.setNeedsAssembly();
00389         }
00390       }
00391 
00392       // B) Store the body of this part.
00393       if( headers && bIsMultipart && dataNode->firstChild() )  {
00394 kdDebug(5006) << "is valid Multipart, processing children:" << endl;
00395         QCString boundary = headers->ContentType().Boundary().c_str();
00396         curNode = dataNode->firstChild();
00397         // store children of multipart
00398         while( curNode ) {
00399 kdDebug(5006) << "--boundary" << endl;
00400           if( resultingData.size() &&
00401               ( '\n' != resultingData.at( resultingData.size()-1 ) ) )
00402             resultingData += QCString( "\n" );
00403           resultingData += QCString( "\n" );
00404           resultingData += "--";
00405           resultingData += boundary;
00406           resultingData += "\n";
00407           // note: We are processing a harmless multipart that is *not*
00408           //       to be replaced by one of it's children, therefor
00409           //       we set their doStoreHeaders to true.
00410           objectTreeToDecryptedMsg( curNode,
00411                                     resultingData,
00412                                     theMessage,
00413                                     false,
00414                                     recCount + 1 );
00415           curNode = curNode->nextSibling();
00416         }
00417 kdDebug(5006) << "--boundary--" << endl;
00418         resultingData += "\n--";
00419         resultingData += boundary;
00420         resultingData += "--\n\n";
00421 kdDebug(5006) << "Multipart processing children - DONE" << endl;
00422       } else if( part ){
00423         // store simple part
00424 kdDebug(5006) << "is Simple part or invalid Multipart, storing body data .. DONE" << endl;
00425         resultingData += part->Body().AsString().c_str();
00426       }
00427     } else {
00428 kdDebug(5006) << "dataNode != curNode:  Replace curNode by dataNode." << endl;
00429       bool rootNodeReplaceFlag = weAreReplacingTheRootNode || !curNode->parentNode();
00430       if( rootNodeReplaceFlag ) {
00431 kdDebug(5006) << "                      Root node will be replaced." << endl;
00432       } else {
00433 kdDebug(5006) << "                      Root node will NOT be replaced." << endl;
00434       }
00435       // store special data to replace the current part
00436       // (e.g. decrypted data or embedded RfC 822 data)
00437       objectTreeToDecryptedMsg( dataNode,
00438                                 resultingData,
00439                                 theMessage,
00440                                 rootNodeReplaceFlag,
00441                                 recCount + 1 );
00442     }
00443   }
00444   kdDebug(5006) << QString("\nKMReaderWin::objectTreeToDecryptedMsg( %1 )  END").arg( recCount ) << endl;
00445 }
00446 
00447 
00448 /*
00449  ===========================================================================
00450 
00451 
00452         E N D    O F     T E M P O R A R Y     M I M E     C O D E
00453 
00454 
00455  ===========================================================================
00456 */
00457 
00458 
00459 
00460 
00461 
00462 
00463 
00464 
00465 
00466 
00467 
00468 void KMReaderWin::createWidgets() {
00469   QVBoxLayout * vlay = new QVBoxLayout( this );
00470   mSplitter = new QSplitter( Qt::Vertical, this, "mSplitter" );
00471   vlay->addWidget( mSplitter );
00472   mMimePartTree = new KMMimePartTree( this, mSplitter, "mMimePartTree" );
00473   mBox = new QHBox( mSplitter, "mBox" );
00474   setStyleDependantFrameWidth();
00475   mBox->setFrameStyle( mMimePartTree->frameStyle() );
00476   mColorBar = new HtmlStatusBar( mBox, "mColorBar" );
00477   mViewer = new KHTMLPart( mBox, "mViewer" );
00478   mSplitter->setOpaqueResize( KGlobalSettings::opaqueResize() );
00479   mSplitter->setResizeMode( mMimePartTree, QSplitter::KeepSize );
00480 }
00481 
00482 const int KMReaderWin::delay = 150;
00483 
00484 //-----------------------------------------------------------------------------
00485 KMReaderWin::KMReaderWin(QWidget *aParent,
00486              QWidget *mainWindow,
00487              KActionCollection* actionCollection,
00488                          const char *aName,
00489                          int aFlags )
00490   : QWidget(aParent, aName, aFlags | Qt::WDestructiveClose),
00491     mAttachmentStrategy( 0 ),
00492     mHeaderStrategy( 0 ),
00493     mHeaderStyle( 0 ),
00494     mUpdateReaderWinTimer( 0, "mUpdateReaderWinTimer" ),
00495     mResizeTimer( 0, "mResizeTimer" ),
00496     mDelayedMarkTimer( 0, "mDelayedMarkTimer" ),
00497     mOldGlobalOverrideEncoding( "---" ), // init with dummy value
00498     mCSSHelper( 0 ),
00499     mRootNode( 0 ),
00500     mMainWindow( mainWindow ),
00501     mActionCollection( actionCollection ),
00502     mMailToComposeAction( 0 ),
00503     mMailToReplyAction( 0 ),
00504     mMailToForwardAction( 0 ),
00505     mAddAddrBookAction( 0 ),
00506     mOpenAddrBookAction( 0 ),
00507     mCopyAction( 0 ),
00508     mCopyURLAction( 0 ),
00509     mUrlOpenAction( 0 ),
00510     mUrlSaveAsAction( 0 ),
00511     mAddBookmarksAction( 0 ),
00512     mStartIMChatAction( 0 ),
00513     mSelectAllAction( 0 ),
00514     mSelectEncodingAction( 0 ),
00515     mToggleFixFontAction( 0 ),
00516     mHtmlWriter( 0 ),
00517     mSavedRelativePosition( 0 ),
00518     mDecrytMessageOverwrite( false ),
00519     mShowSignatureDetails( false ),
00520     mShowAttachmentQuicklist( true )
00521 {
00522   mSplitterSizes << 180 << 100;
00523   mMimeTreeMode = 1;
00524   mMimeTreeAtBottom = true;
00525   mAutoDelete = false;
00526   mLastSerNum = 0;
00527   mWaitingForSerNum = 0;
00528   mMessage = 0;
00529   mLastStatus = KMMsgStatusUnknown;
00530   mMsgDisplay = true;
00531   mPrinting = false;
00532   mShowColorbar = false;
00533   mAtmUpdate = false;
00534 
00535   createWidgets();
00536   createActions( actionCollection );
00537   initHtmlWidget();
00538   readConfig();
00539 
00540   mHtmlOverride = false;
00541   mHtmlLoadExtOverride = false;
00542 
00543   mLevelQuote = GlobalSettings::self()->collapseQuoteLevelSpin() - 1;
00544 
00545   connect( &mUpdateReaderWinTimer, SIGNAL(timeout()),
00546        this, SLOT(updateReaderWin()) );
00547   connect( &mResizeTimer, SIGNAL(timeout()),
00548        this, SLOT(slotDelayedResize()) );
00549   connect( &mDelayedMarkTimer, SIGNAL(timeout()),
00550            this, SLOT(slotTouchMessage()) );
00551 
00552 }
00553 
00554 void KMReaderWin::createActions( KActionCollection * ac ) {
00555   if ( !ac )
00556       return;
00557 
00558   KRadioAction *raction = 0;
00559 
00560   // header style
00561   KActionMenu *headerMenu =
00562     new KActionMenu( i18n("View->", "&Headers"), ac, "view_headers" );
00563   headerMenu->setToolTip( i18n("Choose display style of message headers") );
00564 
00565   connect( headerMenu, SIGNAL(activated()),
00566            this, SLOT(slotCycleHeaderStyles()) );
00567 
00568   raction = new KRadioAction( i18n("View->headers->", "&Enterprise Headers"), 0,
00569                               this, SLOT(slotEnterpriseHeaders()),
00570                               ac, "view_headers_enterprise" );
00571   raction->setToolTip( i18n("Show the list of headers in Enterprise style") );
00572   raction->setExclusiveGroup( "view_headers_group" );
00573   headerMenu->insert(raction);
00574 
00575   raction = new KRadioAction( i18n("View->headers->", "&Fancy Headers"), 0,
00576                               this, SLOT(slotFancyHeaders()),
00577                               ac, "view_headers_fancy" );
00578   raction->setToolTip( i18n("Show the list of headers in a fancy format") );
00579   raction->setExclusiveGroup( "view_headers_group" );
00580   headerMenu->insert( raction );
00581 
00582   raction = new KRadioAction( i18n("View->headers->", "&Brief Headers"), 0,
00583                               this, SLOT(slotBriefHeaders()),
00584                               ac, "view_headers_brief" );
00585   raction->setToolTip( i18n("Show brief list of message headers") );
00586   raction->setExclusiveGroup( "view_headers_group" );
00587   headerMenu->insert( raction );
00588 
00589   raction = new KRadioAction( i18n("View->headers->", "&Standard Headers"), 0,
00590                               this, SLOT(slotStandardHeaders()),
00591                               ac, "view_headers_standard" );
00592   raction->setToolTip( i18n("Show standard list of message headers") );
00593   raction->setExclusiveGroup( "view_headers_group" );
00594   headerMenu->insert( raction );
00595 
00596   raction = new KRadioAction( i18n("View->headers->", "&Long Headers"), 0,
00597                               this, SLOT(slotLongHeaders()),
00598                               ac, "view_headers_long" );
00599   raction->setToolTip( i18n("Show long list of message headers") );
00600   raction->setExclusiveGroup( "view_headers_group" );
00601   headerMenu->insert( raction );
00602 
00603   raction = new KRadioAction( i18n("View->headers->", "&All Headers"), 0,
00604                               this, SLOT(slotAllHeaders()),
00605                               ac, "view_headers_all" );
00606   raction->setToolTip( i18n("Show all message headers") );
00607   raction->setExclusiveGroup( "view_headers_group" );
00608   headerMenu->insert( raction );
00609 
00610   // attachment style
00611   KActionMenu *attachmentMenu =
00612     new KActionMenu( i18n("View->", "&Attachments"), ac, "view_attachments" );
00613   attachmentMenu->setToolTip( i18n("Choose display style of attachments") );
00614   connect( attachmentMenu, SIGNAL(activated()),
00615            this, SLOT(slotCycleAttachmentStrategy()) );
00616 
00617   raction = new KRadioAction( i18n("View->attachments->", "&As Icons"), 0,
00618                               this, SLOT(slotIconicAttachments()),
00619                               ac, "view_attachments_as_icons" );
00620   raction->setToolTip( i18n("Show all attachments as icons. Click to see them.") );
00621   raction->setExclusiveGroup( "view_attachments_group" );
00622   attachmentMenu->insert( raction );
00623 
00624   raction = new KRadioAction( i18n("View->attachments->", "&Smart"), 0,
00625                               this, SLOT(slotSmartAttachments()),
00626                               ac, "view_attachments_smart" );
00627   raction->setToolTip( i18n("Show attachments as suggested by sender.") );
00628   raction->setExclusiveGroup( "view_attachments_group" );
00629   attachmentMenu->insert( raction );
00630 
00631   raction = new KRadioAction( i18n("View->attachments->", "&Inline"), 0,
00632                               this, SLOT(slotInlineAttachments()),
00633                               ac, "view_attachments_inline" );
00634   raction->setToolTip( i18n("Show all attachments inline (if possible)") );
00635   raction->setExclusiveGroup( "view_attachments_group" );
00636   attachmentMenu->insert( raction );
00637 
00638   raction = new KRadioAction( i18n("View->attachments->", "&Hide"), 0,
00639                               this, SLOT(slotHideAttachments()),
00640                               ac, "view_attachments_hide" );
00641   raction->setToolTip( i18n("Do not show attachments in the message viewer") );
00642   raction->setExclusiveGroup( "view_attachments_group" );
00643   attachmentMenu->insert( raction );
00644 
00645   // Set Encoding submenu
00646   mSelectEncodingAction = new KSelectAction( i18n( "&Set Encoding" ), "charset", 0,
00647                                  this, SLOT( slotSetEncoding() ),
00648                                  ac, "encoding" );
00649   QStringList encodings = KMMsgBase::supportedEncodings( false );
00650   encodings.prepend( i18n( "Auto" ) );
00651   mSelectEncodingAction->setItems( encodings );
00652   mSelectEncodingAction->setCurrentItem( 0 );
00653 
00654   mMailToComposeAction = new KAction( i18n("New Message To..."), "mail_new",
00655                                       0, this, SLOT(slotMailtoCompose()), ac,
00656                                       "mailto_compose" );
00657   mMailToReplyAction = new KAction( i18n("Reply To..."), "mail_reply",
00658                                     0, this, SLOT(slotMailtoReply()), ac,
00659                     "mailto_reply" );
00660   mMailToForwardAction = new KAction( i18n("Forward To..."), "mail_forward",
00661                                       0, this, SLOT(slotMailtoForward()), ac,
00662                                       "mailto_forward" );
00663   mAddAddrBookAction = new KAction( i18n("Add to Address Book"),
00664                     0, this, SLOT(slotMailtoAddAddrBook()),
00665                     ac, "add_addr_book" );
00666   mOpenAddrBookAction = new KAction( i18n("Open in Address Book"),
00667                                      0, this, SLOT(slotMailtoOpenAddrBook()),
00668                                      ac, "openin_addr_book" );
00669   mCopyAction = KStdAction::copy( this, SLOT(slotCopySelectedText()), ac, "kmail_copy");
00670   mSelectAllAction = new KAction( i18n("Select All Text"), CTRL+SHIFT+Key_A, this,
00671                                   SLOT(selectAll()), ac, "mark_all_text" );
00672   mCopyURLAction = new KAction( i18n("Copy Link Address"), 0, this,
00673                 SLOT(slotUrlCopy()), ac, "copy_url" );
00674   mUrlOpenAction = new KAction( i18n("Open URL"), 0, this,
00675                                 SLOT(slotUrlOpen()), ac, "open_url" );
00676   mAddBookmarksAction = new KAction( i18n("Bookmark This Link"),
00677                                      "bookmark_add",
00678                                      0, this, SLOT(slotAddBookmarks()),
00679                                      ac, "add_bookmarks" );
00680   mUrlSaveAsAction = new KAction( i18n("Save Link As..."), 0, this,
00681                                   SLOT(slotUrlSave()), ac, "saveas_url" );
00682 
00683   mToggleFixFontAction = new KToggleAction( i18n("Use Fi&xed Font"),
00684                                             Key_X, this, SLOT(slotToggleFixedFont()),
00685                                             ac, "toggle_fixedfont" );
00686 
00687   mStartIMChatAction = new KAction( i18n("Chat &With..."), 0, this,
00688                     SLOT(slotIMChat()), ac, "start_im_chat" );
00689 }
00690 
00691 // little helper function
00692 KRadioAction *KMReaderWin::actionForHeaderStyle( const HeaderStyle * style, const HeaderStrategy * strategy ) {
00693   if ( !mActionCollection )
00694     return 0;
00695   const char * actionName = 0;
00696   if ( style == HeaderStyle::enterprise() )
00697     actionName = "view_headers_enterprise";
00698   if ( style == HeaderStyle::fancy() )
00699     actionName = "view_headers_fancy";
00700   else if ( style == HeaderStyle::brief() )
00701     actionName = "view_headers_brief";
00702   else if ( style == HeaderStyle::plain() ) {
00703     if ( strategy == HeaderStrategy::standard() )
00704       actionName = "view_headers_standard";
00705     else if ( strategy == HeaderStrategy::rich() )
00706       actionName = "view_headers_long";
00707     else if ( strategy == HeaderStrategy::all() )
00708       actionName = "view_headers_all";
00709   }
00710   if ( actionName )
00711     return static_cast<KRadioAction*>(mActionCollection->action(actionName));
00712   else
00713     return 0;
00714 }
00715 
00716 KRadioAction *KMReaderWin::actionForAttachmentStrategy( const AttachmentStrategy * as ) {
00717   if ( !mActionCollection )
00718     return 0;
00719   const char * actionName = 0;
00720   if ( as == AttachmentStrategy::iconic() )
00721     actionName = "view_attachments_as_icons";
00722   else if ( as == AttachmentStrategy::smart() )
00723     actionName = "view_attachments_smart";
00724   else if ( as == AttachmentStrategy::inlined() )
00725     actionName = "view_attachments_inline";
00726   else if ( as == AttachmentStrategy::hidden() )
00727     actionName = "view_attachments_hide";
00728 
00729   if ( actionName )
00730     return static_cast<KRadioAction*>(mActionCollection->action(actionName));
00731   else
00732     return 0;
00733 }
00734 
00735 void KMReaderWin::slotEnterpriseHeaders() {
00736   setHeaderStyleAndStrategy( HeaderStyle::enterprise(),
00737                              HeaderStrategy::rich() );
00738 }
00739 
00740 void KMReaderWin::slotFancyHeaders() {
00741   setHeaderStyleAndStrategy( HeaderStyle::fancy(),
00742                              HeaderStrategy::rich() );
00743 }
00744 
00745 void KMReaderWin::slotBriefHeaders() {
00746   setHeaderStyleAndStrategy( HeaderStyle::brief(),
00747                              HeaderStrategy::brief() );
00748 }
00749 
00750 void KMReaderWin::slotStandardHeaders() {
00751   setHeaderStyleAndStrategy( HeaderStyle::plain(),
00752                              HeaderStrategy::standard());
00753 }
00754 
00755 void KMReaderWin::slotLongHeaders() {
00756   setHeaderStyleAndStrategy( HeaderStyle::plain(),
00757                              HeaderStrategy::rich() );
00758 }
00759 
00760 void KMReaderWin::slotAllHeaders() {
00761   setHeaderStyleAndStrategy( HeaderStyle::plain(),
00762                              HeaderStrategy::all() );
00763 }
00764 
00765 void KMReaderWin::slotLevelQuote( int l )
00766 {
00767   kdDebug( 5006 ) << "Old Level: " << mLevelQuote << " New Level: " << l << endl;
00768 
00769   mLevelQuote = l;
00770   saveRelativePosition();
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,
01465       qRound( scrollview->contentsHeight() * mSavedRelativePosition ) );
01466     mSavedRelativePosition = 0;
01467   }
01468 }
01469 
01470 //-----------------------------------------------------------------------------
01471 int KMReaderWin::pointsToPixel(int pointSize) const
01472 {
01473   const QPaintDeviceMetrics pdm(mViewer->view());
01474 
01475   return (pointSize * pdm.logicalDpiY() + 36) / 72;
01476 }
01477 
01478 //-----------------------------------------------------------------------------
01479 void KMReaderWin::showHideMimeTree( bool isPlainTextTopLevel ) {
01480   if ( mMimeTreeMode == 2 ||
01481        ( mMimeTreeMode == 1 && !isPlainTextTopLevel ) )
01482     mMimePartTree->show();
01483   else {
01484     // don't rely on QSplitter maintaining sizes for hidden widgets:
01485     KConfigGroup reader( KMKernel::config(), "Reader" );
01486     saveSplitterSizes( reader );
01487     mMimePartTree->hide();
01488   }
01489 }
01490 
01491 void KMReaderWin::displayMessage() {
01492   KMMessage * msg = message();
01493 
01494   mMimePartTree->clear();
01495   showHideMimeTree( !msg || // treat no message as "text/plain"
01496             ( msg->type() == DwMime::kTypeText
01497               && msg->subtype() == DwMime::kSubtypePlain ) );
01498 
01499   if ( !msg )
01500     return;
01501 
01502   msg->setOverrideCodec( overrideCodec() );
01503 
01504   htmlWriter()->begin( mCSSHelper->cssDefinitions( isFixedFont() ) );
01505   htmlWriter()->queue( mCSSHelper->htmlHead( isFixedFont() ) );
01506 
01507   if (!parent())
01508     setCaption(msg->subject());
01509 
01510   removeTempFiles();
01511 
01512   mColorBar->setNeutralMode();
01513 
01514   parseMsg(msg);
01515 
01516   if( mColorBar->isNeutral() )
01517     mColorBar->setNormalMode();
01518 
01519   htmlWriter()->queue("</body></html>");
01520   htmlWriter()->flush();
01521 
01522   QTimer::singleShot( 1, this, SLOT(injectAttachments()) );
01523 }
01524 
01525 
01526 //-----------------------------------------------------------------------------
01527 void KMReaderWin::parseMsg(KMMessage* aMsg)
01528 {
01529 #ifndef NDEBUG
01530   kdDebug( 5006 )
01531     << "parseMsg(KMMessage* aMsg "
01532     << ( aMsg == message() ? "==" : "!=" )
01533     << " aMsg )" << endl;
01534 #endif
01535 
01536   KMMessagePart msgPart;
01537   QCString subtype, contDisp;
01538   QByteArray str;
01539 
01540   assert(aMsg!=0);
01541 
01542   aMsg->setIsBeingParsed( true );
01543 
01544   if ( mRootNode && !mRootNode->processed() )
01545   {
01546     kdWarning() << "The root node is not yet processed! Danger!\n";
01547     return;
01548   } else
01549     delete mRootNode;
01550   mRootNode = partNode::fromMessage( aMsg );
01551   const QCString mainCntTypeStr = mRootNode->typeString() + '/' + mRootNode->subTypeString();
01552 
01553   QString cntDesc = aMsg->subject();
01554   if( cntDesc.isEmpty() )
01555     cntDesc = i18n("( body part )");
01556   KIO::filesize_t cntSize = aMsg->msgSize();
01557   QString cntEnc;
01558   if( aMsg->contentTransferEncodingStr().isEmpty() )
01559     cntEnc = "7bit";
01560   else
01561     cntEnc = aMsg->contentTransferEncodingStr();
01562 
01563   // fill the MIME part tree viewer
01564   mRootNode->fillMimePartTree( 0,
01565                    mMimePartTree,
01566                    cntDesc,
01567                    mainCntTypeStr,
01568                    cntEnc,
01569                    cntSize );
01570 
01571   partNode* vCardNode = mRootNode->findType( DwMime::kTypeText, DwMime::kSubtypeXVCard );
01572   bool hasVCard = false;
01573   if( vCardNode ) {
01574     // ### FIXME: We should only do this if the vCard belongs to the sender,
01575     // ### i.e. if the sender's email address is contained in the vCard.
01576     const QString vcard = vCardNode->msgPart().bodyToUnicode( overrideCodec() );
01577     KABC::VCardConverter t;
01578     if ( !t.parseVCards( vcard ).empty() ) {
01579       hasVCard = true;
01580       kdDebug(5006) << "FOUND A VALID VCARD" << endl;
01581       writeMessagePartToTempFile( &vCardNode->msgPart(), vCardNode->nodeId() );
01582     }
01583   }
01584   htmlWriter()->queue( writeMsgHeader(aMsg, hasVCard, true ) );
01585 
01586   // show message content
01587   ObjectTreeParser otp( this );
01588   otp.parseObjectTree( mRootNode );
01589 
01590   // store encrypted/signed status information in the KMMessage
01591   //  - this can only be done *after* calling parseObjectTree()
01592   KMMsgEncryptionState encryptionState = mRootNode->overallEncryptionState();
01593   KMMsgSignatureState  signatureState  = mRootNode->overallSignatureState();
01594   aMsg->setEncryptionState( encryptionState );
01595   // Don't reset the signature state to "not signed" (e.g. if one canceled the
01596   // decryption of a signed messages which has already been decrypted before).
01597   if ( signatureState != KMMsgNotSigned ||
01598        aMsg->signatureState() == KMMsgSignatureStateUnknown ) {
01599     aMsg->setSignatureState( signatureState );
01600   }
01601 
01602   bool emitReplaceMsgByUnencryptedVersion = false;
01603   const KConfigGroup reader( KMKernel::config(), "Reader" );
01604   if ( reader.readBoolEntry( "store-displayed-messages-unencrypted", false ) ) {
01605 
01606   // Hack to make sure the S/MIME CryptPlugs follows the strict requirement
01607   // of german government:
01608   // --> All received encrypted messages *must* be stored in unencrypted form
01609   //     after they have been decrypted once the user has read them.
01610   //     ( "Aufhebung der Verschluesselung nach dem Lesen" )
01611   //
01612   // note: Since there is no configuration option for this, we do that for
01613   //       all kinds of encryption now - *not* just for S/MIME.
01614   //       This could be changed in the objectTreeToDecryptedMsg() function
01615   //       by deciding when (or when not, resp.) to set the 'dataNode' to
01616   //       something different than 'curNode'.
01617 
01618 
01619 kdDebug(5006) << "\n\n\nKMReaderWin::parseMsg()  -  special post-encryption handling:\n1." << endl;
01620 kdDebug(5006) << "(aMsg == msg) = "                               << (aMsg == message()) << endl;
01621 kdDebug(5006) << "   (KMMsgStatusUnknown == mLastStatus) = "           << (KMMsgStatusUnknown == mLastStatus) << endl;
01622 kdDebug(5006) << "|| (KMMsgStatusNew     == mLastStatus) = "           << (KMMsgStatusNew     == mLastStatus) << endl;
01623 kdDebug(5006) << "|| (KMMsgStatusUnread  == mLastStatus) = "           << (KMMsgStatusUnread  == mLastStatus) << endl;
01624 kdDebug(5006) << "(mIdOfLastViewedMessage != aMsg->msgId()) = "    << (mIdOfLastViewedMessage != aMsg->msgId()) << endl;
01625 kdDebug(5006) << "   (KMMsgFullyEncrypted == encryptionState) = "     << (KMMsgFullyEncrypted == encryptionState) << endl;
01626 kdDebug(5006) << "|| (KMMsgPartiallyEncrypted == encryptionState) = " << (KMMsgPartiallyEncrypted == encryptionState) << endl;
01627          // only proceed if we were called the normal way - not by
01628          // double click on the message (==not running in a separate window)
01629   if(    (aMsg == message())
01630          // only proceed if this message was not saved encryptedly before
01631          // to make sure only *new* messages are saved in decrypted form
01632       && (    (KMMsgStatusUnknown == mLastStatus)
01633            || (KMMsgStatusNew     == mLastStatus)
01634            || (KMMsgStatusUnread  == mLastStatus) )
01635          // avoid endless recursions
01636       && (mIdOfLastViewedMessage != aMsg->msgId())
01637          // only proceed if this message is (at least partially) encrypted
01638       && (    (KMMsgFullyEncrypted == encryptionState)
01639            || (KMMsgPartiallyEncrypted == encryptionState) ) ) {
01640 
01641 kdDebug(5006) << "KMReaderWin  -  calling objectTreeToDecryptedMsg()" << endl;
01642 
01643     NewByteArray decryptedData;
01644     // note: The following call may change the message's headers.
01645     objectTreeToDecryptedMsg( mRootNode, decryptedData, *aMsg );
01646     // add a \0 to the data
01647     decryptedData.appendNULL();
01648     QCString resultString( decryptedData.data() );
01649 kdDebug(5006) << "KMReaderWin  -  resulting data:" << resultString << endl;
01650 
01651     if( !resultString.isEmpty() ) {
01652 kdDebug(5006) << "KMReaderWin  -  composing unencrypted message" << endl;
01653       // try this:
01654       aMsg->setBody( resultString );
01655       KMMessage* unencryptedMessage = new KMMessage( *aMsg );
01656       unencryptedMessage->setParent( 0 );
01657       // because this did not work:
01658       /*
01659       DwMessage dwMsg( aMsg->asDwString() );
01660       dwMsg.Body() = DwBody( DwString( resultString.data() ) );
01661       dwMsg.Body().Parse();
01662       KMMessage* unencryptedMessage = new KMMessage( &dwMsg );
01663       */
01664       //kdDebug(5006) << "KMReaderWin  -  resulting message:" << unencryptedMessage->asString() << endl;
01665       kdDebug(5006) << "KMReaderWin  -  attach unencrypted message to aMsg" << endl;
01666       aMsg->setUnencryptedMsg( unencryptedMessage );
01667       emitReplaceMsgByUnencryptedVersion = true;
01668     }
01669   }
01670   }
01671 
01672   // save current main Content-Type before deleting mRootNode
01673   const int rootNodeCntType = mRootNode ? mRootNode->type() : DwMime::kTypeText;
01674   const int rootNodeCntSubtype = mRootNode ? mRootNode->subType() : DwMime::kSubtypePlain;
01675 
01676   // store message id to avoid endless recursions
01677   setIdOfLastViewedMessage( aMsg->msgId() );
01678 
01679   if( emitReplaceMsgByUnencryptedVersion ) {
01680     kdDebug(5006) << "KMReaderWin  -  invoce saving in decrypted form:" << endl;
01681     emit replaceMsgByUnencryptedVersion();
01682   } else {
01683     kdDebug(5006) << "KMReaderWin  -  finished parsing and displaying of message." << endl;
01684     showHideMimeTree( rootNodeCntType == DwMime::kTypeText &&
01685               rootNodeCntSubtype == DwMime::kSubtypePlain );
01686   }
01687 
01688   aMsg->setIsBeingParsed( false );
01689 }
01690 
01691 
01692 //-----------------------------------------------------------------------------
01693 QString KMReaderWin::writeMsgHeader(KMMessage* aMsg, bool hasVCard, bool topLevel)
01694 {
01695   kdFatal( !headerStyle(), 5006 )
01696     << "trying to writeMsgHeader() without a header style set!" << endl;
01697   kdFatal( !headerStrategy(), 5006 )
01698     << "trying to writeMsgHeader() without a header strategy set!" << endl;
01699   QString href;
01700   if (hasVCard)
01701     href = QString("file:") + KURL::encode_string( mTempFiles.last() );
01702 
01703   return headerStyle()->format( aMsg, headerStrategy(), href, mPrinting, topLevel );
01704 }
01705 
01706 
01707 
01708 //-----------------------------------------------------------------------------
01709 QString KMReaderWin::writeMessagePartToTempFile( KMMessagePart* aMsgPart,
01710                                                  int aPartNum )
01711 {
01712   QString fileName = aMsgPart->fileName();
01713   if( fileName.isEmpty() )
01714     fileName = aMsgPart->name();
01715 
01716   //--- Sven's save attachments to /tmp start ---
01717   QString fname = createTempDir( QString::number( aPartNum ) );
01718   if ( fname.isEmpty() )
01719     return QString();
01720 
01721   // strip off a leading path
01722   int slashPos = fileName.findRev( '/' );
01723   if( -1 != slashPos )
01724     fileName = fileName.mid( slashPos + 1 );
01725   if( fileName.isEmpty() )
01726     fileName = "unnamed";
01727   fname += "/" + fileName;
01728 
01729   QByteArray data = aMsgPart->bodyDecodedBinary();
01730   size_t size = data.size();
01731   if ( aMsgPart->type() == DwMime::kTypeText && size) {
01732     // convert CRLF to LF before writing text attachments to disk
01733     size = KMail::Util::crlf2lf( data.data(), size );
01734   }
01735   if( !KPIM::kBytesToFile( data.data(), size, fname, false, false, false ) )
01736     return QString::null;
01737 
01738   mTempFiles.append( fname );
01739   // make file read-only so that nobody gets the impression that he might
01740   // edit attached files (cf. bug #52813)
01741   ::chmod( QFile::encodeName( fname ), S_IRUSR );
01742 
01743   return fname;
01744 }
01745 
01746 QString KMReaderWin::createTempDir( const QString &param )
01747 {
01748   KTempFile *tempFile = new KTempFile( QString::null, "." + param );
01749   tempFile->setAutoDelete( true );
01750   QString fname = tempFile->name();
01751   delete tempFile;
01752 
01753   if( ::access( QFile::encodeName( fname ), W_OK ) != 0 )
01754     // Not there or not writable
01755     if( ::mkdir( QFile::encodeName( fname ), 0 ) != 0
01756         || ::chmod( QFile::encodeName( fname ), S_IRWXU ) != 0 )
01757       return QString::null; //failed create
01758 
01759   assert( !fname.isNull() );
01760 
01761   mTempDirs.append( fname );
01762   return fname;
01763 }
01764 
01765 //-----------------------------------------------------------------------------
01766 void KMReaderWin::showVCard( KMMessagePart * msgPart ) {
01767   const QString vCard = msgPart->bodyToUnicode( overrideCodec() );
01768 
01769   VCardViewer *vcv = new VCardViewer(this, vCard, "vCardDialog");
01770   vcv->show();
01771 }
01772 
01773 //-----------------------------------------------------------------------------
01774 void KMReaderWin::printMsg()
01775 {
01776   if (!message()) return;
01777   mViewer->view()->print();
01778 }
01779 
01780 
01781 //-----------------------------------------------------------------------------
01782 int KMReaderWin::msgPartFromUrl(const KURL &aUrl)
01783 {
01784   if (aUrl.isEmpty()) return -1;
01785 
01786   bool ok;
01787   if ( aUrl.url().startsWith( "#att" ) ) {
01788     int res = aUrl.url().mid( 4 ).toInt( &ok );
01789     if ( ok ) return res;
01790   }
01791 
01792   if (!aUrl.isLocalFile()) return -1;
01793 
01794   QString path = aUrl.path();
01795   uint right = path.findRev('/');
01796   uint left = path.findRev('.', right);
01797 
01798   int res = path.mid(left + 1, right - left - 1).toInt(&ok);
01799   return (ok) ? res : -1;
01800 }
01801 
01802 
01803 //-----------------------------------------------------------------------------
01804 void KMReaderWin::resizeEvent(QResizeEvent *)
01805 {
01806   if( !mResizeTimer.isActive() )
01807   {
01808     //
01809     // Combine all resize operations that are requested as long a
01810     // the timer runs.
01811     //
01812     mResizeTimer.start( 100, true );
01813   }
01814 }
01815 
01816 
01817 //-----------------------------------------------------------------------------
01818 void KMReaderWin::slotDelayedResize()
01819 {
01820   mSplitter->setGeometry(0, 0, width(), height());
01821 }
01822 
01823 
01824 //-----------------------------------------------------------------------------
01825 void KMReaderWin::slotTouchMessage()
01826 {
01827   if ( !message() )
01828     return;
01829 
01830   if ( !message()->isNew() && !message()->isUnread() )
01831     return;
01832 
01833   SerNumList serNums;
01834   serNums.append( message()->getMsgSerNum() );
01835   KMCommand *command = new KMSetStatusCommand( KMMsgStatusRead, serNums );
01836   command->start();
01837 
01838   // should we send an MDN?
01839   if ( mNoMDNsWhenEncrypted &&
01840        message()->encryptionState() != KMMsgNotEncrypted &&
01841        message()->encryptionState() != KMMsgEncryptionStateUnknown )
01842     return;
01843 
01844   KMFolder *folder = message()->parent();
01845   if (folder &&
01846      (folder->isOutbox() || folder->isSent() || folder->isTrash() ||
01847       folder->isDrafts() || folder->isTemplates() ) )
01848     return;
01849 
01850   if ( KMMessage * receipt = message()->createMDN( MDN::ManualAction,
01851                            MDN::Displayed,
01852                            true /* allow GUI */ ) )
01853     if ( !kmkernel->msgSender()->send( receipt ) ) // send or queue
01854       KMessageBox::error( this, i18n("Could not send MDN.") );
01855 }
01856 
01857 
01858 //-----------------------------------------------------------------------------
01859 void KMReaderWin::closeEvent(QCloseEvent *e)
01860 {
01861   QWidget::closeEvent(e);
01862   writeConfig();
01863 }
01864 
01865 
01866 bool foundSMIMEData( const QString aUrl,
01867                      QString& displayName,
01868                      QString& libName,
01869                      QString& keyId )
01870 {
01871   static QString showCertMan("showCertificate#");
01872   displayName = "";
01873   libName = "";
01874   keyId = "";
01875   int i1 = aUrl.find( showCertMan );
01876   if( -1 < i1 ) {
01877     i1 += showCertMan.length();
01878     int i2 = aUrl.find(" ### ", i1);
01879     if( i1 < i2 )
01880     {
01881       displayName = aUrl.mid( i1, i2-i1 );
01882       i1 = i2+5;
01883       i2 = aUrl.find(" ### ", i1);
01884       if( i1 < i2 )
01885       {
01886         libName = aUrl.mid( i1, i2-i1 );
01887         i2 += 5;
01888 
01889         keyId = aUrl.mid( i2 );
01890         /*
01891         int len = aUrl.length();
01892         if( len > i2+1 ) {
01893           keyId = aUrl.mid( i2, 2 );
01894           i2 += 2;
01895           while( len > i2+1 ) {
01896             keyId += ':';
01897             keyId += aUrl.mid( i2, 2 );
01898             i2 += 2;
01899           }
01900         }
01901         */
01902       }
01903     }
01904   }
01905   return !keyId.isEmpty();
01906 }
01907 
01908 
01909 //-----------------------------------------------------------------------------
01910 void KMReaderWin::slotUrlOn(const QString &aUrl)
01911 {
01912   const KURL url(aUrl);
01913   if ( url.protocol() == "kmail" || url.protocol() == "x-kmail"
01914        || (url.protocol().isEmpty() && url.path().isEmpty()) ) {
01915     mViewer->setDNDEnabled( false );
01916   } else {
01917     mViewer->setDNDEnabled( true );
01918   }
01919 
01920   if ( aUrl.stripWhiteSpace().isEmpty() ) {
01921     KPIM::BroadcastStatus::instance()->reset();
01922     return;
01923   }
01924 
01925   mUrlClicked = url;
01926 
01927   const QString msg = URLHandlerManager::instance()->statusBarMessage( url, this );
01928 
01929   kdWarning( msg.isEmpty(), 5006 ) << "KMReaderWin::slotUrlOn(): Unhandled URL hover!" << endl;
01930   KPIM::BroadcastStatus::instance()->setTransientStatusMsg( msg );
01931 }
01932 
01933 
01934 //-----------------------------------------------------------------------------
01935 void KMReaderWin::slotUrlOpen(const KURL &aUrl, const KParts::URLArgs &)
01936 {
01937   mUrlClicked = aUrl;
01938 
01939   if ( URLHandlerManager::instance()->handleClick( aUrl, this ) )
01940     return;
01941 
01942   kdWarning( 5006 ) << "KMReaderWin::slotOpenUrl(): Unhandled URL click!" << endl;
01943   emit urlClicked( aUrl, Qt::LeftButton );
01944 }
01945 
01946 //-----------------------------------------------------------------------------
01947 void KMReaderWin::slotUrlPopup(const QString &aUrl, const QPoint& aPos)
01948 {
01949   const KURL url( aUrl );
01950   mUrlClicked = url;
01951 
01952   if ( URLHandlerManager::instance()->handleContextMenuRequest( url, aPos, this ) )
01953     return;
01954 
01955   if ( message() ) {
01956     kdWarning( 5006 ) << "KMReaderWin::slotUrlPopup(): Unhandled URL right-click!" << endl;
01957     emit popupMenu( *message(), url, aPos );
01958   }
01959 }
01960 
01961 //-----------------------------------------------------------------------------
01962 void KMReaderWin::showAttachmentPopup( int id, const QString & name, const QPoint & p )
01963 {
01964   mAtmCurrent = id;
01965   mAtmCurrentName = name;
01966   KPopupMenu *menu = new KPopupMenu();
01967   menu->insertItem(SmallIcon("fileopen"),i18n("to open", "Open"), 1);
01968   menu->insertItem(i18n("Open With..."), 2);
01969   menu->insertItem(i18n("to view something", "View"), 3);
01970   menu->insertItem(SmallIcon("filesaveas"),i18n("Save As..."), 4);
01971   menu->insertItem(SmallIcon("editcopy"), i18n("Copy"), 9 );
01972   if ( GlobalSettings::self()->allowAttachmentEditing() )
01973     menu->insertItem(SmallIcon("edit"), i18n("Edit Attachment"), 8 );
01974   if ( GlobalSettings::self()->allowAttachmentDeletion() )
01975     menu->insertItem(SmallIcon("editdelete"), i18n("Delete Attachment"), 7 );
01976   if ( name.endsWith( ".xia", false ) &&
01977        Kleo::CryptoBackendFactory::instance()->protocol( "Chiasmus" ) )
01978     menu->insertItem( i18n( "Decrypt With Chiasmus..." ), 6 );
01979   menu->insertItem(i18n("Properties"), 5);
01980   connect(menu, SIGNAL(activated(int)), this, SLOT(slotHandleAttachment(int)));
01981   menu->exec( p ,0 );
01982   delete menu;
01983 }
01984 
01985 //-----------------------------------------------------------------------------
01986 void KMReaderWin::setStyleDependantFrameWidth()
01987 {
01988   if ( !mBox )
01989     return;
01990   // set the width of the frame to a reasonable value for the current GUI style
01991   int frameWidth;
01992   if( style().isA("KeramikStyle") )
01993     frameWidth = style().pixelMetric( QStyle::PM_DefaultFrameWidth ) - 1;
01994   else
01995     frameWidth = style().pixelMetric( QStyle::PM_DefaultFrameWidth );
01996   if ( frameWidth < 0 )
01997     frameWidth = 0;
01998   if ( frameWidth != mBox->lineWidth() )
01999     mBox->setLineWidth( frameWidth );
02000 }
02001 
02002 //-----------------------------------------------------------------------------
02003 void KMReaderWin::styleChange( QStyle& oldStyle )
02004 {
02005   setStyleDependantFrameWidth();
02006   QWidget::styleChange( oldStyle );
02007 }
02008 
02009 //-----------------------------------------------------------------------------
02010 void KMReaderWin::slotHandleAttachment( int choice )
02011 {
02012   mAtmUpdate = true;
02013   partNode* node = mRootNode ? mRootNode->findId( mAtmCurrent ) : 0;
02014   if ( mAtmCurrentName.isEmpty() && node )
02015     mAtmCurrentName = tempFileUrlFromPartNode( node ).path();
02016   if ( choice < 7 ) {
02017   KMHandleAttachmentCommand* command = new KMHandleAttachmentCommand(
02018       node, message(), mAtmCurrent, mAtmCurrentName,
02019       KMHandleAttachmentCommand::AttachmentAction( choice ), 0, this );
02020   connect( command, SIGNAL( showAttachment( int, const QString& ) ),
02021       this, SLOT( slotAtmView( int, const QString& ) ) );
02022   command->start();
02023   } else if ( choice == 7 ) {
02024     slotDeleteAttachment( node );
02025   } else if ( choice == 8 ) {
02026     slotEditAttachment( node );
02027   } else if ( choice == 9 ) {
02028     if ( !node ) return;
02029     KURL::List urls;
02030     KURL url = tempFileUrlFromPartNode( node );
02031     if (!url.isValid() ) return;
02032     urls.append( url );
02033     KURLDrag* drag = new KURLDrag( urls, this );
02034     QApplication::clipboard()->setData( drag, QClipboard::Clipboard );
02035   }
02036 }
02037 
02038 //-----------------------------------------------------------------------------
02039 void KMReaderWin::slotFind()
02040 {
02041   mViewer->findText();
02042 }
02043 
02044 //-----------------------------------------------------------------------------
02045 void KMReaderWin::slotFindNext()
02046 {
02047   mViewer->findTextNext();
02048 }
02049 
02050 //-----------------------------------------------------------------------------
02051 void KMReaderWin::slotToggleFixedFont()
02052 {
02053   mUseFixedFont = !mUseFixedFont;
02054   saveRelativePosition();
02055   update(true);
02056 }
02057 
02058 
02059 //-----------------------------------------------------------------------------
02060 void KMReaderWin::slotCopySelectedText()
02061 {
02062   kapp->clipboard()->setText( mViewer->selectedText() );
02063 }
02064 
02065 
02066 //-----------------------------------------------------------------------------
02067 void KMReaderWin::atmViewMsg(KMMessagePart* aMsgPart)
02068 {
02069   assert(aMsgPart!=0);
02070   KMMessage* msg = new KMMessage;
02071   msg->fromString(aMsgPart->bodyDecoded());
02072   assert(msg != 0);
02073   msg->setMsgSerNum( 0 ); // because lookups will fail
02074   // some information that is needed for imap messages with LOD
02075   msg->setParent( message()->parent() );
02076   msg->setUID(message()->UID());
02077   msg->setReadyToShow(true);
02078   KMReaderMainWin *win = new KMReaderMainWin();
02079   win->showMsg( overrideEncoding(), msg );
02080   win->show();
02081 }
02082 
02083 
02084 void KMReaderWin::setMsgPart( partNode * node ) {
02085   htmlWriter()->reset();
02086   mColorBar->hide();
02087   htmlWriter()->begin( mCSSHelper->cssDefinitions( isFixedFont() ) );
02088   htmlWriter()->write( mCSSHelper->htmlHead( isFixedFont() ) );
02089   // end ###
02090   if ( node ) {
02091     ObjectTreeParser otp( this, 0, true );
02092     otp.parseObjectTree( node );
02093   }
02094   // ### this, too
02095   htmlWriter()->queue( "</body></html>" );
02096   htmlWriter()->flush();
02097 }
02098 
02099 //-----------------------------------------------------------------------------
02100 void KMReaderWin::setMsgPart( KMMessagePart* aMsgPart, bool aHTML,
02101                   const QString& aFileName, const QString& pname )
02102 {
02103   KCursorSaver busy(KBusyPtr::busy());
02104   if (kasciistricmp(aMsgPart->typeStr(), "message")==0) {
02105       // if called from compose win
02106       KMMessage* msg = new KMMessage;
02107       assert(aMsgPart!=0);
02108       msg->fromString(aMsgPart->bodyDecoded());
02109       mMainWindow->setCaption(msg->subject());
02110       setMsg(msg, true);
02111       setAutoDelete(true);
02112   } else if (kasciistricmp(aMsgPart->typeStr(), "text")==0) {
02113       if (kasciistricmp(aMsgPart->subtypeStr(), "x-vcard") == 0) {
02114         showVCard( aMsgPart );
02115     return;
02116       }
02117       htmlWriter()->begin( mCSSHelper->cssDefinitions( isFixedFont() ) );
02118       htmlWriter()->queue( mCSSHelper->htmlHead( isFixedFont() ) );
02119 
02120       if (aHTML && (kasciistricmp(aMsgPart->subtypeStr(), "html")==0)) { // HTML
02121         // ### this is broken. It doesn't stip off the HTML header and footer!
02122         htmlWriter()->queue( aMsgPart->bodyToUnicode( overrideCodec() ) );
02123         mColorBar->setHtmlMode();
02124       } else { // plain text
02125         const QCString str = aMsgPart->bodyDecoded();
02126         ObjectTreeParser otp( this );
02127         otp.writeBodyStr( str,
02128                           overrideCodec() ? overrideCodec() : aMsgPart->codec(),
02129                           message() ? message()->from() : QString::null );
02130       }
02131       htmlWriter()->queue("</body></html>");
02132       htmlWriter()->flush();
02133       mMainWindow->setCaption(i18n("View Attachment: %1").arg(pname));
02134   } else if (kasciistricmp(aMsgPart->typeStr(), "image")==0 ||
02135              (kasciistricmp(aMsgPart->typeStr(), "application")==0 &&
02136               kasciistricmp(aMsgPart->subtypeStr(), "postscript")==0))
02137   {
02138       if (aFileName.isEmpty()) return;  // prevent crash
02139       // Open the window with a size so the image fits in (if possible):
02140       QImageIO *iio = new QImageIO();
02141       iio->setFileName(aFileName);
02142       if( iio->read() ) {
02143           QImage img = iio->image();
02144           QRect desk = KGlobalSettings::desktopGeometry(mMainWindow);
02145           // determine a reasonable window size
02146           int width, height;
02147           if( img.width() < 50 )
02148               width = 70;
02149           else if( img.width()+20 < desk.width() )
02150               width = img.width()+20;
02151           else
02152               width = desk.width();
02153           if( img.height() < 50 )
02154               height = 70;
02155           else if( img.height()+20 < desk.height() )
02156               height = img.height()+20;
02157           else
02158               height = desk.height();
02159           mMainWindow->resize( width, height );
02160       }
02161       // Just write the img tag to HTML:
02162       htmlWriter()->begin( mCSSHelper->cssDefinitions( isFixedFont() ) );
02163       htmlWriter()->write( mCSSHelper->htmlHead( isFixedFont() ) );
02164       htmlWriter()->write( "<img src=\"file:" +
02165                            KURL::encode_string( aFileName ) +
02166                            "\" border=\"0\">\n"
02167                            "</body></html>\n" );
02168       htmlWriter()->end();
02169       setCaption( i18n("View Attachment: %1").arg( pname ) );
02170       show();
02171   } else {
02172     htmlWriter()->begin( mCSSHelper->cssDefinitions( isFixedFont() ) );
02173     htmlWriter()->queue( mCSSHelper->htmlHead( isFixedFont() ) );
02174     htmlWriter()->queue( "<pre>" );
02175 
02176     QString str = aMsgPart->bodyDecoded();
02177     // A QString cannot handle binary data. So if it's shorter than the
02178     // attachment, we assume the attachment is binary:
02179     if( str.length() < (unsigned) aMsgPart->decodedSize() ) {
02180       str.prepend( i18n("[KMail: Attachment contains binary data. Trying to show first character.]",
02181           "[KMail: Attachment contains binary data. Trying to show first %n characters.]",
02182           str.length()) + QChar('\n') );
02183     }
02184     htmlWriter()->queue( QStyleSheet::escape( str ) );
02185     htmlWriter()->queue( "</pre>" );
02186     htmlWriter()->queue("</body></html>");
02187     htmlWriter()->flush();
02188     mMainWindow->setCaption(i18n("View Attachment: %1").arg(pname));
02189   }
02190   // ---Sven's view text, html and image attachments in html widget end ---
02191 }
02192 
02193 
02194 //-----------------------------------------------------------------------------
02195 void KMReaderWin::slotAtmView( int id, const QString& name )
02196 {
02197   partNode* node = mRootNode ? mRootNode->findId( id ) : 0;
02198   if( node ) {
02199     mAtmCurrent = id;
02200     mAtmCurrentName = name;
02201     if ( mAtmCurrentName.isEmpty() )
02202       mAtmCurrentName = tempFileUrlFromPartNode( node ).path();
02203 
02204     KMMessagePart& msgPart = node->msgPart();
02205     QString pname = msgPart.fileName();
02206     if (pname.isEmpty()) pname=msgPart.name();
02207     if (pname.isEmpty()) pname=msgPart.contentDescription();
02208     if (pname.isEmpty()) pname="unnamed";
02209     // image Attachment is saved already
02210     if (kasciistricmp(msgPart.typeStr(), "message")==0) {
02211       atmViewMsg(&msgPart);
02212     } else if ((kasciistricmp(msgPart.typeStr(), "text")==0) &&
02213            (kasciistricmp(msgPart.subtypeStr(), "x-vcard")==0)) {
02214       setMsgPart( &msgPart, htmlMail(), name, pname );
02215     } else {
02216       KMReaderMainWin *win = new KMReaderMainWin(&msgPart, htmlMail(),
02217           name, pname, overrideEncoding() );
02218       win->show();
02219     }
02220   }
02221 }
02222 
02223 //-----------------------------------------------------------------------------
02224 void KMReaderWin::openAttachment( int id, const QString & name )
02225 {
02226   mAtmCurrentName = name;
02227   mAtmCurrent = id;
02228 
02229   QString str, pname, cmd, fileName;
02230 
02231   partNode* node = mRootNode ? mRootNode->findId( id ) : 0;
02232   if( !node ) {
02233     kdWarning(5006) << "KMReaderWin::openAttachment - could not find node " << id << endl;
02234     return;
02235   }
02236   if ( mAtmCurrentName.isEmpty() )
02237     mAtmCurrentName = tempFileUrlFromPartNode( node ).path();
02238 
02239   KMMessagePart& msgPart = node->msgPart();
02240   if (kasciistricmp(msgPart.typeStr(), "message")==0)
02241   {
02242     atmViewMsg(&msgPart);
02243     return;
02244   }
02245 
02246   QCString contentTypeStr( msgPart.typeStr() + '/' + msgPart.subtypeStr() );
02247   KPIM::kAsciiToLower( contentTypeStr.data() );
02248 
02249   if ( qstrcmp( contentTypeStr, "text/x-vcard" ) == 0 ) {
02250     showVCard( &msgPart );
02251     return;
02252   }
02253 
02254   // determine the MIME type of the attachment
02255   KMimeType::Ptr mimetype;
02256   // prefer the value of the Content-Type header
02257   mimetype = KMimeType::mimeType( QString::fromLatin1( contentTypeStr ) );
02258   if ( mimetype->name() == "application/octet-stream" ) {
02259     // consider the filename if Content-Type is application/octet-stream
02260     mimetype = KMimeType::findByPath( name, 0, true /* no disk access */ );
02261   }
02262   if ( ( mimetype->name() == "application/octet-stream" )
02263        && msgPart.isComplete() ) {
02264     // consider the attachment's contents if neither the Content-Type header
02265     // nor the filename give us a clue
02266     mimetype = KMimeType::findByFileContent( name );
02267   }
02268 
02269   KService::Ptr offer =
02270     KServiceTypeProfile::preferredService( mimetype->name(), "Application" );
02271 
02272   QString open_text;
02273   QString filenameText = msgPart.fileName();
02274   if ( filenameText.isEmpty() )
02275     filenameText = msgPart.name();
02276   if ( offer ) {
02277     open_text = i18n("&Open with '%1'").arg( offer->name() );
02278   } else {
02279     open_text = i18n("&Open With...");
02280   }
02281   const QString text = i18n("Open attachment '%1'?\n"
02282                             "Note that opening an attachment may compromise "
02283                             "your system's security.")
02284                        .arg( filenameText );
02285   const int choice = KMessageBox::questionYesNoCancel( this, text,
02286       i18n("Open Attachment?"), KStdGuiItem::saveAs(), open_text,
02287       QString::fromLatin1("askSave") + mimetype->name() ); // dontAskAgainName
02288 
02289   if( choice == KMessageBox::Yes ) {        // Save
02290     mAtmUpdate = true;
02291     KMHandleAttachmentCommand* command = new KMHandleAttachmentCommand( node,
02292         message(), mAtmCurrent, mAtmCurrentName, KMHandleAttachmentCommand::Save,
02293         offer, this );
02294     connect( command, SIGNAL( showAttachment( int, const QString& ) ),
02295         this, SLOT( slotAtmView( int, const QString& ) ) );
02296     command->start();
02297   }
02298   else if( choice == KMessageBox::No ) {    // Open
02299     KMHandleAttachmentCommand::AttachmentAction action = ( offer ?
02300         KMHandleAttachmentCommand::Open : KMHandleAttachmentCommand::OpenWith );
02301     mAtmUpdate = true;
02302     KMHandleAttachmentCommand* command = new KMHandleAttachmentCommand( node,
02303         message(), mAtmCurrent, mAtmCurrentName, action, offer, this );
02304     connect( command, SIGNAL( showAttachment( int, const QString& ) ),
02305         this, SLOT( slotAtmView( int, const QString& ) ) );
02306     command->start();
02307   } else {                  // Cancel
02308     kdDebug(5006) << "Canceled opening attachment" << endl;
02309   }
02310 }
02311 
02312 //-----------------------------------------------------------------------------
02313 void KMReaderWin::slotScrollUp()
02314 {
02315   static_cast<QScrollView *>(mViewer->widget())->scrollBy(0, -10);
02316 }
02317 
02318 
02319 //-----------------------------------------------------------------------------
02320 void KMReaderWin::slotScrollDown()
02321 {
02322   static_cast<QScrollView *>(mViewer->widget())->scrollBy(0, 10);
02323 }
02324 
02325 bool KMReaderWin::atBottom() const
02326 {
02327     const QScrollView *view = static_cast<const QScrollView *>(mViewer->widget());
02328     return view->contentsY() + view->visibleHeight() >= view->contentsHeight();
02329 }
02330 
02331 //-----------------------------------------------------------------------------
02332 void KMReaderWin::slotJumpDown()
02333 {
02334     QScrollView *view = static_cast<QScrollView *>(mViewer->widget());
02335     int offs = (view->clipper()->height() < 30) ? view->clipper()->height() : 30;
02336     view->scrollBy( 0, view->clipper()->height() - offs );
02337 }
02338 
02339 //-----------------------------------------------------------------------------
02340 void KMReaderWin::slotScrollPrior()
02341 {
02342   static_cast<QScrollView *>(mViewer->widget())->scrollBy(0, -(int)(height()*0.8));
02343 }
02344 
02345 
02346 //-----------------------------------------------------------------------------
02347 void KMReaderWin::slotScrollNext()
02348 {
02349   static_cast<QScrollView *>(mViewer->widget())->scrollBy(0, (int)(height()*0.8));
02350 }
02351 
02352 //-----------------------------------------------------------------------------
02353 void KMReaderWin::slotDocumentChanged()
02354 {
02355 
02356 }
02357 
02358 
02359 //-----------------------------------------------------------------------------
02360 void KMReaderWin::slotTextSelected(bool)
02361 {
02362   QString temp = mViewer->selectedText();
02363   kapp->clipboard()->setText(temp);
02364 }
02365 
02366 //-----------------------------------------------------------------------------
02367 void KMReaderWin::selectAll()
02368 {
02369   mViewer->selectAll();
02370 }
02371 
02372 //-----------------------------------------------------------------------------
02373 QString KMReaderWin::copyText()
02374 {
02375   QString temp = mViewer->selectedText();
02376   return temp;
02377 }
02378 
02379 
02380 //-----------------------------------------------------------------------------
02381 void KMReaderWin::slotDocumentDone()
02382 {
02383   // mSbVert->setValue(0);
02384 }
02385 
02386 
02387 //-----------------------------------------------------------------------------
02388 void KMReaderWin::setHtmlOverride(bool override)
02389 {
02390   mHtmlOverride = override;
02391   if (message())
02392       message()->setDecodeHTML(htmlMail());
02393 }
02394 
02395 
02396 //-----------------------------------------------------------------------------
02397 void KMReaderWin::setHtmlLoadExtOverride(bool override)
02398 {
02399   mHtmlLoadExtOverride = override;
02400   //if (message())
02401   //    message()->setDecodeHTML(htmlMail());
02402 }
02403 
02404 
02405 //-----------------------------------------------------------------------------
02406 bool KMReaderWin::htmlMail()
02407 {
02408   return ((mHtmlMail && !mHtmlOverride) || (!mHtmlMail && mHtmlOverride));
02409 }
02410 
02411 
02412 //-----------------------------------------------------------------------------
02413 bool KMReaderWin::htmlLoadExternal()
02414 {
02415   return ((mHtmlLoadExternal && !mHtmlLoadExtOverride) ||
02416           (!mHtmlLoadExternal && mHtmlLoadExtOverride));
02417 }
02418 
02419 
02420 //-----------------------------------------------------------------------------
02421 void KMReaderWin::saveRelativePosition()
02422 {
02423   const QScrollView * scrollview = static_cast<QScrollView *>( mViewer->widget() );
02424   mSavedRelativePosition =
02425     static_cast<float>( scrollview->contentsY() ) / scrollview->contentsHeight();
02426 }
02427 
02428 
02429 //-----------------------------------------------------------------------------
02430 void KMReaderWin::update( bool force )
02431 {
02432   KMMessage* msg = message();
02433   if ( msg )
02434     setMsg( msg, force );
02435 }
02436 
02437 
02438 //-----------------------------------------------------------------------------
02439 KMMessage* KMReaderWin::message( KMFolder** aFolder ) const
02440 {
02441   KMFolder*  tmpFolder;
02442   KMFolder*& folder = aFolder ? *aFolder : tmpFolder;
02443   folder = 0;
02444   if (mMessage)
02445       return mMessage;
02446   if (mLastSerNum) {
02447     KMMessage *message = 0;
02448     int index;
02449     KMMsgDict::instance()->getLocation( mLastSerNum, &folder, &index );
02450     if (folder )
02451       message = folder->getMsg( index );
02452     if (!message)
02453       kdWarning(5006) << "Attempt to reference invalid serial number " << mLastSerNum << "\n" << endl;
02454     return message;
02455   }
02456   return 0;
02457 }
02458 
02459 
02460 
02461 //-----------------------------------------------------------------------------
02462 void KMReaderWin::slotUrlClicked()
02463 {
02464   KMMainWidget *mainWidget = dynamic_cast<KMMainWidget*>(mMainWindow);
02465   uint identity = 0;
02466   if ( message() && message()->parent() ) {
02467     identity = message()->parent()->identity();
02468   }
02469 
02470   KMCommand *command = new KMUrlClickedCommand( mUrlClicked, identity, this,
02471                         false, mainWidget );
02472   command->start();
02473 }
02474 
02475 //-----------------------------------------------------------------------------
02476 void KMReaderWin::slotMailtoCompose()
02477 {
02478   KMCommand *command = new KMMailtoComposeCommand( mUrlClicked, message() );
02479   command->start();
02480 }
02481 
02482 //-----------------------------------------------------------------------------
02483 void KMReaderWin::slotMailtoForward()
02484 {
02485   KMCommand *command = new KMMailtoForwardCommand( mMainWindow, mUrlClicked,
02486                            message() );
02487   command->start();
02488 }
02489 
02490 //-----------------------------------------------------------------------------
02491 void KMReaderWin::slotMailtoAddAddrBook()
02492 {
02493   KMCommand *command = new KMMailtoAddAddrBookCommand( mUrlClicked,
02494                                mMainWindow);
02495   command->start();
02496 }
02497 
02498 //-----------------------------------------------------------------------------
02499 void KMReaderWin::slotMailtoOpenAddrBook()
02500 {
02501   KMCommand *command = new KMMailtoOpenAddrBookCommand( mUrlClicked,
02502                             mMainWindow );
02503   command->start();
02504 }
02505 
02506 //-----------------------------------------------------------------------------
02507 void KMReaderWin::slotUrlCopy()
02508 {
02509   // we don't necessarily need a mainWidget for KMUrlCopyCommand so
02510   // it doesn't matter if the dynamic_cast fails.
02511   KMCommand *command =
02512     new KMUrlCopyCommand( mUrlClicked,
02513                           dynamic_cast<KMMainWidget*>( mMainWindow ) );
02514   command->start();
02515 }
02516 
02517 //-----------------------------------------------------------------------------
02518 void KMReaderWin::slotUrlOpen( const KURL &url )
02519 {
02520   if ( !url.isEmpty() )
02521     mUrlClicked = url;
02522   KMCommand *command = new KMUrlOpenCommand( mUrlClicked, this );
02523   command->start();
02524 }
02525 
02526 //-----------------------------------------------------------------------------
02527 void KMReaderWin::slotAddBookmarks()
02528 {
02529     KMCommand *command = new KMAddBookmarksCommand( mUrlClicked, this );
02530     command->start();
02531 }
02532 
02533 //-----------------------------------------------------------------------------
02534 void KMReaderWin::slotUrlSave()
02535 {
02536   KMCommand *command = new KMUrlSaveCommand( mUrlClicked, mMainWindow );
02537   command->start();
02538 }
02539 
02540 //-----------------------------------------------------------------------------
02541 void KMReaderWin::slotMailtoReply()
02542 {
02543   KMCommand *command = new KMMailtoReplyCommand( mMainWindow, mUrlClicked,
02544     message(), copyText() );
02545   command->start();
02546 }
02547 
02548 //-----------------------------------------------------------------------------
02549 partNode * KMReaderWin::partNodeFromUrl( const KURL & url ) {
02550   return mRootNode ? mRootNode->findId( msgPartFromUrl( url ) ) : 0 ;
02551 }
02552 
02553 partNode * KMReaderWin::partNodeForId( int id ) {
02554   return mRootNode ? mRootNode->findId( id ) : 0 ;
02555 }
02556 
02557 
02558 KURL KMReaderWin::tempFileUrlFromPartNode( const partNode * node )
02559 {
02560   if (!node) return KURL();
02561   QStringList::const_iterator it = mTempFiles.begin();
02562   QStringList::const_iterator end = mTempFiles.end();
02563 
02564   while ( it != end ) {
02565       QString path = *it;
02566       it++;
02567       uint right = path.findRev('/');
02568       uint left = path.findRev('.', right);
02569 
02570       bool ok;
02571       int res = path.mid(left + 1, right - left - 1).toInt(&ok);
02572       if ( res == node->nodeId() )
02573           return KURL( path );
02574   }
02575   return KURL();
02576 }
02577 
02578 //-----------------------------------------------------------------------------
02579 void KMReaderWin::slotSaveAttachments()
02580 {
02581   mAtmUpdate = true;
02582   KMSaveAttachmentsCommand *saveCommand = new KMSaveAttachmentsCommand( mMainWindow,
02583                                                                         message() );
02584   saveCommand->start();
02585 }
02586 
02587 //-----------------------------------------------------------------------------
02588 void KMReaderWin::slotSaveMsg()
02589 {
02590   KMSaveMsgCommand *saveCommand = new KMSaveMsgCommand( mMainWindow, message() );
02591 
02592   if (saveCommand->url().isEmpty())
02593     delete saveCommand;
02594   else
02595     saveCommand->start();
02596 }
02597 //-----------------------------------------------------------------------------
02598 void KMReaderWin::slotIMChat()
02599 {
02600   KMCommand *command = new KMIMChatCommand( mUrlClicked, message() );
02601   command->start();
02602 }
02603 
02604 //-----------------------------------------------------------------------------
02605 bool KMReaderWin::eventFilter( QObject *, QEvent *e )
02606 {
02607   if ( e->type() == QEvent::MouseButtonPress ) {
02608     QMouseEvent* me = static_cast<QMouseEvent*>(e);
02609     if ( me->button() == LeftButton && ( me->state() & ShiftButton ) ) {
02610       // special processing for shift+click
02611       mAtmCurrent = msgPartFromUrl( mUrlClicked );
02612       if ( mAtmCurrent < 0 ) return false; // not an attachment
02613       mAtmCurrentName = mUrlClicked.path();
02614       slotHandleAttachment( KMHandleAttachmentCommand::Save ); // save
02615       return true; // eat event
02616     }
02617   }
02618   // standard event processing
02619   return false;
02620 }
02621 
02622 void KMReaderWin::slotDeleteAttachment(partNode * node)
02623 {
02624   if ( KMessageBox::warningContinueCancel( this,
02625        i18n("Deleting an attachment might invalidate any digital signature on this message."),
02626        i18n("Delete Attachment"), KStdGuiItem::del(), "DeleteAttachmentSignatureWarning" )
02627      != KMessageBox::Continue ) {
02628     return;
02629   }
02630   KMDeleteAttachmentCommand* command = new KMDeleteAttachmentCommand( node, message(), this );
02631   command->start();
02632 }
02633 
02634 void KMReaderWin::slotEditAttachment(partNode * node)
02635 {
02636   if ( KMessageBox::warningContinueCancel( this,
02637         i18n("Modifying an attachment might invalidate any digital signature on this message."),
02638         i18n("Edit Attachment"), KGuiItem( i18n("Edit"), "edit" ), "EditAttachmentSignatureWarning" )
02639         != KMessageBox::Continue ) {
02640     return;
02641   }
02642   KMEditAttachmentCommand* command = new KMEditAttachmentCommand( node, message(), this );
02643   command->start();
02644 }
02645 
02646 KMail::CSSHelper* KMReaderWin::cssHelper()
02647 {
02648   return mCSSHelper;
02649 }
02650 
02651 bool KMReaderWin::decryptMessage() const
02652 {
02653   if ( !GlobalSettings::self()->alwaysDecrypt() )
02654     return mDecrytMessageOverwrite;
02655   return true;
02656 }
02657 
02658 void KMReaderWin::injectAttachments()
02659 {
02660   // inject attachments in header view
02661   // we have to do that after the otp has run so we also see encrypted parts
02662   DOM::Document doc = mViewer->htmlDocument();
02663   DOM::Element injectionPoint = doc.getElementById( "attachmentInjectionPoint" );
02664   if ( injectionPoint.isNull() )
02665     return;
02666 
02667   QString imgpath( locate("data","kmail/pics/") );
02668   QString visibility;
02669   QString urlHandle;
02670   QString imgSrc;
02671   if( !showAttachmentQuicklist() )
02672     {
02673       urlHandle.append( "kmail:showAttachmentQuicklist" );
02674       imgSrc.append( "attachmentQuicklistClosed.png" );
02675     } else {
02676       urlHandle.append( "kmail:hideAttachmentQuicklist" );
02677       imgSrc.append( "attachmentQuicklistOpened.png" );
02678     }
02679 
02680   QString html = renderAttachments( mRootNode, QApplication::palette().active().background() );
02681   if ( html.isEmpty() )
02682     return;
02683 
02684     if ( headerStyle() == HeaderStyle::fancy() )
02685       html.prepend( QString::fromLatin1("<div style=\"float:left;\">%1&nbsp;</div>" ).arg(i18n("Attachments:")) );
02686 
02687     if ( headerStyle() == HeaderStyle::enterprise() ) {
02688       QString link("");
02689       link += "<div style=\"text-align: right;\"><a href=\""+urlHandle+"\"><img src=\""+imgpath+imgSrc+"\"/></a></div>";
02690       html.prepend( link );
02691     }
02692 
02693     assert( injectionPoint.tagName() == "div" );
02694     static_cast<DOM::HTMLElement>( injectionPoint ).setInnerHTML( html );  
02695 }
02696 
02697 static QColor nextColor( const QColor & c )
02698 {
02699   int h, s, v;
02700   c.hsv( &h, &s, &v );
02701   return QColor( (h + 50) % 360, QMAX(s, 64), v, QColor::Hsv );
02702 }
02703 
02704 QString KMReaderWin::renderAttachments(partNode * node, const QColor &bgColor )
02705 {
02706   if ( !node )
02707     return QString();
02708 
02709   QString html;
02710   if ( node->firstChild() ) {
02711     QString subHtml = renderAttachments( node->firstChild(), nextColor( bgColor ) );
02712     if ( !subHtml.isEmpty() ) {
02713 
02714       QString visibility;
02715       if( !showAttachmentQuicklist() )
02716     {
02717       visibility.append( "display:none;" );
02718     }
02719 
02720       QString margin;
02721       if ( node != mRootNode || headerStyle() != HeaderStyle::enterprise() )
02722         margin = "padding:2px; margin:2px; ";
02723       if ( node->msgPart().typeStr() == "message" || node == mRootNode )
02724         html += QString::fromLatin1("<div style=\"background:%1; %2"
02725             "vertical-align:middle; float:left; %3\">").arg( bgColor.name() ).arg( margin ).arg( visibility );
02726       html += subHtml;
02727       if ( node->msgPart().typeStr() == "message" || node == mRootNode )
02728         html += "</div>";
02729     }
02730   } else {
02731     QString label, icon;
02732     icon = node->msgPart().iconName( KIcon::Small );
02733     label = node->msgPart().contentDescription();
02734     if( label.isEmpty() )
02735       label = node->msgPart().name().stripWhiteSpace();
02736     if( label.isEmpty() )
02737       label = node->msgPart().fileName();
02738     bool typeBlacklisted = node->msgPart().typeStr() == "multipart";
02739     if ( !typeBlacklisted && node->msgPart().typeStr() == "application" ) {
02740       typeBlacklisted = node->msgPart().subtypeStr() == "pgp-encrypted"
02741           || node->msgPart().subtypeStr() == "pgp-signature"
02742           || node->msgPart().subtypeStr() == "pkcs7-mime"
02743           || node->msgPart().subtypeStr() == "pkcs7-signature";
02744     }
02745     typeBlacklisted = typeBlacklisted || node == mRootNode;
02746     if ( !label.isEmpty() && !icon.isEmpty() && !typeBlacklisted ) {
02747       html += "<div style=\"float:left;\">";
02748       html += QString::fromLatin1( "<span style=\"white-space:nowrap; border-width: 0px; border-left-width: 5px; border-color: %1; 2px; border-left-style: solid;\">" ).arg( bgColor.name() );
02749       html += QString::fromLatin1( "<a href=\"#att%1\">" ).arg( node->nodeId() );
02750       html += "<img style=\"vertical-align:middle;\" src=\"" + icon + "\"/>&nbsp;";
02751       if ( headerStyle() == HeaderStyle::enterprise() ) {
02752         QFont bodyFont = mCSSHelper->bodyFont( isFixedFont() );
02753         QFontMetrics fm( bodyFont );
02754         html += KStringHandler::rPixelSqueeze( label, fm, 140 );
02755       } else
02756         html += label;
02757       html += "</a></span></div> ";
02758     }
02759   }
02760 
02761   html += renderAttachments( node->nextSibling(), nextColor ( bgColor ) );
02762   return html;
02763 }
02764 
02765 #include "kmreaderwin.moc"
02766 
02767