kmail

kmreaderwin.cpp

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