kmail

kmreaderwin.cpp

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