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       uint 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       if ( i == encodings.size() ) {
01107         // the value of encoding is unknown => use Auto
01108         kdWarning(5006) << "Unknown override character encoding \"" << encoding
01109                         << "\". Using Auto instead." << endl;
01110         mSelectEncodingAction->setCurrentItem( 0 );
01111         mOverrideEncoding = QString::null;
01112       }
01113     }
01114   }
01115   update( true );
01116 }
01117 
01118 //-----------------------------------------------------------------------------
01119 const QTextCodec * KMReaderWin::overrideCodec() const
01120 {
01121   kdDebug(5006) << k_funcinfo << " mOverrideEncoding == '" << mOverrideEncoding << "'" << endl;
01122   if ( mOverrideEncoding.isEmpty() || mOverrideEncoding == "Auto" ) // Auto
01123     return 0;
01124   else
01125     return KMMsgBase::codecForName( mOverrideEncoding.latin1() );
01126 }
01127 
01128 //-----------------------------------------------------------------------------
01129 void KMReaderWin::slotSetEncoding()
01130 {
01131   if ( mSelectEncodingAction->currentItem() == 0 ) // Auto
01132     mOverrideEncoding = QString();
01133   else
01134     mOverrideEncoding = KGlobal::charsets()->encodingForName( mSelectEncodingAction->currentText() );
01135   update( true );
01136 }
01137 
01138 //-----------------------------------------------------------------------------
01139 void KMReaderWin::readGlobalOverrideCodec()
01140 {
01141   // if the global character encoding wasn't changed then there's nothing to do
01142   if ( GlobalSettings::self()->overrideCharacterEncoding() == mOldGlobalOverrideEncoding )
01143     return;
01144 
01145   setOverrideEncoding( GlobalSettings::self()->overrideCharacterEncoding() );
01146   mOldGlobalOverrideEncoding = GlobalSettings::self()->overrideCharacterEncoding();
01147 }
01148 
01149 //-----------------------------------------------------------------------------
01150 void KMReaderWin::setMsg(KMMessage* aMsg, bool force)
01151 {
01152   if (aMsg)
01153       kdDebug(5006) << "(" << aMsg->getMsgSerNum() << ", last " << mLastSerNum << ") " << aMsg->subject() << " "
01154         << aMsg->fromStrip() << ", readyToShow " << (aMsg->readyToShow()) << endl;
01155 
01156     //Reset the level quote if the msg has changed.
01157   if (aMsg && aMsg->getMsgSerNum() != mLastSerNum ){
01158     mLevelQuote = GlobalSettings::self()->collapseQuoteLevelSpin()-1;
01159   }
01160   if ( mPrinting )
01161     mLevelQuote = -1;
01162 
01163   bool complete = true;
01164   if ( aMsg &&
01165        !aMsg->readyToShow() &&
01166        (aMsg->getMsgSerNum() != mLastSerNum) &&
01167        !aMsg->isComplete() )
01168     complete = false;
01169 
01170   // If not forced and there is aMsg and aMsg is same as mMsg then return
01171   if (!force && aMsg && mLastSerNum != 0 && aMsg->getMsgSerNum() == mLastSerNum)
01172     return;
01173 
01174   // (de)register as observer
01175   if (aMsg && message())
01176     message()->detach( this );
01177   if (aMsg)
01178     aMsg->attach( this );
01179   mAtmUpdate = false;
01180 
01181   // connect to the updates if we have hancy headers
01182 
01183   mDelayedMarkTimer.stop();
01184 
01185   mMessage = 0;
01186   if ( !aMsg ) {
01187     mWaitingForSerNum = 0; // otherwise it has been set
01188     mLastSerNum = 0;
01189   } else {
01190     mLastSerNum = aMsg->getMsgSerNum();
01191     // Check if the serial number can be used to find the assoc KMMessage
01192     // If so, keep only the serial number (and not mMessage), to avoid a dangling mMessage
01193     // when going to another message in the mainwindow.
01194     // Otherwise, keep only mMessage, this is fine for standalone KMReaderMainWins since
01195     // we're working on a copy of the KMMessage, which we own.
01196     if (message() != aMsg) {
01197       mMessage = aMsg;
01198       mLastSerNum = 0;
01199     }
01200   }
01201 
01202   if (aMsg) {
01203     aMsg->setOverrideCodec( overrideCodec() );
01204     aMsg->setDecodeHTML( htmlMail() );
01205     mLastStatus = aMsg->status();
01206     // FIXME: workaround to disable DND for IMAP load-on-demand
01207     if ( !aMsg->isComplete() )
01208       mViewer->setDNDEnabled( false );
01209     else
01210       mViewer->setDNDEnabled( true );
01211   } else {
01212     mLastStatus = KMMsgStatusUnknown;
01213   }
01214 
01215   // only display the msg if it is complete
01216   // otherwise we'll get flickering with progressively loaded messages
01217   if ( complete )
01218   {
01219     // Avoid flicker, somewhat of a cludge
01220     if (force) {
01221       // stop the timer to avoid calling updateReaderWin twice
01222       updateReaderWinTimer.stop();
01223       updateReaderWin();
01224     }
01225     else if (updateReaderWinTimer.isActive())
01226       updateReaderWinTimer.changeInterval( delay );
01227     else
01228       updateReaderWinTimer.start( 0, TRUE );
01229   }
01230 
01231   if ( aMsg && (aMsg->isUnread() || aMsg->isNew()) && GlobalSettings::self()->delayedMarkAsRead() ) {
01232     if ( GlobalSettings::self()->delayedMarkTime() != 0 )
01233       mDelayedMarkTimer.start( GlobalSettings::self()->delayedMarkTime() * 1000, TRUE );
01234     else
01235       slotTouchMessage();
01236   }
01237 }
01238 
01239 //-----------------------------------------------------------------------------
01240 void KMReaderWin::clearCache()
01241 {
01242   updateReaderWinTimer.stop();
01243   clear();
01244   mDelayedMarkTimer.stop();
01245   mLastSerNum = 0;
01246   mWaitingForSerNum = 0;
01247   mMessage = 0;
01248 }
01249 
01250 // enter items for the "Important changes" list here:
01251 static const char * const kmailChanges[] = {
01252   ""
01253 };
01254 static const int numKMailChanges =
01255   sizeof kmailChanges / sizeof *kmailChanges;
01256 
01257 // enter items for the "new features" list here, so the main body of
01258 // the welcome page can be left untouched (probably much easier for
01259 // the translators). Note that the <li>...</li> tags are added
01260 // automatically below:
01261 static const char * const kmailNewFeatures[] = {
01262   I18N_NOOP("Full namespace support for IMAP"),
01263   I18N_NOOP("Offline mode"),
01264   I18N_NOOP("Sieve script management and editing"),
01265   I18N_NOOP("Account specific filtering"),
01266   I18N_NOOP("Filtering of incoming mail for online IMAP accounts"),
01267   I18N_NOOP("Online IMAP folders can be used when filtering into folders"),
01268   I18N_NOOP("Automatically delete older mails on POP servers")
01269 };
01270 static const int numKMailNewFeatures =
01271   sizeof kmailNewFeatures / sizeof *kmailNewFeatures;
01272 
01273 
01274 //-----------------------------------------------------------------------------
01275 //static
01276 QString KMReaderWin::newFeaturesMD5()
01277 {
01278   QCString str;
01279   for ( int i = 0 ; i < numKMailChanges ; ++i )
01280     str += kmailChanges[i];
01281   for ( int i = 0 ; i < numKMailNewFeatures ; ++i )
01282     str += kmailNewFeatures[i];
01283   KMD5 md5( str );
01284   return md5.base64Digest();
01285 }
01286 
01287 //-----------------------------------------------------------------------------
01288 void KMReaderWin::displaySplashPage( const QString &info )
01289 {
01290   mMsgDisplay = false;
01291   adjustLayout();
01292 
01293   QString location = locate("data", "kmail/about/main.html");
01294   QString content = KPIM::kFileToString(location);
01295   content = content.arg( locate( "data", "libkdepim/about/kde_infopage.css" ) );
01296   if ( kapp->reverseLayout() )
01297     content = content.arg( "@import \"%1\";" ).arg( locate( "data", "libkdepim/about/kde_infopage_rtl.css" ) );
01298   else
01299     content = content.arg( "" );
01300 
01301   mViewer->begin(KURL( location ));
01302 
01303   QString fontSize = QString::number( pointsToPixel( mCSSHelper->bodyFont().pointSize() ) );
01304   QString appTitle = i18n("KMail");
01305   QString catchPhrase = ""; //not enough space for a catch phrase at default window size i18n("Part of the Kontact Suite");
01306   QString quickDescription = i18n("The email client for the K Desktop Environment.");
01307   mViewer->write(content.arg(fontSize).arg(appTitle).arg(catchPhrase).arg(quickDescription).arg(info));
01308   mViewer->end();
01309 }
01310 
01311 void KMReaderWin::displayBusyPage()
01312 {
01313   QString info =
01314     i18n( "<h2 style='margin-top: 0px;'>Retrieving Folder Contents</h2><p>Please wait . . .</p>&nbsp;" );
01315 
01316   displaySplashPage( info );
01317 }
01318 
01319 void KMReaderWin::displayOfflinePage()
01320 {
01321   QString info =
01322     i18n( "<h2 style='margin-top: 0px;'>Offline</h2><p>KMail is currently in offline mode. "
01323         "Click <a href=\"kmail:goOnline\">here</a> to go online . . .</p>&nbsp;" );
01324 
01325   displaySplashPage( info );
01326 }
01327 
01328 
01329 //-----------------------------------------------------------------------------
01330 void KMReaderWin::displayAboutPage()
01331 {
01332   QString info =
01333     i18n("%1: KMail version; %2: help:// URL; %3: homepage URL; "
01334      "%4: prior KMail version; %5: prior KDE version; "
01335      "%6: generated list of new features; "
01336      "%7: First-time user text (only shown on first start); "
01337          "%8: generated list of important changes; "
01338      "--- end of comment ---",
01339      "<h2 style='margin-top: 0px;'>Welcome to KMail %1</h2><p>KMail is the email client for the K "
01340      "Desktop Environment. It is designed to be fully compatible with "
01341      "Internet mailing standards including MIME, SMTP, POP3 and IMAP."
01342      "</p>\n"
01343      "<ul><li>KMail has many powerful features which are described in the "
01344      "<a href=\"%2\">documentation</a></li>\n"
01345      "<li>The <a href=\"%3\">KMail homepage</A> offers information about "
01346      "new versions of KMail</li></ul>\n"
01347          "%8\n" // important changes
01348      "<p>Some of the new features in this release of KMail include "
01349      "(compared to KMail %4, which is part of KDE %5):</p>\n"
01350      "<ul>\n%6</ul>\n"
01351      "%7\n"
01352      "<p>We hope that you will enjoy KMail.</p>\n"
01353      "<p>Thank you,</p>\n"
01354          "<p style='margin-bottom: 0px'>&nbsp; &nbsp; The KMail Team</p>")
01355     .arg(KMAIL_VERSION) // KMail version
01356     .arg("help:/kmail/index.html") // KMail help:// URL
01357     .arg("http://kmail.kde.org/") // KMail homepage URL
01358     .arg("1.8").arg("3.4"); // prior KMail and KDE version
01359 
01360   QString featureItems;
01361   for ( int i = 0 ; i < numKMailNewFeatures ; i++ )
01362     featureItems += i18n("<li>%1</li>\n").arg( i18n( kmailNewFeatures[i] ) );
01363 
01364   info = info.arg( featureItems );
01365 
01366   if( kmkernel->firstStart() ) {
01367     info = info.arg( i18n("<p>Please take a moment to fill in the KMail "
01368               "configuration panel at Settings-&gt;Configure "
01369               "KMail.\n"
01370               "You need to create at least a default identity and "
01371               "an incoming as well as outgoing mail account."
01372               "</p>\n") );
01373   } else {
01374     info = info.arg( QString::null );
01375   }
01376 
01377   if ( ( numKMailChanges > 1 ) || ( numKMailChanges == 1 && strlen(kmailChanges[0]) > 0 ) ) {
01378     QString changesText =
01379       i18n("<p><span style='font-size:125%; font-weight:bold;'>"
01380            "Important changes</span> (compared to KMail %1):</p>\n")
01381       .arg("1.8");
01382     changesText += "<ul>\n";
01383     for ( int i = 0 ; i < numKMailChanges ; i++ )
01384       changesText += i18n("<li>%1</li>\n").arg( i18n( kmailChanges[i] ) );
01385     changesText += "</ul>\n";
01386     info = info.arg( changesText );
01387   }
01388   else
01389     info = info.arg(""); // remove the %8
01390 
01391   displaySplashPage( info );
01392 }
01393 
01394 void KMReaderWin::enableMsgDisplay() {
01395   mMsgDisplay = true;
01396   adjustLayout();
01397 }
01398 
01399 
01400 //-----------------------------------------------------------------------------
01401 
01402 void KMReaderWin::updateReaderWin()
01403 {
01404   if (!mMsgDisplay) return;
01405 
01406   mViewer->setOnlyLocalReferences(!htmlLoadExternal());
01407 
01408   htmlWriter()->reset();
01409 
01410   KMFolder* folder;
01411   if (message(&folder))
01412   {
01413     if ( mShowColorbar )
01414       mColorBar->show();
01415     else
01416       mColorBar->hide();
01417     displayMessage();
01418   }
01419   else
01420   {
01421     mColorBar->hide();
01422     mMimePartTree->hide();
01423     mMimePartTree->clear();
01424     htmlWriter()->begin( mCSSHelper->cssDefinitions( isFixedFont() ) );
01425     htmlWriter()->write( mCSSHelper->htmlHead( isFixedFont() ) + "</body></html>" );
01426     htmlWriter()->end();
01427   }
01428 
01429   if (mSavedRelativePosition)
01430   {
01431     QScrollView * scrollview = static_cast<QScrollView *>(mViewer->widget());
01432     scrollview->setContentsPos ( 0, qRound(  scrollview->contentsHeight() * mSavedRelativePosition ) );
01433     mSavedRelativePosition = 0;
01434   }
01435 }
01436 
01437 //-----------------------------------------------------------------------------
01438 int KMReaderWin::pointsToPixel(int pointSize) const
01439 {
01440   const QPaintDeviceMetrics pdm(mViewer->view());
01441 
01442   return (pointSize * pdm.logicalDpiY() + 36) / 72;
01443 }
01444 
01445 //-----------------------------------------------------------------------------
01446 void KMReaderWin::showHideMimeTree( bool isPlainTextTopLevel ) {
01447   if ( mMimeTreeMode == 2 ||
01448        ( mMimeTreeMode == 1 && !isPlainTextTopLevel ) )
01449     mMimePartTree->show();
01450   else {
01451     // don't rely on QSplitter maintaining sizes for hidden widgets:
01452     KConfigGroup reader( KMKernel::config(), "Reader" );
01453     saveSplitterSizes( reader );
01454     mMimePartTree->hide();
01455   }
01456 }
01457 
01458 void KMReaderWin::displayMessage() {
01459   KMMessage * msg = message();
01460 
01461   mMimePartTree->clear();
01462   showHideMimeTree( !msg || // treat no message as "text/plain"
01463             ( msg->type() == DwMime::kTypeText
01464               && msg->subtype() == DwMime::kSubtypePlain ) );
01465 
01466   if ( !msg )
01467     return;
01468 
01469   msg->setOverrideCodec( overrideCodec() );
01470 
01471   htmlWriter()->begin( mCSSHelper->cssDefinitions( isFixedFont() ) );
01472   htmlWriter()->queue( mCSSHelper->htmlHead( isFixedFont() ) );
01473 
01474   if (!parent())
01475     setCaption(msg->subject());
01476 
01477   removeTempFiles();
01478 
01479   mColorBar->setNeutralMode();
01480 
01481   parseMsg(msg);
01482 
01483   if( mColorBar->isNeutral() )
01484     mColorBar->setNormalMode();
01485 
01486   htmlWriter()->queue("</body></html>");
01487   htmlWriter()->flush();
01488 }
01489 
01490 
01491 //-----------------------------------------------------------------------------
01492 void KMReaderWin::parseMsg(KMMessage* aMsg)
01493 {
01494 #ifndef NDEBUG
01495   kdDebug( 5006 )
01496     << "parseMsg(KMMessage* aMsg "
01497     << ( aMsg == message() ? "==" : "!=" )
01498     << " aMsg )" << endl;
01499 #endif
01500 
01501   KMMessagePart msgPart;
01502   QCString subtype, contDisp;
01503   QByteArray str;
01504 
01505   assert(aMsg!=0);
01506 
01507   delete mRootNode;
01508   mRootNode = partNode::fromMessage( aMsg );
01509   const QCString mainCntTypeStr = mRootNode->typeString() + '/' + mRootNode->subTypeString();
01510 
01511   QString cntDesc = aMsg->subject();
01512   if( cntDesc.isEmpty() )
01513     cntDesc = i18n("( body part )");
01514   KIO::filesize_t cntSize = aMsg->msgSize();
01515   QString cntEnc;
01516   if( aMsg->contentTransferEncodingStr().isEmpty() )
01517     cntEnc = "7bit";
01518   else
01519     cntEnc = aMsg->contentTransferEncodingStr();
01520 
01521   // fill the MIME part tree viewer
01522   mRootNode->fillMimePartTree( 0,
01523                    mMimePartTree,
01524                    cntDesc,
01525                    mainCntTypeStr,
01526                    cntEnc,
01527                    cntSize );
01528 
01529   partNode* vCardNode = mRootNode->findType( DwMime::kTypeText, DwMime::kSubtypeXVCard );
01530   bool hasVCard = false;
01531   if( vCardNode ) {
01532     // ### FIXME: We should only do this if the vCard belongs to the sender,
01533     // ### i.e. if the sender's email address is contained in the vCard.
01534     const QString vcard = vCardNode->msgPart().bodyToUnicode( overrideCodec() );
01535     KABC::VCardConverter t;
01536     if ( !t.parseVCards( vcard ).empty() ) {
01537       hasVCard = true;
01538       kdDebug(5006) << "FOUND A VALID VCARD" << endl;
01539       writeMessagePartToTempFile( &vCardNode->msgPart(), vCardNode->nodeId() );
01540     }
01541   }
01542   htmlWriter()->queue( writeMsgHeader(aMsg, hasVCard) );
01543 
01544   // show message content
01545   ObjectTreeParser otp( this );
01546   otp.parseObjectTree( mRootNode );
01547 
01548   // store encrypted/signed status information in the KMMessage
01549   //  - this can only be done *after* calling parseObjectTree()
01550   KMMsgEncryptionState encryptionState = mRootNode->overallEncryptionState();
01551   KMMsgSignatureState  signatureState  = mRootNode->overallSignatureState();
01552   aMsg->setEncryptionState( encryptionState );
01553   // Don't reset the signature state to "not signed" (e.g. if one canceled the
01554   // decryption of a signed messages which has already been decrypted before).
01555   if ( signatureState != KMMsgNotSigned ||
01556        aMsg->signatureState() == KMMsgSignatureStateUnknown ) {
01557     aMsg->setSignatureState( signatureState );
01558   }
01559 
01560   bool emitReplaceMsgByUnencryptedVersion = false;
01561   const KConfigGroup reader( KMKernel::config(), "Reader" );
01562   if ( reader.readBoolEntry( "store-displayed-messages-unencrypted", false ) ) {
01563 
01564   // Hack to make sure the S/MIME CryptPlugs follows the strict requirement
01565   // of german government:
01566   // --> All received encrypted messages *must* be stored in unencrypted form
01567   //     after they have been decrypted once the user has read them.
01568   //     ( "Aufhebung der Verschluesselung nach dem Lesen" )
01569   //
01570   // note: Since there is no configuration option for this, we do that for
01571   //       all kinds of encryption now - *not* just for S/MIME.
01572   //       This could be changed in the objectTreeToDecryptedMsg() function
01573   //       by deciding when (or when not, resp.) to set the 'dataNode' to
01574   //       something different than 'curNode'.
01575 
01576 
01577 kdDebug(5006) << "\n\n\nKMReaderWin::parseMsg()  -  special post-encryption handling:\n1." << endl;
01578 kdDebug(5006) << "(aMsg == msg) = "                               << (aMsg == message()) << endl;
01579 kdDebug(5006) << "   (KMMsgStatusUnknown == mLastStatus) = "           << (KMMsgStatusUnknown == mLastStatus) << endl;
01580 kdDebug(5006) << "|| (KMMsgStatusNew     == mLastStatus) = "           << (KMMsgStatusNew     == mLastStatus) << endl;
01581 kdDebug(5006) << "|| (KMMsgStatusUnread  == mLastStatus) = "           << (KMMsgStatusUnread  == mLastStatus) << endl;
01582 kdDebug(5006) << "(mIdOfLastViewedMessage != aMsg->msgId()) = "    << (mIdOfLastViewedMessage != aMsg->msgId()) << endl;
01583 kdDebug(5006) << "   (KMMsgFullyEncrypted == encryptionState) = "     << (KMMsgFullyEncrypted == encryptionState) << endl;
01584 kdDebug(5006) << "|| (KMMsgPartiallyEncrypted == encryptionState) = " << (KMMsgPartiallyEncrypted == encryptionState) << endl;
01585          // only proceed if we were called the normal way - not by
01586          // double click on the message (==not running in a separate window)
01587   if(    (aMsg == message())
01588          // only proceed if this message was not saved encryptedly before
01589          // to make sure only *new* messages are saved in decrypted form
01590       && (    (KMMsgStatusUnknown == mLastStatus)
01591            || (KMMsgStatusNew     == mLastStatus)
01592            || (KMMsgStatusUnread  == mLastStatus) )
01593          // avoid endless recursions
01594       && (mIdOfLastViewedMessage != aMsg->msgId())
01595          // only proceed if this message is (at least partially) encrypted
01596       && (    (KMMsgFullyEncrypted == encryptionState)
01597            || (KMMsgPartiallyEncrypted == encryptionState) ) ) {
01598 
01599 kdDebug(5006) << "KMReaderWin  -  calling objectTreeToDecryptedMsg()" << endl;
01600 
01601     NewByteArray decryptedData;
01602     // note: The following call may change the message's headers.
01603     objectTreeToDecryptedMsg( mRootNode, decryptedData, *aMsg );
01604     // add a \0 to the data
01605     decryptedData.appendNULL();
01606     QCString resultString( decryptedData.data() );
01607 kdDebug(5006) << "KMReaderWin  -  resulting data:" << resultString << endl;
01608 
01609     if( !resultString.isEmpty() ) {
01610 kdDebug(5006) << "KMReaderWin  -  composing unencrypted message" << endl;
01611       // try this:
01612       aMsg->setBody( resultString );
01613       KMMessage* unencryptedMessage = new KMMessage( *aMsg );
01614       unencryptedMessage->setParent( 0 );
01615       // because this did not work:
01616       /*
01617       DwMessage dwMsg( aMsg->asDwString() );
01618       dwMsg.Body() = DwBody( DwString( resultString.data() ) );
01619       dwMsg.Body().Parse();
01620       KMMessage* unencryptedMessage = new KMMessage( &dwMsg );
01621       */
01622       //kdDebug(5006) << "KMReaderWin  -  resulting message:" << unencryptedMessage->asString() << endl;
01623       kdDebug(5006) << "KMReaderWin  -  attach unencrypted message to aMsg" << endl;
01624       aMsg->setUnencryptedMsg( unencryptedMessage );
01625       emitReplaceMsgByUnencryptedVersion = true;
01626     }
01627   }
01628   }
01629 
01630   // save current main Content-Type before deleting mRootNode
01631   const int rootNodeCntType = mRootNode ? mRootNode->type() : DwMime::kTypeText;
01632   const int rootNodeCntSubtype = mRootNode ? mRootNode->subType() : DwMime::kSubtypePlain;
01633 
01634   // store message id to avoid endless recursions
01635   setIdOfLastViewedMessage( aMsg->msgId() );
01636 
01637   if( emitReplaceMsgByUnencryptedVersion ) {
01638     kdDebug(5006) << "KMReaderWin  -  invoce saving in decrypted form:" << endl;
01639     emit replaceMsgByUnencryptedVersion();
01640   } else {
01641     kdDebug(5006) << "KMReaderWin  -  finished parsing and displaying of message." << endl;
01642     showHideMimeTree( rootNodeCntType == DwMime::kTypeText &&
01643               rootNodeCntSubtype == DwMime::kSubtypePlain );
01644   }
01645 }
01646 
01647 
01648 //-----------------------------------------------------------------------------
01649 QString KMReaderWin::writeMsgHeader(KMMessage* aMsg, bool hasVCard)
01650 {
01651   kdFatal( !headerStyle(), 5006 )
01652     << "trying to writeMsgHeader() without a header style set!" << endl;
01653   kdFatal( !headerStrategy(), 5006 )
01654     << "trying to writeMsgHeader() without a header strategy set!" << endl;
01655   QString href;
01656   if (hasVCard)
01657     href = QString("file:") + KURL::encode_string( mTempFiles.last() );
01658 
01659   return headerStyle()->format( aMsg, headerStrategy(), href, mPrinting );
01660 }
01661 
01662 
01663 
01664 //-----------------------------------------------------------------------------
01665 QString KMReaderWin::writeMessagePartToTempFile( KMMessagePart* aMsgPart,
01666                                                  int aPartNum )
01667 {
01668   QString fileName = aMsgPart->fileName();
01669   if( fileName.isEmpty() )
01670     fileName = aMsgPart->name();
01671 
01672   //--- Sven's save attachments to /tmp start ---
01673   KTempFile *tempFile = new KTempFile( QString::null,
01674                                        "." + QString::number( aPartNum ) );
01675   tempFile->setAutoDelete( true );
01676   QString fname = tempFile->name();
01677   delete tempFile;
01678 
01679   if( ::access( QFile::encodeName( fname ), W_OK ) != 0 )
01680     // Not there or not writable
01681     if( ::mkdir( QFile::encodeName( fname ), 0 ) != 0
01682         || ::chmod( QFile::encodeName( fname ), S_IRWXU ) != 0 )
01683       return QString::null; //failed create
01684 
01685   assert( !fname.isNull() );
01686 
01687   mTempDirs.append( fname );
01688   // strip off a leading path
01689   int slashPos = fileName.findRev( '/' );
01690   if( -1 != slashPos )
01691     fileName = fileName.mid( slashPos + 1 );
01692   if( fileName.isEmpty() )
01693     fileName = "unnamed";
01694   fname += "/" + fileName;
01695 
01696   QByteArray data = aMsgPart->bodyDecodedBinary();
01697   size_t size = data.size();
01698   if ( aMsgPart->type() == DwMime::kTypeText && size) {
01699     // convert CRLF to LF before writing text attachments to disk
01700     size = KMail::Util::crlf2lf( data.data(), size );
01701   }
01702   if( !KPIM::kBytesToFile( data.data(), size, fname, false, false, false ) )
01703     return QString::null;
01704 
01705   mTempFiles.append( fname );
01706   // make file read-only so that nobody gets the impression that he might
01707   // edit attached files (cf. bug #52813)
01708   ::chmod( QFile::encodeName( fname ), S_IRUSR );
01709 
01710   return fname;
01711 }
01712 
01713 
01714 //-----------------------------------------------------------------------------
01715 void KMReaderWin::showVCard( KMMessagePart * msgPart ) {
01716   const QString vCard = msgPart->bodyToUnicode( overrideCodec() );
01717 
01718   VCardViewer *vcv = new VCardViewer(this, vCard, "vCardDialog");
01719   vcv->show();
01720 }
01721 
01722 //-----------------------------------------------------------------------------
01723 void KMReaderWin::printMsg()
01724 {
01725   if (!message()) return;
01726   mViewer->view()->print();
01727 }
01728 
01729 
01730 //-----------------------------------------------------------------------------
01731 int KMReaderWin::msgPartFromUrl(const KURL &aUrl)
01732 {
01733   if (aUrl.isEmpty()) return -1;
01734 
01735   if (!aUrl.isLocalFile()) return -1;
01736 
01737   QString path = aUrl.path();
01738   uint right = path.findRev('/');
01739   uint left = path.findRev('.', right);
01740 
01741   bool ok;
01742   int res = path.mid(left + 1, right - left - 1).toInt(&ok);
01743   return (ok) ? res : -1;
01744 }
01745 
01746 
01747 //-----------------------------------------------------------------------------
01748 void KMReaderWin::resizeEvent(QResizeEvent *)
01749 {
01750   if( !mResizeTimer.isActive() )
01751   {
01752     //
01753     // Combine all resize operations that are requested as long a
01754     // the timer runs.
01755     //
01756     mResizeTimer.start( 100, true );
01757   }
01758 }
01759 
01760 
01761 //-----------------------------------------------------------------------------
01762 void KMReaderWin::slotDelayedResize()
01763 {
01764   mSplitter->setGeometry(0, 0, width(), height());
01765 }
01766 
01767 
01768 //-----------------------------------------------------------------------------
01769 void KMReaderWin::slotTouchMessage()
01770 {
01771   if ( !message() )
01772     return;
01773 
01774   if ( !message()->isNew() && !message()->isUnread() )
01775     return;
01776 
01777   SerNumList serNums;
01778   serNums.append( message()->getMsgSerNum() );
01779   KMCommand *command = new KMSetStatusCommand( KMMsgStatusRead, serNums );
01780   command->start();
01781   if ( mNoMDNsWhenEncrypted &&
01782        message()->encryptionState() != KMMsgNotEncrypted &&
01783        message()->encryptionState() != KMMsgEncryptionStateUnknown )
01784     return;
01785   if ( KMMessage * receipt = message()->createMDN( MDN::ManualAction,
01786                            MDN::Displayed,
01787                            true /* allow GUI */ ) )
01788     if ( !kmkernel->msgSender()->send( receipt ) ) // send or queue
01789       KMessageBox::error( this, i18n("Could not send MDN.") );
01790 }
01791 
01792 
01793 //-----------------------------------------------------------------------------
01794 void KMReaderWin::closeEvent(QCloseEvent *e)
01795 {
01796   QWidget::closeEvent(e);
01797   writeConfig();
01798 }
01799 
01800 
01801 bool foundSMIMEData( const QString aUrl,
01802                      QString& displayName,
01803                      QString& libName,
01804                      QString& keyId )
01805 {
01806   static QString showCertMan("showCertificate#");
01807   displayName = "";
01808   libName = "";
01809   keyId = "";
01810   int i1 = aUrl.find( showCertMan );
01811   if( -1 < i1 ) {
01812     i1 += showCertMan.length();
01813     int i2 = aUrl.find(" ### ", i1);
01814     if( i1 < i2 )
01815     {
01816       displayName = aUrl.mid( i1, i2-i1 );
01817       i1 = i2+5;
01818       i2 = aUrl.find(" ### ", i1);
01819       if( i1 < i2 )
01820       {
01821         libName = aUrl.mid( i1, i2-i1 );
01822         i2 += 5;
01823 
01824         keyId = aUrl.mid( i2 );
01825         /*
01826         int len = aUrl.length();
01827         if( len > i2+1 ) {
01828           keyId = aUrl.mid( i2, 2 );
01829           i2 += 2;
01830           while( len > i2+1 ) {
01831             keyId += ':';
01832             keyId += aUrl.mid( i2, 2 );
01833             i2 += 2;
01834           }
01835         }
01836         */
01837       }
01838     }
01839   }
01840   return !keyId.isEmpty();
01841 }
01842 
01843 
01844 //-----------------------------------------------------------------------------
01845 void KMReaderWin::slotUrlOn(const QString &aUrl)
01846 {
01847   if ( aUrl.stripWhiteSpace().isEmpty() ) {
01848     KPIM::BroadcastStatus::instance()->reset();
01849     return;
01850   }
01851 
01852   const KURL url(aUrl);
01853   mUrlClicked = url;
01854 
01855   const QString msg = URLHandlerManager::instance()->statusBarMessage( url, this );
01856 
01857   kdWarning( msg.isEmpty(), 5006 ) << "KMReaderWin::slotUrlOn(): Unhandled URL hover!" << endl;
01858   KPIM::BroadcastStatus::instance()->setTransientStatusMsg( msg );
01859 }
01860 
01861 
01862 //-----------------------------------------------------------------------------
01863 void KMReaderWin::slotUrlOpen(const KURL &aUrl, const KParts::URLArgs &)
01864 {
01865   mUrlClicked = aUrl;
01866 
01867   if ( URLHandlerManager::instance()->handleClick( aUrl, this ) )
01868     return;
01869 
01870   kdWarning( 5006 ) << "KMReaderWin::slotOpenUrl(): Unhandled URL click!" << endl;
01871   emit urlClicked( aUrl, Qt::LeftButton );
01872 }
01873 
01874 //-----------------------------------------------------------------------------
01875 void KMReaderWin::slotUrlPopup(const QString &aUrl, const QPoint& aPos)
01876 {
01877   const KURL url( aUrl );
01878   mUrlClicked = url;
01879 
01880   if ( URLHandlerManager::instance()->handleContextMenuRequest( url, aPos, this ) )
01881     return;
01882 
01883   if ( message() ) {
01884     kdWarning( 5006 ) << "KMReaderWin::slotUrlPopup(): Unhandled URL right-click!" << endl;
01885     emit popupMenu( *message(), url, aPos );
01886   }
01887 }
01888 
01889 //-----------------------------------------------------------------------------
01890 void KMReaderWin::showAttachmentPopup( int id, const QString & name, const QPoint & p )
01891 {
01892   mAtmCurrent = id;
01893   mAtmCurrentName = name;
01894   KPopupMenu *menu = new KPopupMenu();
01895   menu->insertItem(SmallIcon("fileopen"),i18n("to open", "Open"), 1);
01896   menu->insertItem(i18n("Open With..."), 2);
01897   menu->insertItem(i18n("to view something", "View"), 3);
01898   menu->insertItem(SmallIcon("filesaveas"),i18n("Save As..."), 4);
01899   if ( name.endsWith( ".xia", false ) &&
01900        Kleo::CryptoBackendFactory::instance()->protocol( "Chiasmus" ) )
01901     menu->insertItem( i18n( "Decrypt With Chiasmus..." ), 6 );
01902   menu->insertItem(i18n("Properties"), 5);
01903   connect(menu, SIGNAL(activated(int)), this, SLOT(slotHandleAttachment(int)));
01904   menu->exec( p ,0 );
01905   delete menu;
01906 }
01907 
01908 //-----------------------------------------------------------------------------
01909 void KMReaderWin::setStyleDependantFrameWidth()
01910 {
01911   if ( !mBox )
01912     return;
01913   // set the width of the frame to a reasonable value for the current GUI style
01914   int frameWidth;
01915   if( style().isA("KeramikStyle") )
01916     frameWidth = style().pixelMetric( QStyle::PM_DefaultFrameWidth ) - 1;
01917   else
01918     frameWidth = style().pixelMetric( QStyle::PM_DefaultFrameWidth );
01919   if ( frameWidth < 0 )
01920     frameWidth = 0;
01921   if ( frameWidth != mBox->lineWidth() )
01922     mBox->setLineWidth( frameWidth );
01923 }
01924 
01925 //-----------------------------------------------------------------------------
01926 void KMReaderWin::styleChange( QStyle& oldStyle )
01927 {
01928   setStyleDependantFrameWidth();
01929   QWidget::styleChange( oldStyle );
01930 }
01931 
01932 //-----------------------------------------------------------------------------
01933 void KMReaderWin::slotHandleAttachment( int choice )
01934 {
01935   mAtmUpdate = true;
01936   partNode* node = mRootNode ? mRootNode->findId( mAtmCurrent ) : 0;
01937   KMHandleAttachmentCommand* command = new KMHandleAttachmentCommand(
01938       node, message(), mAtmCurrent, mAtmCurrentName,
01939       KMHandleAttachmentCommand::AttachmentAction( choice ), 0, this );
01940   connect( command, SIGNAL( showAttachment( int, const QString& ) ),
01941       this, SLOT( slotAtmView( int, const QString& ) ) );
01942   command->start();
01943 }
01944 
01945 //-----------------------------------------------------------------------------
01946 void KMReaderWin::slotFind()
01947 {
01948   mViewer->findText();
01949 }
01950 
01951 //-----------------------------------------------------------------------------
01952 void KMReaderWin::slotFindNext()
01953 {
01954   mViewer->findTextNext();
01955 }
01956 
01957 //-----------------------------------------------------------------------------
01958 void KMReaderWin::slotToggleFixedFont()
01959 {
01960   QScrollView * scrollview = static_cast<QScrollView *>(mViewer->widget());
01961   mSavedRelativePosition = (float)scrollview->contentsY() / scrollview->contentsHeight();
01962 
01963   mUseFixedFont = !mUseFixedFont;
01964   update(true);
01965 }
01966 
01967 
01968 //-----------------------------------------------------------------------------
01969 void KMReaderWin::slotCopySelectedText()
01970 {
01971   kapp->clipboard()->setText( mViewer->selectedText() );
01972 }
01973 
01974 
01975 //-----------------------------------------------------------------------------
01976 void KMReaderWin::atmViewMsg(KMMessagePart* aMsgPart)
01977 {
01978   assert(aMsgPart!=0);
01979   KMMessage* msg = new KMMessage;
01980   msg->fromString(aMsgPart->bodyDecoded());
01981   assert(msg != 0);
01982   msg->setMsgSerNum( 0 ); // because lookups will fail
01983   // some information that is needed for imap messages with LOD
01984   msg->setParent( message()->parent() );
01985   msg->setUID(message()->UID());
01986   msg->setReadyToShow(true);
01987   KMReaderMainWin *win = new KMReaderMainWin();
01988   win->showMsg( overrideEncoding(), msg );
01989   win->show();
01990 }
01991 
01992 
01993 void KMReaderWin::setMsgPart( partNode * node ) {
01994   htmlWriter()->reset();
01995   mColorBar->hide();
01996   htmlWriter()->begin( mCSSHelper->cssDefinitions( isFixedFont() ) );
01997   htmlWriter()->write( mCSSHelper->htmlHead( isFixedFont() ) );
01998   // end ###
01999   if ( node ) {
02000     ObjectTreeParser otp( this, 0, true );
02001     otp.parseObjectTree( node );
02002   }
02003   // ### this, too
02004   htmlWriter()->queue( "</body></html>" );
02005   htmlWriter()->flush();
02006 }
02007 
02008 //-----------------------------------------------------------------------------
02009 void KMReaderWin::setMsgPart( KMMessagePart* aMsgPart, bool aHTML,
02010                   const QString& aFileName, const QString& pname )
02011 {
02012   KCursorSaver busy(KBusyPtr::busy());
02013   if (kasciistricmp(aMsgPart->typeStr(), "message")==0) {
02014       // if called from compose win
02015       KMMessage* msg = new KMMessage;
02016       assert(aMsgPart!=0);
02017       msg->fromString(aMsgPart->bodyDecoded());
02018       mMainWindow->setCaption(msg->subject());
02019       setMsg(msg, true);
02020       setAutoDelete(true);
02021   } else if (kasciistricmp(aMsgPart->typeStr(), "text")==0) {
02022       if (kasciistricmp(aMsgPart->subtypeStr(), "x-vcard") == 0) {
02023         showVCard( aMsgPart );
02024     return;
02025       }
02026       htmlWriter()->begin( mCSSHelper->cssDefinitions( isFixedFont() ) );
02027       htmlWriter()->queue( mCSSHelper->htmlHead( isFixedFont() ) );
02028 
02029       if (aHTML && (kasciistricmp(aMsgPart->subtypeStr(), "html")==0)) { // HTML
02030         // ### this is broken. It doesn't stip off the HTML header and footer!
02031         htmlWriter()->queue( aMsgPart->bodyToUnicode( overrideCodec() ) );
02032         mColorBar->setHtmlMode();
02033       } else { // plain text
02034         const QCString str = aMsgPart->bodyDecoded();
02035         ObjectTreeParser otp( this );
02036         otp.writeBodyStr( str,
02037                           overrideCodec() ? overrideCodec() : aMsgPart->codec(),
02038                           message() ? message()->from() : QString::null );
02039       }
02040       htmlWriter()->queue("</body></html>");
02041       htmlWriter()->flush();
02042       mMainWindow->setCaption(i18n("View Attachment: %1").arg(pname));
02043   } else if (kasciistricmp(aMsgPart->typeStr(), "image")==0 ||
02044              (kasciistricmp(aMsgPart->typeStr(), "application")==0 &&
02045               kasciistricmp(aMsgPart->subtypeStr(), "postscript")==0))
02046   {
02047       if (aFileName.isEmpty()) return;  // prevent crash
02048       // Open the window with a size so the image fits in (if possible):
02049       QImageIO *iio = new QImageIO();
02050       iio->setFileName(aFileName);
02051       if( iio->read() ) {
02052           QImage img = iio->image();
02053           QRect desk = KGlobalSettings::desktopGeometry(mMainWindow);
02054           // determine a reasonable window size
02055           int width, height;
02056           if( img.width() < 50 )
02057               width = 70;
02058           else if( img.width()+20 < desk.width() )
02059               width = img.width()+20;
02060           else
02061               width = desk.width();
02062           if( img.height() < 50 )
02063               height = 70;
02064           else if( img.height()+20 < desk.height() )
02065               height = img.height()+20;
02066           else
02067               height = desk.height();
02068           mMainWindow->resize( width, height );
02069       }
02070       // Just write the img tag to HTML:
02071       htmlWriter()->begin( mCSSHelper->cssDefinitions( isFixedFont() ) );
02072       htmlWriter()->write( mCSSHelper->htmlHead( isFixedFont() ) );
02073       htmlWriter()->write( "<img src=\"file:" +
02074                            KURL::encode_string( aFileName ) +
02075                            "\" border=\"0\">\n"
02076                            "</body></html>\n" );
02077       htmlWriter()->end();
02078       setCaption( i18n("View Attachment: %1").arg( pname ) );
02079       show();
02080   } else {
02081     htmlWriter()->begin( mCSSHelper->cssDefinitions( isFixedFont() ) );
02082     htmlWriter()->queue( mCSSHelper->htmlHead( isFixedFont() ) );
02083     htmlWriter()->queue( "<pre>" );
02084 
02085     QString str = aMsgPart->bodyDecoded();
02086     // A QString cannot handle binary data. So if it's shorter than the
02087     // attachment, we assume the attachment is binary:
02088     if( str.length() < (unsigned) aMsgPart->decodedSize() ) {
02089       str.prepend( i18n("[KMail: Attachment contains binary data. Trying to show first character.]",
02090           "[KMail: Attachment contains binary data. Trying to show first %n characters.]",
02091           str.length()) + QChar('\n') );
02092     }
02093     htmlWriter()->queue( QStyleSheet::escape( str ) );
02094     htmlWriter()->queue( "</pre>" );
02095     htmlWriter()->queue("</body></html>");
02096     htmlWriter()->flush();
02097     mMainWindow->setCaption(i18n("View Attachment: %1").arg(pname));
02098   }
02099   // ---Sven's view text, html and image attachments in html widget end ---
02100 }
02101 
02102 
02103 //-----------------------------------------------------------------------------
02104 void KMReaderWin::slotAtmView( int id, const QString& name )
02105 {
02106   partNode* node = mRootNode ? mRootNode->findId( id ) : 0;
02107   if( node ) {
02108     mAtmCurrent = id;
02109     mAtmCurrentName = name;
02110 
02111     KMMessagePart& msgPart = node->msgPart();
02112     QString pname = msgPart.fileName();
02113     if (pname.isEmpty()) pname=msgPart.name();
02114     if (pname.isEmpty()) pname=msgPart.contentDescription();
02115     if (pname.isEmpty()) pname="unnamed";
02116     // image Attachment is saved already
02117     if (kasciistricmp(msgPart.typeStr(), "message")==0) {
02118       atmViewMsg(&msgPart);
02119     } else if ((kasciistricmp(msgPart.typeStr(), "text")==0) &&
02120            (kasciistricmp(msgPart.subtypeStr(), "x-vcard")==0)) {
02121       setMsgPart( &msgPart, htmlMail(), name, pname );
02122     } else {
02123       KMReaderMainWin *win = new KMReaderMainWin(&msgPart, htmlMail(),
02124           name, pname, overrideEncoding() );
02125       win->show();
02126     }
02127   }
02128 }
02129 
02130 //-----------------------------------------------------------------------------
02131 void KMReaderWin::openAttachment( int id, const QString & name )
02132 {
02133   mAtmCurrentName = name;
02134   mAtmCurrent = id;
02135 
02136   QString str, pname, cmd, fileName;
02137 
02138   partNode* node = mRootNode ? mRootNode->findId( id ) : 0;
02139   if( !node ) {
02140     kdWarning(5006) << "KMReaderWin::openAttachment - could not find node " << id << endl;
02141     return;
02142   }
02143 
02144   KMMessagePart& msgPart = node->msgPart();
02145   if (kasciistricmp(msgPart.typeStr(), "message")==0)
02146   {
02147     atmViewMsg(&msgPart);
02148     return;
02149   }
02150 
02151   QCString contentTypeStr( msgPart.typeStr() + '/' + msgPart.subtypeStr() );
02152   KPIM::kAsciiToLower( contentTypeStr.data() );
02153 
02154   if ( qstrcmp( contentTypeStr, "text/x-vcard" ) == 0 ) {
02155     showVCard( &msgPart );
02156     return;
02157   }
02158 
02159   // determine the MIME type of the attachment
02160   KMimeType::Ptr mimetype;
02161   // prefer the value of the Content-Type header
02162   mimetype = KMimeType::mimeType( QString::fromLatin1( contentTypeStr ) );
02163   if ( mimetype->name() == "application/octet-stream" ) {
02164     // consider the filename if Content-Type is application/octet-stream
02165     mimetype = KMimeType::findByPath( name, 0, true /* no disk access */ );
02166   }
02167   if ( ( mimetype->name() == "application/octet-stream" )
02168        && msgPart.isComplete() ) {
02169     // consider the attachment's contents if neither the Content-Type header
02170     // nor the filename give us a clue
02171     mimetype = KMimeType::findByFileContent( name );
02172   }
02173 
02174   KService::Ptr offer =
02175     KServiceTypeProfile::preferredService( mimetype->name(), "Application" );
02176 
02177   QString open_text;
02178   QString filenameText = msgPart.fileName();
02179   if ( filenameText.isEmpty() )
02180     filenameText = msgPart.name();
02181   if ( offer ) {
02182     open_text = i18n("&Open with '%1'").arg( offer->name() );
02183   } else {
02184     open_text = i18n("&Open With...");
02185   }
02186   const QString text = i18n("Open attachment '%1'?\n"
02187                             "Note that opening an attachment may compromise "
02188                             "your system's security.")
02189                        .arg( filenameText );
02190   const int choice = KMessageBox::questionYesNoCancel( this, text,
02191       i18n("Open Attachment?"), KStdGuiItem::saveAs(), open_text,
02192       QString::fromLatin1("askSave") + mimetype->name() ); // dontAskAgainName
02193 
02194   if( choice == KMessageBox::Yes ) {        // Save
02195     mAtmUpdate = true;
02196     KMHandleAttachmentCommand* command = new KMHandleAttachmentCommand( node,
02197         message(), mAtmCurrent, mAtmCurrentName, KMHandleAttachmentCommand::Save,
02198         offer, this );
02199     connect( command, SIGNAL( showAttachment( int, const QString& ) ),
02200         this, SLOT( slotAtmView( int, const QString& ) ) );
02201     command->start();
02202   }
02203   else if( choice == KMessageBox::No ) {    // Open
02204     KMHandleAttachmentCommand::AttachmentAction action = ( offer ?
02205         KMHandleAttachmentCommand::Open : KMHandleAttachmentCommand::OpenWith );
02206     mAtmUpdate = true;
02207     KMHandleAttachmentCommand* command = new KMHandleAttachmentCommand( node,
02208         message(), mAtmCurrent, mAtmCurrentName, action, offer, this );
02209     connect( command, SIGNAL( showAttachment( int, const QString& ) ),
02210         this, SLOT( slotAtmView( int, const QString& ) ) );
02211     command->start();
02212   } else {                  // Cancel
02213     kdDebug(5006) << "Canceled opening attachment" << endl;
02214   }
02215 }
02216 
02217 //-----------------------------------------------------------------------------
02218 void KMReaderWin::slotScrollUp()
02219 {
02220   static_cast<QScrollView *>(mViewer->widget())->scrollBy(0, -10);
02221 }
02222 
02223 
02224 //-----------------------------------------------------------------------------
02225 void KMReaderWin::slotScrollDown()
02226 {
02227   static_cast<QScrollView *>(mViewer->widget())->scrollBy(0, 10);
02228 }
02229 
02230 bool KMReaderWin::atBottom() const
02231 {
02232     const QScrollView *view = static_cast<const QScrollView *>(mViewer->widget());
02233     return view->contentsY() + view->visibleHeight() >= view->contentsHeight();
02234 }
02235 
02236 //-----------------------------------------------------------------------------
02237 void KMReaderWin::slotJumpDown()
02238 {
02239     QScrollView *view = static_cast<QScrollView *>(mViewer->widget());
02240     int offs = (view->clipper()->height() < 30) ? view->clipper()->height() : 30;
02241     view->scrollBy( 0, view->clipper()->height() - offs );
02242 }
02243 
02244 //-----------------------------------------------------------------------------
02245 void KMReaderWin::slotScrollPrior()
02246 {
02247   static_cast<QScrollView *>(mViewer->widget())->scrollBy(0, -(int)(height()*0.8));
02248 }
02249 
02250 
02251 //-----------------------------------------------------------------------------
02252 void KMReaderWin::slotScrollNext()
02253 {
02254   static_cast<QScrollView *>(mViewer->widget())->scrollBy(0, (int)(height()*0.8));
02255 }
02256 
02257 //-----------------------------------------------------------------------------
02258 void KMReaderWin::slotDocumentChanged()
02259 {
02260 
02261 }
02262 
02263 
02264 //-----------------------------------------------------------------------------
02265 void KMReaderWin::slotTextSelected(bool)
02266 {
02267   QString temp = mViewer->selectedText();
02268   kapp->clipboard()->setText(temp);
02269 }
02270 
02271 //-----------------------------------------------------------------------------
02272 void KMReaderWin::selectAll()
02273 {
02274   mViewer->selectAll();
02275 }
02276 
02277 //-----------------------------------------------------------------------------
02278 QString KMReaderWin::copyText()
02279 {
02280   QString temp = mViewer->selectedText();
02281   return temp;
02282 }
02283 
02284 
02285 //-----------------------------------------------------------------------------
02286 void KMReaderWin::slotDocumentDone()
02287 {
02288   // mSbVert->setValue(0);
02289 }
02290 
02291 
02292 //-----------------------------------------------------------------------------
02293 void KMReaderWin::setHtmlOverride(bool override)
02294 {
02295   mHtmlOverride = override;
02296   if (message())
02297       message()->setDecodeHTML(htmlMail());
02298 }
02299 
02300 
02301 //-----------------------------------------------------------------------------
02302 void KMReaderWin::setHtmlLoadExtOverride(bool override)
02303 {
02304   mHtmlLoadExtOverride = override;
02305   //if (message())
02306   //    message()->setDecodeHTML(htmlMail());
02307 }
02308 
02309 
02310 //-----------------------------------------------------------------------------
02311 bool KMReaderWin::htmlMail()
02312 {
02313   return ((mHtmlMail && !mHtmlOverride) || (!mHtmlMail && mHtmlOverride));
02314 }
02315 
02316 
02317 //-----------------------------------------------------------------------------
02318 bool KMReaderWin::htmlLoadExternal()
02319 {
02320   return ((mHtmlLoadExternal && !mHtmlLoadExtOverride) ||
02321           (!mHtmlLoadExternal && mHtmlLoadExtOverride));
02322 }
02323 
02324 
02325 //-----------------------------------------------------------------------------
02326 void KMReaderWin::update( bool force )
02327 {
02328   KMMessage* msg = message();
02329   if ( msg )
02330     setMsg( msg, force );
02331 }
02332 
02333 
02334 //-----------------------------------------------------------------------------
02335 KMMessage* KMReaderWin::message( KMFolder** aFolder ) const
02336 {
02337   KMFolder*  tmpFolder;
02338   KMFolder*& folder = aFolder ? *aFolder : tmpFolder;
02339   folder = 0;
02340   if (mMessage)
02341       return mMessage;
02342   if (mLastSerNum) {
02343     KMMessage *message = 0;
02344     int index;
02345     KMMsgDict::instance()->getLocation( mLastSerNum, &folder, &index );
02346     if (folder )
02347       message = folder->getMsg( index );
02348     if (!message)
02349       kdWarning(5006) << "Attempt to reference invalid serial number " << mLastSerNum << "\n" << endl;
02350     return message;
02351   }
02352   return 0;
02353 }
02354 
02355 
02356 
02357 //-----------------------------------------------------------------------------
02358 void KMReaderWin::slotUrlClicked()
02359 {
02360   KMMainWidget *mainWidget = dynamic_cast<KMMainWidget*>(mMainWindow);
02361   uint identity = 0;
02362   if ( message() && message()->parent() ) {
02363     identity = message()->parent()->identity();
02364   }
02365 
02366   KMCommand *command = new KMUrlClickedCommand( mUrlClicked, identity, this,
02367                         false, mainWidget );
02368   command->start();
02369 }
02370 
02371 //-----------------------------------------------------------------------------
02372 void KMReaderWin::slotMailtoCompose()
02373 {
02374   KMCommand *command = new KMMailtoComposeCommand( mUrlClicked, message() );
02375   command->start();
02376 }
02377 
02378 //-----------------------------------------------------------------------------
02379 void KMReaderWin::slotMailtoForward()
02380 {
02381   KMCommand *command = new KMMailtoForwardCommand( mMainWindow, mUrlClicked,
02382                            message() );
02383   command->start();
02384 }
02385 
02386 //-----------------------------------------------------------------------------
02387 void KMReaderWin::slotMailtoAddAddrBook()
02388 {
02389   KMCommand *command = new KMMailtoAddAddrBookCommand( mUrlClicked,
02390                                mMainWindow);
02391   command->start();
02392 }
02393 
02394 //-----------------------------------------------------------------------------
02395 void KMReaderWin::slotMailtoOpenAddrBook()
02396 {
02397   KMCommand *command = new KMMailtoOpenAddrBookCommand( mUrlClicked,
02398                             mMainWindow );
02399   command->start();
02400 }
02401 
02402 //-----------------------------------------------------------------------------
02403 void KMReaderWin::slotUrlCopy()
02404 {
02405   // we don't necessarily need a mainWidget for KMUrlCopyCommand so
02406   // it doesn't matter if the dynamic_cast fails.
02407   KMCommand *command =
02408     new KMUrlCopyCommand( mUrlClicked,
02409                           dynamic_cast<KMMainWidget*>( mMainWindow ) );
02410   command->start();
02411 }
02412 
02413 //-----------------------------------------------------------------------------
02414 void KMReaderWin::slotUrlOpen( const KURL &url )
02415 {
02416   if ( !url.isEmpty() )
02417     mUrlClicked = url;
02418   KMCommand *command = new KMUrlOpenCommand( mUrlClicked, this );
02419   command->start();
02420 }
02421 
02422 //-----------------------------------------------------------------------------
02423 void KMReaderWin::slotAddBookmarks()
02424 {
02425     KMCommand *command = new KMAddBookmarksCommand( mUrlClicked, this );
02426     command->start();
02427 }
02428 
02429 //-----------------------------------------------------------------------------
02430 void KMReaderWin::slotUrlSave()
02431 {
02432   KMCommand *command = new KMUrlSaveCommand( mUrlClicked, mMainWindow );
02433   command->start();
02434 }
02435 
02436 //-----------------------------------------------------------------------------
02437 void KMReaderWin::slotMailtoReply()
02438 {
02439   KMCommand *command = new KMMailtoReplyCommand( mMainWindow, mUrlClicked,
02440     message(), copyText() );
02441   command->start();
02442 }
02443 
02444 //-----------------------------------------------------------------------------
02445 partNode * KMReaderWin::partNodeFromUrl( const KURL & url ) {
02446   return mRootNode ? mRootNode->findId( msgPartFromUrl( url ) ) : 0 ;
02447 }
02448 
02449 partNode * KMReaderWin::partNodeForId( int id ) {
02450   return mRootNode ? mRootNode->findId( id ) : 0 ;
02451 }
02452 
02453 //-----------------------------------------------------------------------------
02454 void KMReaderWin::slotSaveAttachments()
02455 {
02456   mAtmUpdate = true;
02457   KMSaveAttachmentsCommand *saveCommand = new KMSaveAttachmentsCommand( mMainWindow,
02458                                                                         message() );
02459   saveCommand->start();
02460 }
02461 
02462 //-----------------------------------------------------------------------------
02463 void KMReaderWin::slotSaveMsg()
02464 {
02465   KMSaveMsgCommand *saveCommand = new KMSaveMsgCommand( mMainWindow, message() );
02466 
02467   if (saveCommand->url().isEmpty())
02468     delete saveCommand;
02469   else
02470     saveCommand->start();
02471 }
02472 //-----------------------------------------------------------------------------
02473 void KMReaderWin::slotIMChat()
02474 {
02475   KMCommand *command = new KMIMChatCommand( mUrlClicked, message() );
02476   command->start();
02477 }
02478 
02479 //-----------------------------------------------------------------------------
02480 QString KMReaderWin::createAtmFileLink() const
02481 {
02482   QFileInfo atmFileInfo(mAtmCurrentName);
02483 
02484   KTempFile *linkFile = new KTempFile( locateLocal("tmp", atmFileInfo.fileName() +"_["),
02485                           "]."+ atmFileInfo.extension() );
02486 
02487   linkFile->setAutoDelete(true);
02488   QString linkName = linkFile->name();
02489   delete linkFile;
02490 
02491   if ( link(QFile::encodeName(mAtmCurrentName), QFile::encodeName(linkName)) == 0 ) {
02492     return linkName; // success
02493   }
02494   kdWarning(5006) << "Couldn't link to " << mAtmCurrentName << endl;
02495   return QString::null;
02496 }
02497 
02498 //-----------------------------------------------------------------------------
02499 bool KMReaderWin::eventFilter( QObject *, QEvent *e )
02500 {
02501   if ( e->type() == QEvent::MouseButtonPress ) {
02502     QMouseEvent* me = static_cast<QMouseEvent*>(e);
02503     if ( me->button() == LeftButton && ( me->state() & ShiftButton ) ) {
02504       // special processing for shift+click
02505       mAtmCurrent = msgPartFromUrl( mUrlClicked );
02506       if ( mAtmCurrent < 0 ) return false; // not an attachment
02507       mAtmCurrentName = mUrlClicked.path();
02508       slotHandleAttachment( KMHandleAttachmentCommand::Save ); // save
02509       return true; // eat event
02510     }
02511   }
02512   // standard event processing
02513   return false;
02514 }
02515 
02516 #include "kmreaderwin.moc"
02517 
02518 
KDE Home | KDE Accessibility Home | Description of Access Keys