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