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