kmail

kmreaderwin.cpp

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