Revision: 201015 RCL_3 PDK_3.0.i
authorDremov Kirill (Nokia-D-MSW/Tampere) <kirill.dremov@nokia.com>
Tue, 27 Apr 2010 16:20:14 +0300
branchRCL_3
changeset 19 b13141f05c3d
parent 17 8592a65ad3fb
child 24 b5fbb9b25d57
Revision: 201015 Kit: 201017
email_plat/email_crkeys_api/inc/commonemailcrkeys.h
emailcontacts/contactactionmenu/src/cfsccontactactionmenulist.cpp
emailservices/emailframework/commonlib/src/CFSMailBox.cpp
emailservices/emailframework/commonlib/src/CFSMailMessageBase.cpp
emailservices/emailserver/cmailhandlerplugin/inc/cmailcpshandler.h
emailservices/emailserver/cmailhandlerplugin/inc/cmailcpsif.h
emailservices/emailserver/cmailhandlerplugin/inc/cmailcpssettings.h
emailservices/emailserver/cmailhandlerplugin/src/cmailcpshandler.cpp
emailservices/emailserver/cmailhandlerplugin/src/cmailcpsif.cpp
emailservices/emailserver/cmailhandlerplugin/src/cmailcpssettings.cpp
emailservices/emailserver/cmailhandlerplugin/src/cmailpluginproxy.cpp
emailservices/emailstore/base_plugin/group/BasePlugin.mmp
emailservices/emailstore/base_plugin/inc/NestedAO.h
emailservices/emailstore/base_plugin/inc/baseplugindelayedopsprivate.h
emailservices/emailstore/base_plugin/src/NestedAO.cpp
emailservices/emailstore/base_plugin/src/baseplugindelayedops.cpp
emailuis/emailui/data/html/email_rtl.html
emailuis/emailui/inc/FreestyleEmailUiHtmlViewerView.h
emailuis/emailui/inc/FreestyleEmailUiLayoutHandler.h
emailuis/emailui/inc/FreestyleEmailUiSendAttachmentsListControl.h
emailuis/emailui/inc/ncsaddressinputfield.h
emailuis/emailui/inc/ncscomposeview.h
emailuis/emailui/inc/ncscomposeviewcontainer.h
emailuis/emailui/inc/ncseditor.h
emailuis/emailui/inc/ncseditorcustomdraw.h
emailuis/emailui/inc/ncsheadercontainer.h
emailuis/emailui/inc/ncspopuplistbox.h
emailuis/emailui/inc/ncssubjectfield.h
emailuis/emailui/src/FreestyleEmailUiCLSListsHandler.cpp
emailuis/emailui/src/FreestyleEmailUiHtmlViewerContainer.cpp
emailuis/emailui/src/FreestyleEmailUiHtmlViewerView.cpp
emailuis/emailui/src/FreestyleEmailUiMailListVisualiser.cpp
emailuis/emailui/src/FreestyleEmailUiSendAttachmentsListControl.cpp
emailuis/emailui/src/FreestyleEmailUiViewBase.cpp
emailuis/emailui/src/FreestyleMessageHeaderHTML.cpp
emailuis/emailui/src/ncsaddressinputfield.cpp
emailuis/emailui/src/ncsattachmentfield.cpp
emailuis/emailui/src/ncscomposeview.cpp
emailuis/emailui/src/ncscomposeviewcontainer.cpp
emailuis/emailui/src/ncseditor.cpp
emailuis/emailui/src/ncseditorcustomdraw.cpp
emailuis/emailui/src/ncsheadercontainer.cpp
emailuis/emailui/src/ncspopuplistbox.cpp
emailuis/emailui/src/ncssubjectfield.cpp
emailuis/uicomponents/group/fs_generic.mmp
emailuis/uicomponents/inc/cuicscrollbar.h
emailuis/uicomponents/src/cuicscrollbar.cpp
emailuis/uicomponents/src/fstreeplaintwolineitemvisualizer.cpp
emailuis/widget/emailwidgetsettings/src/emailwidgetsettingsappui.cpp
help/data/xhtml.zip
help/inc/cmail.hlp.hrh
ipsservices/ipssosplugin/inc/ipsplgsosbaseplugin.h
ipsservices/ipssosplugin/src/ipsplgmsgmapper.cpp
ipsservices/ipssosplugin/src/ipsplgsosbaseplugin.cpp
meetingrequest/mrdb/inc/cesmrcaldbmgr.h
meetingrequest/mrdb/src/cesmrcaldbmgr.cpp
meetingrequest/mrentry/inc/cesmrfsmailboxutils.h
meetingrequest/mrentry/inc/cesmrmeetingrequestentry.h
meetingrequest/mrentry/src/cesmrfsmailboxutils.cpp
meetingrequest/mrentry/src/cesmrmeetingrequestentry.cpp
meetingrequest/mrgui/mrfieldbuildercommon/src/cesmrrichtextviewer.cpp
meetingrequest/mrgui/mrfieldbuilderplugin/src/cesmrvieweralldayeventfield.cpp
meetingrequest/mrgui/mrfieldbuilderplugin/src/cesmrviewerdescriptionfield.cpp
meetingrequest/mrgui/mrfieldbuilderplugin/src/cesmrviewerdetailedsubjectfield.cpp
meetingrequest/mrgui/mrfieldbuilderplugin/src/cesmrviewerlocationfield.cpp
meetingrequest/mrgui/mrfieldbuilderpluginextension/src/cesmrviewerattendeesfield.cpp
--- a/email_plat/email_crkeys_api/inc/commonemailcrkeys.h	Wed Apr 14 15:42:15 2010 +0300
+++ b/email_plat/email_crkeys_api/inc/commonemailcrkeys.h	Tue Apr 27 16:20:14 2010 +0300
@@ -2,7 +2,7 @@
 * Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 * This component and the accompanying materials are made available
-* under the terms of the License "Eclipse Public License v1.0"
+* under the terms of "Eclipse Public License v1.0"
 * which accompanies this distribution, and is available
 * at the URL "http://www.eclipse.org/legal/epl-v10.html".
 *
--- a/emailcontacts/contactactionmenu/src/cfsccontactactionmenulist.cpp	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailcontacts/contactactionmenu/src/cfsccontactactionmenulist.cpp	Tue Apr 27 16:20:14 2010 +0300
@@ -27,14 +27,14 @@
 #include <coeaui.h>
 #include <coefontprovider.h>
 #include <gulfont.h>
-#include <aknbiditextutils.h> 
-#include <aknlayoutfont.h> 
-#include <aknlayout2scalabledatadef.h>
+#include <AknBidiTextUtils.h> 
+#include <AknLayoutFont.h> 
+#include <AknLayout2ScalableDataDef.h>
 #include <aknlayout2scalabledef.h>
 #include <layoutmetadata.cdl.h>
-#include <cdlengine.h>
+#include <CdlEngine.h>
 #include <coemain.h>
-#include <aknslistboxbackgroundcontrolcontext.h> 
+#include <AknsListBoxBackgroundControlContext.h> 
 
 #include <aknlayoutscalable_apps.cdl.h>
 #include <layoutmetadata.cdl.h>
--- a/emailservices/emailframework/commonlib/src/CFSMailBox.cpp	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailservices/emailframework/commonlib/src/CFSMailBox.cpp	Tue Apr 27 16:20:14 2010 +0300
@@ -69,6 +69,18 @@
 EXPORT_C CFSMailBox::~CFSMailBox()
 {
     FUNC_LOG;
+    // extension KMailboxExtMrCalInfo needs to be released here because of
+    // MR UI
+    CEmailExtension* extension = NULL;
+    TRAPD( err, extension = CExtendableEmail::ExtensionL( KMailboxExtMrCalInfo ) );
+    if( extension != NULL && err==KErrNone )
+        {
+        // Release extension needs to be called twice because, previous
+        // CExtendableEmail::ExtensionL( KMailboxExtMrCalInfo ) call increased
+        // reference counter with one, so there is need to relase this one also.
+        CExtendableEmail::ReleaseExtension( extension );
+        CExtendableEmail::ReleaseExtension( extension );
+        }
     iFolders.ResetAndDestroy();
 }
 
@@ -361,6 +373,7 @@
 {
     FUNC_LOG;
     TFSPendingRequest request;
+    request.iRequestId = 0;
     if( CFSMailPlugin* plugin = iRequestHandler->GetPluginByUid( GetId() ) )
         {
         // init asynchronous request
@@ -827,8 +840,20 @@
 EXPORT_C void CFSMailBox::ReleaseExtension( CEmailExtension* aExtension )
     {
     FUNC_LOG;
-    // no specialized behaviour, call base class
-    CExtendableEmail::ReleaseExtension( aExtension );
+    // MR UI needs KMailboxExtMrCalInfo to not be released until CFSMailBox 
+    // exists. It is released in desctrucor
+    if( aExtension->Uid() != KMailboxExtMrCalInfo )
+        {
+        // no specialized behaviour, call base class
+        CExtendableEmail::ReleaseExtension( aExtension );
+        }
+    else
+        {
+        if( !aExtension->DecRef() )
+            {
+            aExtension->IncRef();
+            }
+        }
     }
     
 // -----------------------------------------------------------------------------
--- a/emailservices/emailframework/commonlib/src/CFSMailMessageBase.cpp	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailservices/emailframework/commonlib/src/CFSMailMessageBase.cpp	Tue Apr 27 16:20:14 2010 +0300
@@ -88,6 +88,12 @@
 		iSubject = NULL;
 		}
 
+    if(iReplyTo)
+        {
+        delete iReplyTo;
+        iReplyTo = NULL;
+        }
+	
 	// clear recipients lists
 	iToRecipients.ResetAndDestroy();		
 	iCcRecipients.ResetAndDestroy();
--- a/emailservices/emailserver/cmailhandlerplugin/inc/cmailcpshandler.h	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailservices/emailserver/cmailhandlerplugin/inc/cmailcpshandler.h	Tue Apr 27 16:20:14 2010 +0300
@@ -69,6 +69,11 @@
     virtual void SettingsChangedCallback();
 
     /**
+     *
+     */
+    void SetUpdateNeeded( const TFSMailMsgId aMailbox );
+    
+    /**
      * Wraps all "Update*" methods
      */
     void UpdateFullL();    
@@ -168,6 +173,12 @@
      */
     void DisplayHSPageFullNoteL();
         
+    /**
+     * get count of unread messages in inbox
+     * @param aMailbox mailbox id
+     */    
+    TInt GetUnreadCountL( TFSMailMsgId aMailbox);
+
 protected:
     /**
      * From CFSNotificationHandlerBase
@@ -303,12 +314,6 @@
     void HandleMailDeletedEventL( TFSMailMsgId aMailbox, TAny* aParam1, TAny* aParam2 );
 
     /**
-     * get count of unread messages in inbox
-     * @param aMailbox mailbox id
-     */    
-    TInt GetUnreadCountL( TFSMailMsgId aMailbox);
-
-    /**
      * get count of unseen messages in inbox
      * @param aMailbox mailbox id
      */    
--- a/emailservices/emailserver/cmailhandlerplugin/inc/cmailcpsif.h	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailservices/emailserver/cmailhandlerplugin/inc/cmailcpsif.h	Tue Apr 27 16:20:14 2010 +0300
@@ -34,6 +34,18 @@
 #include "cmailcpsifconsts.h"
 
 /**
+*
+*/
+class TInstIdInfo
+	{
+public:
+    TBuf<KMaxDescLen> iCid;
+	TBool             iUpdateNeeded;
+	TBool             iWizardPublished;
+	};
+
+
+/**
  *  CMail ContentPublishingService interface class
  *  Class implementing interface towards LIW FW and Content Publishing Service
  *
@@ -181,6 +193,20 @@
      * 
      */	
 	void AddWidgetToHomescreenL( const TFSMailMsgId aMailbox );
+    /**
+     * 
+     */
+    TInt GetWidgetInstanceId(const TDesC& aContentId);
+
+    /**
+     * 
+     */
+    void SetUpdateNeeded( const TInt aInstance, const TBool aValue );
+
+    /**
+     * 
+     */
+    TBool UpdateNeeded( const TInt aInstance );
 
 private:
     
@@ -249,11 +275,6 @@
     void RemoveL( TUint aId );
 
     /**
-     * 
-     */	    
-    TInt FindWidgetInstanceId(const TDesC& aContentId);
-
-    /**
      * Resets all the published content values on HomeScreen database
      */
     void ResetPublishedDataL( const TDesC& aContentId );
@@ -267,30 +288,30 @@
     
 public:
 	//
-    RPointerArray<HBufC>    iInstIdList;
+    RArray<TInstIdInfo>     iInstIdList;
 private:
-	CMailCpsHandler*		iMailCpsHandler; //uses
+    CMailCpsHandler*        iMailCpsHandler; //uses
     // LIW IF
-    MLiwInterface* 			iMsgInterface;
+    MLiwInterface*          iMsgInterface;
     // LIW Service handler
-    CLiwServiceHandler* 	iServiceHandler;
+    CLiwServiceHandler*     iServiceHandler;
     // resource file offset
     TInt                    iResourceFileOffset;
     // UIDS of the published entities
-    TUint 					iMailboxNameUid;
+    TUint                   iMailboxNameUid;
     // message count of a mailbox
-    TUint 					iMessageCountUid;
+    TUint                   iMessageCountUid;
     // row count
-    TUint 					iRowCountUid;
+    TUint                   iRowCountUid;
     // message header details id
-    TUint 					iMsgUid;
+    TUint                   iMsgUid;
     // setup text and action id
-    TUint 					iSetupUid;
-	// is content allowed to publish	
-	TBool 					iAllowedToPublish[KMaxMailboxCount];
-	// From configuration: are homescreen notifications observed or ignored
-	TBool                   iIgnoreHsNotifications;
-	
+    TUint                   iSetupUid;
+    // is content allowed to publish	
+    TBool                   iAllowedToPublish[KMaxMailboxCount];
+    // From configuration: are homescreen notifications observed or ignored
+    TBool                   iIgnoreHsNotifications;
+    //
 	CHsCcApiClient*         iContentControlClient;
     };
 
--- a/emailservices/emailserver/cmailhandlerplugin/inc/cmailcpssettings.h	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailservices/emailserver/cmailhandlerplugin/inc/cmailcpssettings.h	Tue Apr 27 16:20:14 2010 +0300
@@ -83,6 +83,7 @@
      * Gets array of external mailboxes from widget settings
      * @param aAccounts on completion, contains the necessary information of
      * external mailboxes that currently should have a widget
+     * transfers ownership of accounts to caller
      */
     void GetExtMailboxesL( RPointerArray<CMailExternalAccount>& aAccounts );
 
@@ -132,6 +133,11 @@
     
     /**
      * 
+     */    
+    TInt WidgetCountByMailbox( TInt aMailboxId );
+    
+    /**
+     * 
      */	
 	TBool IsSelected( TInt aId );
 	
@@ -180,7 +186,7 @@
     /**
      *
      */    
-    TBool GetNewMailState( const TFSMailMsgId& aMailBox );
+    TBool GetNewMailStateL( const TFSMailMsgId& aMailBox, TInt aUnreadCount );
 
     /**
      * Find next free CenRep key to store setting.
@@ -244,6 +250,15 @@
     TInt ResolveMailbox( const TInt aMailboxId, TFSMailMsgId& aMsg ); 
 
     /**
+     * Finds mailbox if plugin id is set - more efficient than Resolve mailbox
+     * 
+     * @param aMsg      mailbox both PluginId and Id is checked
+     * @return KErrNone if mailbox exists  
+     * @return KErrNotFound aMsg.Id() points to non-existent mailbox
+     **/
+    TInt CheckMailboxExistence( TFSMailMsgId& aMsg );
+
+    /**
      * Gets array of CenRep keys representing mailboxes configured to widget
      * @param aKeys array of keys
      */
@@ -263,6 +278,7 @@
     TInt GetSettingToAssociate( const TDesC& aContentId );
 
     /**
+     * Returns CMailExternalAccount::NewL() according to cenrep key aKey
      * @param aKey
      */
     CMailExternalAccount* GetExtMailboxL( TInt aKey );
--- a/emailservices/emailserver/cmailhandlerplugin/src/cmailcpshandler.cpp	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailservices/emailserver/cmailhandlerplugin/src/cmailcpshandler.cpp	Tue Apr 27 16:20:14 2010 +0300
@@ -27,6 +27,8 @@
 #include <memaildata.h>
 #include <memailmailboxdata.h>
 
+#include <scs/cleanuputils.h> // CleanupResetAndDestroyPushL
+
 #include "emailtrace.h"
 #include "cfsmailclient.h"
 #include "cfsmailbox.h"
@@ -130,9 +132,10 @@
     FUNC_LOG;
     // Get current configuration from settings interface,
     // and pass it on to actual publisher interface
+        
     iLiwIf->SetConfiguration( iSettings->Configuration() );
-
     TInt iiMax( iSettings->Mailboxes().Count() );
+    INFO_1("iSettings->Mailboxes().Count() = %d", iiMax );
     for ( TInt ii = 0; ii < iiMax; ii++ )
         {
         CFSMailBox* mailbox( NULL );
@@ -141,33 +144,34 @@
         TInt mailboxId(0);
         if (mailbox)
             {
+            CleanupStack::PushL( mailbox );
             mailboxId = mailbox->GetId().Id();
-            }
-        if ( mailboxId )
-            {
-            CleanupStack::PushL( mailbox );
-            CMailMailboxDetails* mailboxDetails = CreateMailboxDetailsL( *mailbox );
-            CleanupStack::PushL( mailboxDetails );
-
-            TBuf<KMaxDescLen> cid;
-            TInt next(1);
-
-            // Check if same mailbox is already in iAccountsArray once or more
-            for ( TInt i = 0; i < iAccountsArray.Count(); i++ )
+            if ( mailboxId )
                 {
-                TInt id = (TInt)iAccountsArray[i]->iMailboxId.Id();
-                if (id == mailboxId)
+                CMailMailboxDetails* mailboxDetails = CreateMailboxDetailsL( *mailbox );
+                CleanupStack::PushL( mailboxDetails );
+    
+                TBuf<KMaxDescLen> cid;
+                TInt next(1);
+    
+                // Check if same mailbox is already in iAccountsArray once or more
+                for ( TInt i = 0; i < iAccountsArray.Count(); i++ )
                     {
-                    next++;
+                    TInt id = (TInt)iAccountsArray[i]->iMailboxId.Id();
+                    if (id == mailboxId)
+                        {
+                        next++;
+                        }
                     }
+                iSettings->GetContentId(mailboxId, next, cid);
+                mailboxDetails->SetWidgetInstance(cid);
+                iAccountsArray.AppendL( mailboxDetails );
+                CleanupStack::Pop( mailboxDetails );
                 }
-            iSettings->GetContentId(mailboxId, next, cid);
-            mailboxDetails->SetWidgetInstance(cid);
-            iAccountsArray.AppendL( mailboxDetails );
-            CleanupStack::Pop( mailboxDetails );
             CleanupStack::PopAndDestroy( mailbox );
             }
         }
+     INFO_1("iAccountsArray.Count() = %d", iAccountsArray.Count() );
     }
 
 // ---------------------------------------------------------
@@ -179,7 +183,7 @@
     FUNC_LOG;
     // Read external account data from settings
     RPointerArray<CMailExternalAccount> extAccounts;
-    CleanupClosePushL( extAccounts );
+    CleanupResetAndDestroyPushL( extAccounts );  // owning - GetExtMailboxesL transfers ownership
     iSettings->GetExtMailboxesL( extAccounts );
 
     // Delete removed plugins
@@ -192,7 +196,7 @@
     SelectAndUpdateExtAccountsL( extAccounts );
 
     __ASSERT_DEBUG( extAccounts.Count() == 0, Panic( ECmailHandlerPluginPanicNoFailedState ) );
-    CleanupStack::PopAndDestroy();
+    CleanupStack::PopAndDestroy( &extAccounts );
     }
 
 // ---------------------------------------------------------
@@ -309,11 +313,32 @@
     TRAP_IGNORE( InitializeL() );
     TRAP_IGNORE( InitializeExternalAccountsL() );
     // Update widget contents after settings change
+    TInt count = iLiwIf->GetWidgetInstanceCount();
+    for (TInt i = 0; i < count; i++ )
+        {
+        iLiwIf->SetUpdateNeeded( i, ETrue );
+        }
     TRAP_IGNORE( UpdateFullL() );
     CleanWaitingForNewMailbox();
     }
 
 // ---------------------------------------------------------
+// CMailCpsHandler::SetUpdateNeeded
+// ---------------------------------------------------------
+//
+void CMailCpsHandler::SetUpdateNeeded( const TFSMailMsgId aMailbox )
+    {
+    FUNC_LOG;
+    TInt count = iSettings->WidgetCountByMailbox( aMailbox.Id() );
+    for (TInt i = 0; i < count; i++ )
+        {
+        TBuf<KMaxDescLen> cid;
+        iSettings->GetContentId( aMailbox.Id(), i + 1, cid );
+        iLiwIf->SetUpdateNeeded( iLiwIf->GetWidgetInstanceId( cid ), ETrue );
+        }
+    }
+
+// ---------------------------------------------------------
 // CMailCpsHandler::UpdateFullL
 // ---------------------------------------------------------
 //
@@ -324,7 +349,7 @@
         {
         if ( iLiwIf->AllowedToPublish(instance) )
             {
-            UpdateMailboxesL(instance, iLiwIf->iInstIdList[instance]->Des());
+            UpdateMailboxesL(instance, iLiwIf->iInstIdList[instance].iCid);
             }
         }
     }
@@ -344,45 +369,51 @@
         plugin->UpdateAccountL( aContentId );
         }
     else // handle internal accounts
-        {   
-        TInt row(1); // start from first row
-        TInt mailbox(0);
-        TBool found( EFalse );
-        // try to find mailbox with matching contentId
-        for ( mailbox = 0; mailbox < iAccountsArray.Count(); mailbox++ )
-            {
-            if ( !aContentId.Compare( *iAccountsArray[mailbox]->iWidgetInstance ) )
-                {
-                INFO_1("iAccountsArray.Count() == %d", iAccountsArray.Count());
-                found = ETrue;
-                break;
-                }
-            }
-
-        // if contentId found from array, update the mailbox
-        if ( found )
+        {
+        if ( iLiwIf->UpdateNeeded( aInstance ) )
             {
-            // Update fields from left to right
-            UpdateMailBoxIconL( mailbox, aInstance, row );
-            UpdateMailboxNameL( mailbox, aInstance, row );
-            UpdateIndicatorIconL( mailbox, aInstance, row );
-            row++;
-            UpdateMessagesL( mailbox, aInstance, 1, row);
-            row++;
-            UpdateMessagesL( mailbox, aInstance, 2, row);
-            }
-        else
-            {
-            // Clean mailbox name
-            iLiwIf->PublishActiveMailboxNameL( aInstance, 1, KNullDesC );
-            // Clean mailbox icon
-            TFSMailMsgId mailBoxId; // id not essential here        
-            iLiwIf->PublishMailboxIconL( aInstance, 1, KNullIcon, mailBoxId);
-            // Clean indicator icon
-            iLiwIf->PublishIndicatorIconL( aInstance, 1, KNullIcon);
-            // Clean message rows
-            UpdateEmptyMessagesL( aInstance, 2 );
-            UpdateEmptyMessagesL( aInstance, 3 );
+            TInt row(1); // start from first row
+            TInt mailbox(0);
+            TBool found( EFalse );
+            // try to find mailbox with matching contentId
+            for ( mailbox = 0; mailbox < iAccountsArray.Count(); mailbox++ )
+                {
+                if ( !aContentId.Compare( *iAccountsArray[mailbox]->iWidgetInstance ) )
+                    {
+                    INFO_1("iAccountsArray[mailbox] mailbox = %d", mailbox);
+                    found = ETrue;
+                    break;
+                    }
+                }
+
+            // if contentId found from array, update the mailbox
+            if ( found )
+                {
+                 INFO_1("found = TRUE iAccountsArray.Count() == %d", iAccountsArray.Count());
+                // Update fields from left to right
+                UpdateMailBoxIconL( mailbox, aInstance, row );
+                UpdateMailboxNameL( mailbox, aInstance, row );
+                UpdateIndicatorIconL( mailbox, aInstance, row );
+                row++;
+                UpdateMessagesL( mailbox, aInstance, 1, row);
+                row++;
+                UpdateMessagesL( mailbox, aInstance, 2, row);
+                }
+            else
+                {
+                INFO_1("found = FALSE iAccountsArray.Count() == %d", iAccountsArray.Count());
+                // Clean mailbox name
+                iLiwIf->PublishActiveMailboxNameL( aInstance, 1, KNullDesC );
+                // Clean mailbox icon
+                TFSMailMsgId mailBoxId; // id not essential here        
+                iLiwIf->PublishMailboxIconL( aInstance, 1, KNullIcon, mailBoxId);
+                // Clean indicator icon
+                iLiwIf->PublishIndicatorIconL( aInstance, 1, KNullIcon);
+                // Clean message rows
+                UpdateEmptyMessagesL( aInstance, 2 );
+                UpdateEmptyMessagesL( aInstance, 3 );
+                }
+            iLiwIf->SetUpdateNeeded( aInstance, EFalse );
             }
         }
     }
@@ -478,10 +509,11 @@
         mailBoxId = iAccountsArray[aMailBoxNumber]->iMailboxId;
 
         CFSMailBox* mailbox( NULL );
-        mailbox = MailClient().GetMailBoxByUidL( mailBoxId );
+        mailbox = MailClient().GetMailBoxByUidL( mailBoxId ); // transferred ownership
         if(mailbox)
             {
             TFSMailMsgId parentFolder( mailbox->GetStandardFolderId( EFSInbox ) );
+            delete mailbox;
             // Check that folder is correct
             CFSMailFolder* folder = MailClient().GetFolderByUidL( mailBoxId, parentFolder );
             if ( !folder )
@@ -504,7 +536,7 @@
 
             // Update folder if provided, otherwise use current folder
             RPointerArray<CFSMailMessage> folderMessages(1);
-            CleanupClosePushL( folderMessages );
+            CleanupResetAndDestroyPushL( folderMessages ); // owning array, from emailapiutils.h
 
             TFSMailDetails details( EFSMsgDataEnvelope );
             RArray<TFSMailSortCriteria> sorting;
@@ -529,7 +561,6 @@
                 CleanupStack::PopAndDestroy( &sorting );
                 CleanupStack::PopAndDestroy( &folderMessages );
                 CleanupStack::PopAndDestroy( folder );
-
                 return;
                 }
             TFSMailMsgId msgId = folderMessages[aMessageNumber - 1]->GetMessageId();
@@ -733,13 +764,12 @@
         TFSMailMsgId mailBoxId;
         mailBoxId = iAccountsArray[aMailBoxNumber]->iMailboxId;
 
-        if ( iSettings->GetNewMailState( mailBoxId ) )
+        if ( iSettings->GetNewMailStateL( mailBoxId, GetUnreadCountL(mailBoxId) ) )
             {
             iLiwIf->PublishIndicatorIconL( aWidgetInstance,
                                            aRowNumber,
                                            EMbmCmailhandlerpluginQgn_stat_message_mail_uni );
             }
-
         else if( !IsOutboxEmptyL(mailBoxId) )
             {
             iLiwIf->PublishIndicatorIconL( aWidgetInstance,
@@ -820,27 +850,37 @@
         case TFSEventMailboxRenamed:
             {
             HandleMailboxRenamedEventL( aMailbox );
+            SetUpdateNeeded( aMailbox );
             UpdateFullL();
             break;
             }
         case TFSEventMailboxDeleted:
             {
             HandleMailboxDeletedEventL( aMailbox );
+            SetUpdateNeeded( aMailbox );
             UpdateFullL();
             break;
             }
         case TFSEventNewMail:
             {
             HandleNewMailEventL( aMailbox, aParam1, aParam2 );
+            SetUpdateNeeded( aMailbox );
             UpdateFullL();
             break;
             }
         case TFSEventMailDeleted:
             {
             HandleMailDeletedEventL( aMailbox, aParam1, aParam2 );
+            SetUpdateNeeded( aMailbox );
             UpdateFullL();
             break;
             }
+        case TFSEventMailChanged:
+            {
+            SetUpdateNeeded( aMailbox );
+            UpdateFullL();
+            break;
+            }            
         default:
             {
             break;
@@ -1083,6 +1123,7 @@
     if(mailbox)
         {
         TFSMailMsgId folderId( mailbox->GetStandardFolderId( EFSInbox ) );
+        delete mailbox; // transferred ownership
         // Check that folder is correct
         CFSMailFolder* folder = MailClient().GetFolderByUidL( aMailbox, folderId );
         if ( !folder )
@@ -1117,6 +1158,7 @@
     if(mailbox)
         {
         TFSMailMsgId folderId( mailbox->GetStandardFolderId( EFSInbox ) );
+        delete mailbox; // transferred ownership
         // Check that folder is correct
         CFSMailFolder* folder = MailClient().GetFolderByUidL( aMailbox, folderId );
         if ( !folder )
@@ -1152,6 +1194,7 @@
     if(mailbox)
         {
         TFSMailMsgId folderId( mailbox->GetStandardFolderId( EFSOutbox ) );
+        delete mailbox; // ownership was transferred
         // Check that folder is correct
         CFSMailFolder* folder = MailClient().GetFolderByUidL( aMailbox, folderId );
         if ( !folder )
@@ -1181,7 +1224,7 @@
         CleanupDeletePushL( iterator );
 
         RPointerArray<CFSMailMessage> messages;
-        CleanupClosePushL( messages );
+        CleanupResetAndDestroyPushL( messages ); // owning array
         iterator->NextL( TFSMailMsgId(), msgCount, messages );
 
         TInt arrayCount(messages.Count());
@@ -1774,7 +1817,7 @@
     TInt totalMailboxCount( 0 );
     TUid interfaceUid = TUid::Uid( KEmailObserverInterfaceUid );
     RImplInfoPtrArray plugins;
-    CleanupClosePushL( plugins );
+    CleanupResetAndDestroyPushL(plugins); // CleanupClosePushL does not call ptr destructors
     REComSession::ListImplementationsL( interfaceUid, plugins);
 
     for ( TInt i = 0; i < plugins.Count(); i++ )
@@ -1787,7 +1830,7 @@
         totalMailboxCount += data.MailboxesL().Count();
         }
 
-    CleanupStack::PopAndDestroy(); // plugins
+    CleanupStack::PopAndDestroy( &plugins ); // plugins
     return totalMailboxCount;
     }
 
--- a/emailservices/emailserver/cmailhandlerplugin/src/cmailcpsif.cpp	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailservices/emailserver/cmailhandlerplugin/src/cmailcpsif.cpp	Tue Apr 27 16:20:14 2010 +0300
@@ -95,7 +95,10 @@
         iMsgInterface = NULL;
         }
     delete iServiceHandler;
-    iInstIdList.ResetAndDestroy();  
+    for ( TInt i = 0; i < iInstIdList.Count(); i++ )
+        {
+        iInstIdList.Remove(i);
+        }
     CCoeEnv::Static()->DeleteResourceFile( iResourceFileOffset );
     if ( iContentControlClient ) 
         {
@@ -180,22 +183,24 @@
 // CMailCpsIf::PublishSetupWizardL
 // ---------------------------------------------------------------------------
 //
-void CMailCpsIf::PublishSetupWizardL(TInt instance)
+void CMailCpsIf::PublishSetupWizardL(TInt aInstance)
     {
     FUNC_LOG;
-    TFSMailMsgId mailBoxId;
-    TFSMailMsgId folderId;
-
-    HBufC* setupEmail = StringLoader::LoadLC(R_EMAILWIDGET_TEXT_SETUP_EMAIL);
+    if (!iInstIdList[aInstance].iWizardPublished)
+        {
+        TFSMailMsgId mailBoxId;
+        TFSMailMsgId folderId;
     
-    iSetupUid = PublishDescriptorL(
+       HBufC* setupEmail = StringLoader::LoadLC(R_EMAILWIDGET_TEXT_SETUP_EMAIL);
+    
+        iSetupUid = PublishDescriptorL(
             KPubId, KContTypeSetupText,
-            iInstIdList[instance]->Des(),
+            iInstIdList[aInstance].iCid,
             *setupEmail, 
-            KKeySetupText, KTriggerWizard8);	
+            KKeySetupText, KTriggerWizard8);
 
-    PublishImageL(
-            iInstIdList[instance]->Des(),
+        PublishImageL(
+            iInstIdList[aInstance].iCid,
             KContTypeSetupIcon,
             KKeySetupIcon,
             EMbmCmailhandlerpluginQgn_prop_cmail_new_mailbox,
@@ -203,8 +208,8 @@
             mailBoxId,
             KNullDes);
             
-    PublishImageL(
-            iInstIdList[instance]->Des(),
+        PublishImageL(
+            iInstIdList[aInstance].iCid,
             KContTypeSetupBrandIcon1,
             KKeySetupBrandIcon1,
             EMbmCmailhandlerpluginQgn_indi_cmail_drop_email_account,
@@ -212,8 +217,8 @@
             mailBoxId,
             KSetupBrand1);
 
-    PublishImageL(
-            iInstIdList[instance]->Des(),
+        PublishImageL(
+            iInstIdList[aInstance].iCid,
             KContTypeSetupBrandIcon2,
             KKeySetupBrandIcon2,
             EMbmCmailhandlerpluginQgn_indi_cmail_drop_email_account,
@@ -221,8 +226,8 @@
             mailBoxId,
             KSetupBrand2);
 
-    PublishImageL(
-            iInstIdList[instance]->Des(),
+        PublishImageL(
+            iInstIdList[aInstance].iCid,
             KContTypeSetupBrandIcon3,
             KKeySetupBrandIcon3,
             EMbmCmailhandlerpluginQgn_indi_cmail_drop_email_account,
@@ -230,16 +235,17 @@
             mailBoxId,
             KSetupBrand3);
 
-    PublishImageL(
-            iInstIdList[instance]->Des(),
+        PublishImageL(
+            iInstIdList[aInstance].iCid,
             KContTypeSetupBrandIcon4,
             KKeySetupBrandIcon4,
             EMbmCmailhandlerpluginQgn_indi_cmail_drop_email_account,
             EMbmCmailhandlerpluginQgn_indi_cmail_drop_email_account_mask,
             mailBoxId,
-            KSetupBrand4);            
-
-    CleanupStack::PopAndDestroy(setupEmail);    
+            KSetupBrand4);
+        iInstIdList[aInstance].iWizardPublished = ETrue;
+        CleanupStack::PopAndDestroy(setupEmail);
+        }        
     }
 
 // ---------------------------------------------------------------------------
@@ -266,7 +272,7 @@
 		
     iMailboxNameUid = PublishDescriptorL(
         KPubId, contentType, 
-        iInstIdList[aInstance]->Des(),
+        iInstIdList[aInstance].iCid,        
         aMailboxName,
         textKey, KTriggerEmailUi8);
     }
@@ -292,8 +298,8 @@
 
     TFSMailMsgId dummy;
     
-    PublishDescriptorL( KPubId, contentType, iInstIdList[aInstance]->Des(),
-        aMailboxName, textKey, aAction);
+    PublishDescriptorL( KPubId, contentType, iInstIdList[aInstance].iCid,
+        aMailboxName, textKey, aAction);        
     }
 
 // ---------------------------------------------------------------------------
@@ -322,7 +328,7 @@
     key.Append(row8);
 
     PublishImageL(
-              iInstIdList[aInstance]->Des(),
+              iInstIdList[aInstance].iCid,
               contentType,
               key,
               aIcon,
@@ -357,7 +363,7 @@
     key.Append(row8);
 
     PublishImageL(
-              iInstIdList[aInstance]->Des(),
+              iInstIdList[aInstance].iCid,
               contentType,
               key,
               aIcon,
@@ -382,9 +388,10 @@
     key.Copy(KKeyMailboxIcons);     
     key.Append(_L8("1"));
 
-    User::LeaveIfNull( iInstIdList[aInstance] );
+    if ( GetWidgetInstanceCount() <= aInstance ) User::LeaveIfError( KErrNotFound );
+
     PublishIconReferenceL(
-        iInstIdList[aInstance]->Des(),
+        iInstIdList[aInstance].iCid,
         contentType,
         key,
         aIconPath );
@@ -480,7 +487,7 @@
 
     iMailboxNameUid = PublishDescriptorL(
         KPubId, contentType, 
-        iInstIdList[aInstance]->Des(),
+        iInstIdList[aInstance].iCid,
         aText,
         textKey, KNullDes8);  
     }
@@ -895,7 +902,7 @@
                              {
                              // Publishing to homescreen suspended.
                              HBufC* cid = contentid.AllocLC();
-	                         TInt widgetInstance = FindWidgetInstanceId(cid->Des());
+                             TInt widgetInstance = GetWidgetInstanceId(cid->Des());
 							 if(widgetInstance>=0)
                              	iAllowedToPublish[widgetInstance] = EFalse;
                              CleanupStack::PopAndDestroy( cid );
@@ -903,15 +910,19 @@
                          else if (trigger.Compare(KResume16) == 0)
                              {
                              HBufC* cid = contentid.AllocLC();
-                             if ( FindWidgetInstanceId(cid->Des()) < 0 )
+                             if ( GetWidgetInstanceId(cid->Des()) < 0 )
                                  {
-                                 iInstIdList.AppendL( contentid.AllocL() );
+                                 TInstIdInfo instIdInfo;
+                                 instIdInfo.iCid.Copy(cid->Des());                           
+                                 instIdInfo.iUpdateNeeded = ETrue;
+                                 instIdInfo.iWizardPublished = EFalse;
+                                 iInstIdList.AppendL(instIdInfo);
                                  }
-                             TInt widgetInstance = FindWidgetInstanceId(cid->Des()); 
+                             TInt widgetInstance = GetWidgetInstanceId(cid->Des()); 
                              if(widgetInstance>=0)// coverity fix, index can be negativ, allowed 0, since it is valid index
                                  {
-                                 PublishSetupWizardL(widgetInstance);
                                  iMailCpsHandler->UpdateMailboxesL(widgetInstance, cid->Des());
+                                 PublishSetupWizardL(widgetInstance);                                 
                                  // Widget visible on the homescreen. Publishing allowed.
                                  iAllowedToPublish[widgetInstance] = ETrue;
                                  }
@@ -923,7 +934,11 @@
                              HBufC* cid = contentid.AllocLC();
                              if ( cid->Length() > 0 )
                                  {
-                                 iInstIdList.AppendL( contentid.AllocL() );
+                                 TInstIdInfo instIdInfo;
+                                 instIdInfo.iCid.Copy(cid->Des());                           
+                                 instIdInfo.iUpdateNeeded = ETrue;
+                                 instIdInfo.iWizardPublished = EFalse;
+                                 iInstIdList.AppendL(instIdInfo);
                                  TFSMailMsgId mailBox( iMailCpsHandler->WaitingForNewWidget() );
                                  if ( mailBox.Id() > 0 )
                                      {
@@ -950,7 +965,7 @@
                              HBufC* cid = contentid.AllocLC();                             
                              ResetPublishedDataL( cid->Des() );							 
                              iMailCpsHandler->DissociateWidgetFromSettingL( cid->Des() );
-                             TInt widgetInstance = FindWidgetInstanceId( cid->Des() );
+                             TInt widgetInstance = GetWidgetInstanceId( cid->Des() );
                              if (widgetInstance != KErrNotFound )
                                  {
                                  iInstIdList.Remove(widgetInstance);
@@ -1027,16 +1042,16 @@
 
 
 // ---------------------------------------------------------------------------
-// CMailCpsIf::FindWidgetInstanceId
+// CMailCpsIf::GetWidgetInstanceId
 // ---------------------------------------------------------------------------
 //
-TInt CMailCpsIf::FindWidgetInstanceId( const TDesC& aContentId )
+TInt CMailCpsIf::GetWidgetInstanceId( const TDesC& aContentId )
     {
     FUNC_LOG;
     TInt instance(KErrNotFound);
-    for (TInt i = 0; i < iInstIdList.Count(); i++)
+    for (TInt i = 0; i < iInstIdList.Count(); i++)    
         {
-        TInt val = aContentId.Compare(iInstIdList[i]->Des());
+        TInt val = aContentId.Compare(iInstIdList[i].iCid);
         if (!val)
             {
             instance = i;
@@ -1092,11 +1107,11 @@
     
     for ( TInt i = 0; i < iInstIdList.Count(); i++ )
         {
-        if ( !iMailCpsHandler->Associated(iInstIdList[i]->Des()) )
+        if ( !iMailCpsHandler->Associated(iInstIdList[i].iCid) )
             {
             // Empty e-mail widget found. Associate new account to it.
             iMailCpsHandler->AssociateWidgetToSetting( 
-                    iInstIdList[i]->Des(),
+                    iInstIdList[i].iCid,
                     aMailbox );
             return;
             }
@@ -1157,3 +1172,23 @@
     FUNC_LOG;
     }
 
+// ---------------------------------------------------------------------------
+// CMailCpsIf::SetUpdateNeeded
+// ---------------------------------------------------------------------------
+//
+void CMailCpsIf::SetUpdateNeeded( const TInt aInstance, const TBool aValue )
+    {
+    FUNC_LOG;
+    iInstIdList[aInstance].iUpdateNeeded = aValue;
+    }
+
+// ---------------------------------------------------------------------------
+// CMailCpsIf::UpdateNeeded
+// ---------------------------------------------------------------------------
+//
+TBool CMailCpsIf::UpdateNeeded( const TInt aInstance )
+    {
+    FUNC_LOG;
+    return iInstIdList[aInstance].iUpdateNeeded;
+    }
+
--- a/emailservices/emailserver/cmailhandlerplugin/src/cmailcpssettings.cpp	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailservices/emailserver/cmailhandlerplugin/src/cmailcpssettings.cpp	Tue Apr 27 16:20:14 2010 +0300
@@ -122,45 +122,104 @@
 void CMailCpsSettings::LoadSettingsL()
     {
     FUNC_LOG;
-    // Clean up local settings cache
-    iMailboxArray.Reset();
     TInt ret( KErrNone );
-    
-    // Load mailbox array
-    RArray<TUint32> keys;
+
+    // mailbox keys
+    RArray<TUint> cenrepMailboxes; 
+    CleanupClosePushL( cenrepMailboxes );
+    RArray<TBool> cenrepMailboxesExistence; 
+    CleanupClosePushL( cenrepMailboxesExistence );
+
+    // cenrep keys
+    RArray<TUint32> keys; 
     CleanupClosePushL( keys );
     GetMailboxNonZeroKeysL( keys );
-    const TInt iiMax( keys.Count() );
-    for ( TInt ii = 0; ii < iiMax; ii++ )
+    TInt dMax( keys.Count() );
+    
+    cenrepMailboxes.ReserveL( dMax );
+    cenrepMailboxesExistence.ReserveL( dMax );
+    
+    // make array of mailbox keys
+    TInt value( 0 );
+    TInt i;
+    for ( i = 0; i < dMax; i++ )
+        {
+         User::LeaveIfError( ret = iCenRep->Get( keys[i], value ));
+         cenrepMailboxes.AppendL( static_cast<TUint>(value) );
+         cenrepMailboxesExistence.AppendL( EFalse );
+        }
+    CleanupStack::PopAndDestroy(&keys); 
+    
+    // Sync array of cenrep keys with iMailboxArray
+    // remove from array what is not in cenrep
+    TInt dFound( KErrNotFound );
+    for ( i = iMailboxArray.Count()-1; i >= 0; i -- )
         {
-        TInt value( 0 );
-        ret = iCenRep->Get( keys[ii], value );
-        if ( ret )
-            {
-            User::Leave( ret );
+        dFound = cenrepMailboxes.Find( iMailboxArray[i].Id() );
+        if ( KErrNotFound != dFound ) 
+            { 
+             // mailbox is in iMailboxArray and in cenrep => check provider
+            INFO_1("Mailbox both in cenrep and iMailboxArray: i = %d ", i );
+            ret = CheckMailboxExistence( iMailboxArray[i] );
+            if ( KErrNotFound == ret)
+                {
+                // mailbox was removed from provider => remove from cenrep also
+                // cenrepMailboxes indexed the same way as keys => finding key not needed 
+                ret = iCenRep->Reset( KCMailMailboxIdBase + i );
+                ret = iCenRep->Reset( KCMailPluginIdBase + i );
+                ret = iCenRep->Reset( KCMailWidgetContentIdBase + i );
+                INFO_1("Mailbox removed from cenrep: dFound %d ", dFound );
+                }
+            else
+                {
+                User::LeaveIfError(ret); // for instance if no memory
+                INFO_1("Mailbox provider check ok: dFound = %d ", dFound );
+                }
+            cenrepMailboxesExistence[dFound] = ETrue; // not remove to ensure indexes are the same as in keys
             }
         else
             {
+            // mailbox was removed from cenrep => remove from array
+            iMailboxArray.Remove(i);
+            INFO_1("Mailbox removed from iMailboxArray: i = %d ", i );
+            }
+        }
+    // Check order and new mailboxes 
+    TInt j(0);
+    for ( i = 0; i < dMax; i++ )
+        {
+        // new mailboxes in cenrep needs to be added to iMailboxArray
+        if ( ! cenrepMailboxesExistence[i] ) 
+            {
             TFSMailMsgId mailbox; 
-            ret = ResolveMailbox( value, mailbox );
-            if ( ret )
+            // Find mailbox by this function because cenrep does not hold pluginID
+            if ( KErrNone == ResolveMailbox( cenrepMailboxes[i], mailbox ) )
                 {
-				INFO("CMailCpsSettings::LoadSettingsL(): Error: ignore this entry");
-                // Resolving encountered error, ignore this entry
-                ret = iCenRep->Reset( KCMailMailboxIdBase+ii );
-                ret = iCenRep->Reset( KCMailPluginIdBase+ii );
-                ret = iCenRep->Reset( KCMailWidgetContentIdBase+ii );
-                if ( ret )
+                iMailboxArray.Insert( mailbox, i );
+                INFO_1("Mailbox added to iMailboxArray: i = %d ", i );
+                }
+            }
+        // Check if order is OK
+        if ( iMailboxArray[i].Id() != cenrepMailboxes[i] )
+            {
+            TInt jMax( iMailboxArray.Count() );
+            for ( j = i+1; j <= jMax; j++ )
+                {
+                if ( iMailboxArray[j].Id() == cenrepMailboxes[i])
                     {
+                    iMailboxArray.Insert( iMailboxArray[j], i ); 
+                    iMailboxArray.Remove( j+1 );// insertion increased indices 
+                    break;
                     }
                 }
-            else
+            if (j == jMax) // arrays not in sync error
                 {
-                iMailboxArray.AppendL( mailbox );
+                User::Leave( KErrNotFound );
                 }
             }
         }
-    CleanupStack::PopAndDestroy(); // CleanupClosePushL( keys )
+    CleanupStack::PopAndDestroy(&cenrepMailboxesExistence);
+    CleanupStack::PopAndDestroy(&cenrepMailboxes);
     }
 
 // ---------------------------------------------------------------------------
@@ -217,7 +276,7 @@
     FUNC_LOG;
     RPointerArray<CFSMailBox> mailboxarray;
     TInt err = iMailClient.ListMailBoxes( TFSMailMsgId(), mailboxarray );
-	INFO_1("CMailCpsSettings::ResolveMailbox(): : ListMailBoxes() returns %d", err);
+	INFO_1("CMailCpsSettings::ResolveMailbox():: ListMailBoxes() returns %d", err);
     if( !err ) // KErrNone = 0
         {
         err = KErrNotFound;
@@ -238,6 +297,28 @@
     return err;
     }
 
+TInt CMailCpsSettings::CheckMailboxExistence( TFSMailMsgId& aMsg )
+    {
+    FUNC_LOG;
+    CFSMailBox *mbox( NULL );
+    TRAPD(err, mbox = iMailClient.GetMailBoxByUidL(aMsg));
+    if ( mbox ) // mail box exists
+        {
+        delete mbox;
+        return KErrNone;
+        }
+    if ( ( KErrNotFound == err ) || ( KErrNone == err ) )
+        {
+    // mail box not exists, chek if it is not in different plugin 
+    // very safe, maybe return KErrNotFound would be enough
+        return ResolveMailbox( aMsg.Id(), aMsg );
+        }
+    return err;
+    }
+
+
+
+
 // ---------------------------------------------------------------------------
 // CMailCpsSettings::StartObservingL
 // ---------------------------------------------------------------------------
@@ -305,7 +386,7 @@
         CleanupStack::Pop( account );
         }
 
-    CleanupStack::PopAndDestroy(); // keys
+    CleanupStack::PopAndDestroy(&keys); // keys
     }
 
 // ---------------------------------------------------------------------------
@@ -370,7 +451,7 @@
         {
         }
 
-    CleanupStack::PopAndDestroy(); // CleanupClosePushL( keys );
+    CleanupStack::PopAndDestroy( &keys ); // keys 
 
     }
 
@@ -547,6 +628,27 @@
     }
 
 // ---------------------------------------------------------------------------
+// CMailCpsSettings::WidgetCountByMailbox
+// ---------------------------------------------------------------------------
+//
+TInt CMailCpsSettings::WidgetCountByMailbox( TInt aMailboxId )
+    {
+    FUNC_LOG;
+    TInt ret(0);
+    for (TInt i = 0; i < KMaxMailboxCount; i++)
+        {       
+        TInt value;
+        TUint32 mailboxKey(KCMailMailboxIdBase+i);
+        iCenRep->Get( mailboxKey, value );     
+        if (aMailboxId == value)
+            {
+            ret++;
+            }
+        }
+    return ret;
+    }
+
+// ---------------------------------------------------------------------------
 // CMailCpsSettings::IsSelected
 // ---------------------------------------------------------------------------
 //
@@ -636,6 +738,7 @@
     RPointerArray<CFSMailBox> mailboxarray;
     iMailClient.ListMailBoxes( TFSMailMsgId(), mailboxarray );    
     TInt ret = mailboxarray.Count(); 
+    mailboxarray.ResetAndDestroy();
     return ret;
     }
 
@@ -678,28 +781,35 @@
     }
 
 // -----------------------------------------------------------------------------
-// CMailCpsSettings::GetNewMailState
+// CMailCpsSettings::GetNewMailStateL
 // -----------------------------------------------------------------------------
-TBool CMailCpsSettings::GetNewMailState( const TFSMailMsgId& aMailBox )
+TBool CMailCpsSettings::GetNewMailStateL( const TFSMailMsgId& aMailBox, TInt aUnreadCount )
     {
     FUNC_LOG;
     TBool ret(EFalse);
-    TBuf<KMaxDescLen> mailbox;
-    mailbox.Num(aMailBox.Id());
+    if ( aUnreadCount )
+        {
+        TBuf<KMaxDescLen> mailbox;
+        mailbox.Num(aMailBox.Id());
 
-    TBuf<KMaxDescLen> str;
-    str.Copy(KStartSeparator);    
-    str.Append(mailbox);
-    str.Append(KEndSeparator);    
+        TBuf<KMaxDescLen> str;
+        str.Copy(KStartSeparator);    
+        str.Append(mailbox);
+        str.Append(KEndSeparator);    
 
-    TBuf<KMaxDescLen> stored;
-    TUint32 key(KCMailMailboxesWithNewMail);
-    iCenRep->Get( key, stored );
+        TBuf<KMaxDescLen> stored;
+        TUint32 key(KCMailMailboxesWithNewMail);
+        iCenRep->Get( key, stored );
     
-    TInt result = stored.Find(str);
-    if (result >= 0)
+        TInt result = stored.Find(str);
+        if (result >= 0)
+            {
+            ret = ETrue;
+            }
+        }
+    else
         {
-        ret = ETrue;
+        ToggleWidgetNewMailIconL( EFalse, aMailBox );
         }
     return ret;
     }
--- a/emailservices/emailserver/cmailhandlerplugin/src/cmailpluginproxy.cpp	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailservices/emailserver/cmailhandlerplugin/src/cmailpluginproxy.cpp	Tue Apr 27 16:20:14 2010 +0300
@@ -368,7 +368,7 @@
     TInt id( KErrNotFound );
     for ( TInt i = 0; i < iPublisher.iInstIdList.Count(); i++ )
         {
-        if ( aContentId.Compare( *(iPublisher.iInstIdList[i]) ) == 0 )
+        if ( aContentId.Compare( iPublisher.iInstIdList[i].iCid ) == 0 )            
             {
             id = i;
             }
--- a/emailservices/emailstore/base_plugin/group/BasePlugin.mmp	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailservices/emailstore/base_plugin/group/BasePlugin.mmp	Tue Apr 27 16:20:14 2010 +0300
@@ -62,7 +62,7 @@
 SOURCE basepluginfetch.cpp
 SOURCE baseplugindelayedops.cpp
 SOURCE basepluginresourceloader.cpp
-
+SOURCE NestedAO.cpp
 
 // *************************************
 // OTHER STUFF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/emailservices/emailstore/base_plugin/inc/NestedAO.h	Tue Apr 27 16:20:14 2010 +0300
@@ -0,0 +1,89 @@
+/*
+* ============================================================================
+*  Name     : NestedAO.h
+*  Part of  : Base Plugin
+*
+*  Description:
+*       Class used to implement nested active object used to handle deletion
+*       of large number of messages by breaking them into smaller chunks
+*  Version:
+*
+*  Copyright (C) 2010 Nokia Corporation.
+*  This material, including documentation and any related
+*  computer programs, is protected by copyright controlled by
+*  Nokia Corporation. All rights are reserved. Copying,
+*  including reproducing, storing,  adapting or translating, any
+*  or all of this material requires the prior written consent of
+*  Nokia Corporation. This material also contains confidential
+*  information which may not be disclosed to others without the
+*  prior written consent of Nokia Corporation.
+* ============================================================================
+*/
+
+#ifndef __NESTED_AO_H__
+#define __NESTED_AO_H__
+
+//  Include Files
+
+
+#include <e32base.h>
+
+
+class MDeletionHandler
+    {
+public:
+    enum TState
+        {
+        EInProgress,
+        EFree
+        };
+    //Deletes messages from aStartIndex KSizeOfChunk at a time
+    virtual TBool DeleteMessagesInChunksL( TInt aStartIndex ) = 0;
+    };
+//Time interval between issuing 2 requests to delete messages
+const TInt KWaitIntervalInMicroSecs=500;
+//Maximum number of messages deleted in one go
+const TInt KSizeOfChunk=10;
+
+NONSHARABLE_CLASS ( CNestedAO ) : public CTimer
+    {
+    public:
+        
+        static CNestedAO* NewL( MDeletionHandler& aDeletionHandler );
+        virtual ~CNestedAO();
+        // --------------------------------------------------------------------------
+        // CNestedAO::DeleteMessagesAsync
+        // Used to delete messages asynchronously 
+        // Deleting a small number of messages at a time
+        // ------------
+        void DeleteMessagesAsync();
+        // --------------------------------------------------------------------------
+        // CNestedAO::Rc
+        // Used to return the iStatus return value
+        // ------------        
+        TInt Rc() { return iRc; }
+        
+    private:
+        CNestedAO( MDeletionHandler& aDeletionHandler );
+        void ConstructL();
+        
+        // inherited from CActive
+        virtual void RunL();
+        virtual void DoCancel();
+        // --------------------------------------------------------------------------
+        // CNestedAO::Stop
+        // Stops the scheduler from running
+        // Called after all messages are processed
+        // or in error condition
+        // ------------           
+        void Stop();
+        
+    private:
+        CActiveSchedulerWait* iNestedWait;
+        MDeletionHandler& iDeletionHandler;
+        TInt iDeletionIndex;
+        TInt iRc;
+    };
+
+
+#endif  //__NESTED_AO_H__
--- a/emailservices/emailstore/base_plugin/inc/baseplugindelayedopsprivate.h	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailservices/emailstore/base_plugin/inc/baseplugindelayedopsprivate.h	Tue Apr 27 16:20:14 2010 +0300
@@ -19,7 +19,7 @@
 
 
 #include "baseplugindelayedops.h"
-
+#include "NestedAO.h"
 
 /**
  * Lets the user enqueue and dequeue asynchronous jobs for handling
@@ -70,7 +70,7 @@
 /**
  * 
  */
-NONSHARABLE_CLASS( CDelayedDeleteMessagesOp ) : public CDelayedOp
+NONSHARABLE_CLASS( CDelayedDeleteMessagesOp ) : public CDelayedOp, public MDeletionHandler
     {
 
 public:
@@ -90,6 +90,10 @@
     //CDelayedOp::ExecuteOpL
     virtual void ExecuteOpL();
     
+    //From MDeletionHandler
+    //Used to delete messages in chunks starting from aStartIndex
+    TBool DeleteMessagesInChunksL( TInt aStartIndex );
+    
 private:
 
     void ConstructL( const RArray<TFSMailMsgId>& aMessages );
@@ -108,7 +112,7 @@
     TMsgStoreId iFolderId;
     RArray<TMsgStoreId> iMessages;
     TBool iImmediateDelete;
-    
+    TState iState;
     __LOG_DECLARATION
     };
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/emailservices/emailstore/base_plugin/src/NestedAO.cpp	Tue Apr 27 16:20:14 2010 +0300
@@ -0,0 +1,124 @@
+/*
+* ==============================================================================
+*  Name        : NestedAO.cpp
+*  Part of     : Base Plugin
+*  Description : Implementation of a nested active object used to handle deletion
+*                of large number of messages by breaking them into smaller chunks
+*  Version     : 
+*
+*  Copyright (c) 2005 - 2010 Nokia Corporation.
+*  This material, including documentation and any related
+*  computer programs, is protected by copyright controlled by
+*  Nokia Corporation. All rights are reserved. Copying,
+*  including reproducing, storing, adapting or translating, any
+*  or all of this material requires the prior written consent of
+*  Nokia Corporation. This material also contains confidential
+*  information which may not be disclosed to others without the
+*  prior written consent of Nokia Corporation.
+* ==============================================================================
+*/
+//  Include Files
+//
+
+
+#include "NestedAO.h"
+#include "baseplugindelayedops.h"
+#include "baseplugindelayedopsprivate.h"
+
+//Class CNestedAO
+
+// --------------------------------------------------------------------------
+//  CNestedAO::NewL
+// ------------ 
+CNestedAO* CNestedAO::NewL( MDeletionHandler& aDeletionHandler )
+    {
+    CNestedAO* self = new(ELeave) CNestedAO( aDeletionHandler );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+// --------------------------------------------------------------------------
+//  CNestedAO::CNestedAO
+// ------------ 
+CNestedAO::CNestedAO( MDeletionHandler& aDeletionHandler ) 
+ : CTimer( EPriorityIdle ), iDeletionHandler( aDeletionHandler ), iRc( KErrNone )
+    {
+    }
+// --------------------------------------------------------------------------
+//  CNestedAO::ConstructL()
+// ------------ 
+void CNestedAO::ConstructL()
+    {
+    CTimer::ConstructL();
+    iNestedWait = new( ELeave ) CActiveSchedulerWait();
+    CActiveScheduler::Add( this );
+    }
+// --------------------------------------------------------------------------
+//  CNestedAO::~CNestedAO
+// ------------ 
+CNestedAO::~CNestedAO()
+    {
+    Cancel();
+    delete iNestedWait;
+    }
+// --------------------------------------------------------------------------
+// CNestedAO::DeleteMessagesAsync
+// Used to delete messages asynchronously 
+// Deleting a small number of messages at a time
+// ------------
+void CNestedAO::DeleteMessagesAsync()
+    {
+    iDeletionIndex = 0;
+    After( KWaitIntervalInMicroSecs );  //to invoke RunL after 100 microseconds
+    iNestedWait->Start(); 
+    }
+// --------------------------------------------------------------------------
+//  CNestedAO::DoCancel
+// ------------ 
+void CNestedAO::DoCancel()
+    {
+    iRc = KErrCancel;
+    Stop();
+    }
+// --------------------------------------------------------------------------
+//  CNestedAO::RunL
+// ------------    
+void CNestedAO::RunL()
+    {
+    iRc = iStatus.Int();
+    if ( iStatus.Int() == KErrNone )
+        {
+        TBool done = iDeletionHandler.DeleteMessagesInChunksL( iDeletionIndex );
+        if( !done )
+        	{
+        	//Increment deletionidex
+        	iDeletionIndex+=KSizeOfChunk;
+        	After( KWaitIntervalInMicroSecs ); 
+        	}
+        else
+        	{
+        	Stop();
+        	}
+		}
+    else
+        {
+        Stop();
+        }
+    }
+
+// --------------------------------------------------------------------------
+// CNestedAO::Stop
+// Stops the scheduler from running
+// Called after all messages are processed
+// or in error condition
+// ------------    
+void CNestedAO::Stop()
+    {
+    if( iNestedWait->IsStarted() )
+        {
+        // Stop the nested active scheduler (flow-of-control will pick up immediately following the
+        // call to iWait.Start().
+        iNestedWait->AsyncStop();
+        } // end if
+    }
--- a/emailservices/emailstore/base_plugin/src/baseplugindelayedops.cpp	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailservices/emailstore/base_plugin/src/baseplugindelayedops.cpp	Tue Apr 27 16:20:14 2010 +0300
@@ -18,7 +18,7 @@
 
 #include "baseplugindelayedops.h"
 #include "baseplugindelayedopsprivate.h"
-
+#include "NestedAO.h"
 
 ///////////////////////////////////////////////////
 // CDelayedOp                                    //
@@ -228,7 +228,63 @@
     __LOG_DESTRUCT
     }
 
+/**
+ * 
+ */
+/*public virtual*/TBool CDelayedDeleteMessagesOp::DeleteMessagesInChunksL( TInt aStartIndex )
+    {
+    __LOG_ENTER( "DeleteMessagesInChunksL" );
+    TBool done=EFalse;
+    TInt endIndex;
+    if( aStartIndex + KSizeOfChunk < iMessages.Count() )
+        {
+            endIndex = aStartIndex + KSizeOfChunk;
+        }
+    else
+        {
+        endIndex = iMessages.Count();   
+        done=ETrue;
+        }
+    CMailboxInfo& mailBoxInfo
+        = GetPlugin().GetMailboxInfoL( iMailBoxId );
+    CMsgStoreMailBox& mailBox = mailBoxInfo();
 
+    for ( TInt i = aStartIndex; i < endIndex; ++i )
+        {
+        TMsgStoreId msgId = iMessages[i];
+        
+        if ( EFalse == iImmediateDelete )
+            {
+            //try to find the message in the deleted items folder.
+            CMsgStoreMessage* theMessage = NULL;
+            TRAP_IGNORE( theMessage = mailBox.FetchMessageL(
+              msgId, mailBoxInfo.iRootFolders.iFolders[EFSDeleted] ) );
+            
+            if ( NULL == theMessage )
+                {
+                //if not in deleted items then move it there.
+                __LOG_WRITE8_FORMAT1_INFO("Moving message 0x%X to the deleted items.", msgId );
+                mailBox.MoveMessageL(
+                   msgId, KMsgStoreInvalidId,
+                   mailBoxInfo.iRootFolders.iFolders[EFSDeleted] );
+                }
+            else
+                {
+                //in deleted items, really delete it.
+                __LOG_WRITE8_FORMAT1_INFO( "Deleting message 0x%X.", msgId );
+
+                delete theMessage;
+                mailBox.DeleteMessageL( msgId, iFolderId );
+                }
+            }
+        else
+            {
+            mailBox.DeleteMessageL( msgId, iFolderId );
+            }
+        }
+    __LOG_EXIT;
+    return done;    
+    }
 /**
  * 
  */
@@ -265,7 +321,7 @@
     TMsgStoreId aFolderId )
     :
     iMailBoxId( aMailBoxId ), iFolderId( aFolderId ),
-    iImmediateDelete( EFalse )
+    iImmediateDelete( EFalse ), iState ( EFree )
     {
     }
 
@@ -275,47 +331,21 @@
 /*private*/ void CDelayedDeleteMessagesOp::ExecuteOpL()
     {
     __LOG_ENTER( "ExecuteOpL" );
-    
-    CMailboxInfo& mailBoxInfo
-        = GetPlugin().GetMailboxInfoL( iMailBoxId );
-    CMsgStoreMailBox& mailBox = mailBoxInfo();
-
-    TInt count = iMessages.Count();
-    for ( TInt i = 0; i < count; ++i )
+    if ( iState != EFree )
         {
-        TMsgStoreId msgId = iMessages[i];
-        
-        if ( EFalse == iImmediateDelete )
-            {
-            //try to find the message in the deleted items folder.
-            CMsgStoreMessage* theMessage = NULL;
-            TRAP_IGNORE( theMessage = mailBox.FetchMessageL(
-              msgId, mailBoxInfo.iRootFolders.iFolders[EFSDeleted] ) );
-            
-            if ( NULL == theMessage )
-                {
-                //if not in deleted items then move it there.
-                __LOG_WRITE8_FORMAT1_INFO(
-                     "Moving message 0x%X to the deleted items.", msgId );
-                mailBox.MoveMessageL(
-                   msgId, KMsgStoreInvalidId,
-                   mailBoxInfo.iRootFolders.iFolders[EFSDeleted] );
-                }
-            else
-                {
-                //in deleted items, really delete it.
-                __LOG_WRITE8_FORMAT1_INFO( "Deleting message 0x%X.", msgId );
-
-                delete theMessage;
-                mailBox.DeleteMessageL( msgId, iFolderId );
-                }
-            }
-        else
-            {
-            mailBox.DeleteMessageL( msgId, iFolderId );
-            }
+        //this code becomes re-entrant now because we use nested AS.
+        // so if we are already authenticating, return right away.
+        return;
         }
-
+    iState=EInProgress;
+    CNestedAO* nestedAO = CNestedAO::NewL( *this );
+    //this is a blocking call with nested active scheduler
+    //This method makes a callback periodically to DeleteMessagesInChunks
+    //to delete the messages one chunk at a time
+    nestedAO->DeleteMessagesAsync();
+    //continue execution here
+    delete nestedAO;
+    iState = EFree;
     __LOG_EXIT;
     }
 
--- a/emailuis/emailui/data/html/email_rtl.html	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailuis/emailui/data/html/email_rtl.html	Tue Apr 27 16:20:14 2010 +0300
@@ -1,19 +1,21 @@
 <html dir="rtl">
 <header>
 <script language="javascript">
-function setEmailBodyDirection()
-	{
-	var bodyFrame = document.getElementById("body_frame");
-	bodyFrame.contentWindow.document.body.dir = "rtl";
-	bodyFrame.contentWindow.document.body.align = "right"
-	}
+function setEmailBodyDirection() {
+    var htmlTagName = "html";
+	var d = document.getElementById("body_frame").contentWindow.document;
+	var a = d.getElementsByTagName(htmlTagName);
+	if (a.length > 0 )  {
+	    a[0].setAttribute("dir", "rtl");
+    }
+}
 onload=setEmailBodyDirection;
 </script>
 <script language="javascript" src="email.js"></script>
 </header>
 <frameset rows="10%,*" border="0" id="email_frameSet" onLoad="hideImages('body_frame')">
 <frame id="header_frame" src="header.html" >
-<frame id="body_frame" src="temp/body.html" >
+<frame id="body_frame" src="temp/body.html" onLoad="setEmailBodyDirection()" >
 </frameset>
 
 </html>
--- a/emailuis/emailui/inc/FreestyleEmailUiHtmlViewerView.h	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailuis/emailui/inc/FreestyleEmailUiHtmlViewerView.h	Tue Apr 27 16:20:14 2010 +0300
@@ -212,6 +212,7 @@
     void LoadContentFromFileL( RFile& aFile );
     void LoadContentFromUrlL( const TDesC& aUrl );
     void LoadContentFromMailMessageL( CFSMailMessage* aMailMessage, TBool aResetScrollPosition =ETrue );
+    static TInt DeleteMail( TAny* aSelf );
     void DeleteMailL(TBool aSilentDelete = EFalse);
     void HideContainer();
     void ShowContainerL();
@@ -337,6 +338,7 @@
     // Flag selection handler active object for global note
     CFlagSelectionNoteHandler* iFlagSelectionHandler;  
     TBool iNextOrPrevMessageSelected;
+    TBool iMessageIsDeleted;
     };
 
 ////////////////////////////////////////
--- a/emailuis/emailui/inc/FreestyleEmailUiLayoutHandler.h	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailuis/emailui/inc/FreestyleEmailUiLayoutHandler.h	Tue Apr 27 16:20:14 2010 +0300
@@ -25,9 +25,9 @@
 #include <alf/alfenv.h>
 #include <alf/alftextstyle.h>
 #include <aknlayout2scalabledef.h>
-#include <aknutils.h>
+#include <AknUtils.h>
 // INTERNAL INCLUDES
-#include "freestyleemailuilayoutdata.h"
+#include "FreestyleEmailUiLayoutData.h"
 
 // FORWARD DECLARATIONS
 class CFsTreeList;
--- a/emailuis/emailui/inc/FreestyleEmailUiSendAttachmentsListControl.h	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailuis/emailui/inc/FreestyleEmailUiSendAttachmentsListControl.h	Tue Apr 27 16:20:14 2010 +0300
@@ -24,7 +24,6 @@
 
 // LOCAL INCLUDES
 #include "FreestyleEmailUiAttachmentsListModel.h"
-#include "FreestyleEmailUiUtilities.h"
 #include "fsccontactactionmenudefines.h"
 
 // FORWARD DECLARATIONS
@@ -44,7 +43,7 @@
 */
 // <cmail>
 class CFreestyleEmailUiSendAttachmentsListControl 
-	: public CAlfControl, public MFsActionMenuPositionGiver, public MMGFetchVerifier, public MFSEmailUiGenericTimerCallback
+	: public CAlfControl, public MFsActionMenuPositionGiver, public MMGFetchVerifier 
     {  
 // </cmail>
 public:
@@ -89,10 +88,7 @@
     TBool OfferEventL( const TAlfEvent& aEvent );  
 
     TBool IsAttachmentAddingLocked() const;
-    
-	// Fire timer callback
-	void TimerEventL( CFSEmailUiGenericTimer* aTriggeredTimer );
-    
+        
     /**
     * AppendAttachmentToListL
     * Adds new attachment to list and email body
@@ -244,9 +240,7 @@
     
     // adding attachment locked
     TBool iAttachmentAddingLocked;
-    
-    // Timer to postpone the Info Dialog 
-    CFSEmailUiGenericTimer* iDialogTimer;
+
     };
 
 #endif /*FREESTYLEMAILUI_SENDATTACHMENTSLISTCONTROL_H_*/
--- a/emailuis/emailui/inc/ncsaddressinputfield.h	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailuis/emailui/inc/ncsaddressinputfield.h	Tue Apr 27 16:20:14 2010 +0300
@@ -154,12 +154,12 @@
         
     TBool IsEmpty() const;
 
-// <cmail> S60 Skin support
     void SetLabelTextColorL (TRgb aColor);
     
     void FixSemicolonAtTheEndL();
-// </cmail>
 
+    void SetCursorVisible( TBool aCursorVisible );
+    
 public: // from CoeControl
     
     /**
--- a/emailuis/emailui/inc/ncscomposeview.h	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailuis/emailui/inc/ncscomposeview.h	Tue Apr 27 16:20:14 2010 +0300
@@ -68,6 +68,19 @@
     public MAknServerAppExitObserver
     {
     
+private:
+
+    /**
+     * Type of commit
+     */
+    enum TCommitType
+        {
+        // This is transient commit, message may get further modifications
+        ETransient,
+        // This is final commit, no more incoming changes
+        EFinal
+        };
+        
 public:   // constructors and destructor
 
     /**
@@ -180,7 +193,9 @@
     * explicitely requested.
     */
     void CommitL( TBool aParseAddresses = ETrue,
-        TFieldToCommit aFieldToCommit = EAllFields, TBool aSaveNow = EFalse );
+        TFieldToCommit aFieldToCommit = EAllFields, 
+        TBool aSaveNow = EFalse,
+        TCommitType aType = ETransient );
 
     /**
      * Saves the message content, if it has been changed since the last save.
--- a/emailuis/emailui/inc/ncscomposeviewcontainer.h	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailuis/emailui/inc/ncscomposeviewcontainer.h	Tue Apr 27 16:20:14 2010 +0300
@@ -90,12 +90,12 @@
     virtual ~CNcsComposeViewContainer();
 
 public: // new functions
-        
+
     /**
-    * UpdateScrollBarL
+    * UpdateScrollBar
     * Updates scroll bar data.
     */
-    void UpdateScrollBarL();
+    void UpdateScrollBar();
 
     /**
     * GetToFieldAddressesL
@@ -496,13 +496,13 @@
      * if any popup dialog is open
      */
     void SwitchChangeMskOff(TBool aTag);
-    
+
     /**
-     * ScrollL
+     * Scroll
      * @param aTargetPos Scrolls display to given position
      */
-    void ScrollL( TInt aTargetPos );
-    
+    void Scroll( TInt aTargetPos, TBool aDrawNow = ETrue );
+
 public: // from CoeControl
 
     /**
@@ -734,6 +734,11 @@
 
     // Descriptor for read-only quote text. Own.
     HBufC* iReadOnlyQuote;
+
+    TInt iTotalComposerHeight; 
+    TInt iVisibleAreaHeight;
+    TInt iTotalMoveY;
+    TInt iSeparatorHeight;
     };
 
 
--- a/emailuis/emailui/inc/ncseditor.h	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailuis/emailui/inc/ncseditor.h	Tue Apr 27 16:20:14 2010 +0300
@@ -115,12 +115,10 @@
 // </cmail> Platform layout changes
 
 public: // from CoeControl
-    
-    virtual TKeyResponse OfferKeyEventL( const TKeyEvent& aKeyEvent, TEventCode aType );
 
-    virtual void SetRect( const TRect& aRect );
+    TKeyResponse OfferKeyEventL( const TKeyEvent& aKeyEvent, TEventCode aType );
     void ActivateL();
-    
+
 public: // from CEikEdwin
 
     virtual void SetTextL( const TDesC* aDes );
@@ -149,14 +147,10 @@
 	
     void UpdateColors();
 
-    void UpdateGraphics();
-    
-    void DoUpdateGraphicsL();
-    
     TAknTextComponentLayout GetLayout();
-    //<cmail>
+
     void Draw( const TRect& aRect ) const;
-    //</cmail>
+
 private: // data
     
     TInt iPreviousFontHeight;
@@ -169,9 +163,6 @@
     // Header fields have different backgrounds than message field.
     TBool iHeaderField;
 
-    // background control context. Owned.
-    CAknsBasicBackgroundControlContext* iBgContext;
-
     // Custom drawer. Not owned.
     CNcsCustomDraw* iCustomDrawer;
 
--- a/emailuis/emailui/inc/ncseditorcustomdraw.h	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailuis/emailui/inc/ncseditorcustomdraw.h	Tue Apr 27 16:20:14 2010 +0300
@@ -88,6 +88,10 @@
     const CNcsEditor* iEditor;
     
     TAknTextComponentLayout iTextPaneLayout;
+    TInt 					iLineHeigth;
+    TRgb 					iLineColor;
+    TInt                    iLineOffset;
+    TInt                    iPrevBrX;
     };
 
 #endif //CNCSEDITORCUSTOMDRAW_H
--- a/emailuis/emailui/inc/ncsheadercontainer.h	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailuis/emailui/inc/ncsheadercontainer.h	Tue Apr 27 16:20:14 2010 +0300
@@ -355,7 +355,10 @@
      */
     void ShowCursor( TBool aShow, TDrawNow aDrawNow = ENoDrawNow );
 
-    void DoScrollL();
+    void DoScroll();
+    
+    void SetPhysicsEmulationOngoing( TBool aPhysOngoing );
+    
 private: // Function members
 
 	void FocusChanged(TDrawNow aDrawNow);
@@ -440,8 +443,6 @@
     //flag which disables changes of MSK label if any popup dialog is open
     TBool iSwitchChangeMskOff;
 
-    CAknsBasicBackgroundControlContext* iBgContext;
-    
     TBool iLongTapEventConsumed;
     TBool iRALInProgress;
     
--- a/emailuis/emailui/inc/ncspopuplistbox.h	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailuis/emailui/inc/ncspopuplistbox.h	Tue Apr 27 16:20:14 2010 +0300
@@ -144,8 +144,8 @@
     void SetListItemsFromArrayL();
 
     TInt RoundToItemHeight(const TInt aPopupHeight) const;
-    
-    void SetPopupHeight();
+
+    void SetPopupRect();
  
     void SetScrollBarVisibilityL();
 
--- a/emailuis/emailui/inc/ncssubjectfield.h	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailuis/emailui/inc/ncssubjectfield.h	Tue Apr 27 16:20:14 2010 +0300
@@ -95,6 +95,8 @@
 		
     void EnableKineticScrollingL(CAknPhysics* aPhysics );
     
+    void SetCursorVisible( TBool aCursorVisible );
+    
 public: // from CoeControl
         /**
         * SetContainerWinowL
--- a/emailuis/emailui/src/FreestyleEmailUiCLSListsHandler.cpp	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailuis/emailui/src/FreestyleEmailUiCLSListsHandler.cpp	Tue Apr 27 16:20:14 2010 +0300
@@ -120,12 +120,13 @@
 			}
 		}
 		
-	RPointerArray<CFSEmailUiClsItem> allMatches = ConstructOneListL( iMatchingCompleteContacts,
+    RPointerArray<CFSEmailUiClsItem> allMatches = ConstructOneListL( iMatchingCompleteContacts,
                                                                       iMatchingMRUContacts,
                                                                       iMatchingMissingEmailContacts );
-	iClsListObserver->ArrayUpdatedL( allMatches );
-	allMatches.ResetAndDestroy();
-	}
+    CleanupResetAndDestroyClosePushL( allMatches ); // Ownership is taken
+    iClsListObserver->ArrayUpdatedL( allMatches ); 
+    CleanupStack::PopAndDestroy(&allMatches ); // Array is released, destructors are called 
+    }
 
 // -----------------------------------------------------------------------------
 // CFSEmailUiClsListsHandler::InputModeChangedL
--- a/emailuis/emailui/src/FreestyleEmailUiHtmlViewerContainer.cpp	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailuis/emailui/src/FreestyleEmailUiHtmlViewerContainer.cpp	Tue Apr 27 16:20:14 2010 +0300
@@ -79,9 +79,9 @@
 _LIT( KHtmlGreaterThan, "&gt;" );
 _LIT( KHtmlAmpersand, "&amp;" );
 _LIT( KHtmlQuotation, "&quot;" );
-_LIT( KHtmlLinkTag, "<a href=\"%S\">" );
-_LIT( KHtmlLinkTagWWW, "<a href=\"%S%S\">" );
-_LIT( KHtmlLinkEndTag, "</a>" );
+// _LIT( KHtmlLinkTag, "<a href=\"%S\">" );
+// _LIT( KHtmlLinkTagWWW, "<a href=\"%S%S\">" );
+// _LIT( KHtmlLinkEndTag, "</a>" );
 _LIT( KURLTypeBody, "body");
 
 _LIT( KURLDisplayImages, "cmail://displayImages/" );
@@ -93,11 +93,11 @@
 const TText KLessThan = 0x3c;
 const TText KAmpersand = 0x26;
 const TText KQuotation = 0x22;
-const TText KCharacterSpace = 0x20;
+// const TText KCharacterSpace = 0x20;
 const TText KSOH = 0x01; // Start Of Heading
-const TText KCR = 0x0d; // Carriage Return
+// const TText KCR = 0x0d; // Carriage Return
 const TText KLF = 0x0a; // Line Feed
-const TText KHT = 0x09; // Horizontal Tab
+// const TText KHT = 0x09; // Horizontal Tab
 const TText KUnicodeNewLineCharacter = 0x2028;
 const TText KUnicodeParagraphCharacter = 0x2029;        
 const TReal KOverlayButtonMarginX = 0.01; // 1%
@@ -1507,7 +1507,7 @@
     CleanupStack::PushL ( itemEngine );
     if ( itemEngine->ItemCount() > 0 )
         {
-        _LIT( KHttp, "http://" );
+        _LIT( KSchemeDelimiter, "://" );
         _LIT( KUrlFormat, "<a href=\"%S\">%S</a>" );
         _LIT( KUrlFormatWithHttp, "<a href=\"http://%S\">%S</a>" );
         
@@ -1531,7 +1531,7 @@
             target.Append( source.Mid( currentSourcePosition, item.iStartPos - currentSourcePosition ) );
             const TPtrC url( source.Mid( item.iStartPos, item.iLength ) );
             TPtrC format( KUrlFormat() );
-            if ( url.FindF( KHttp() ) == KErrNotFound ) 
+            if ( url.FindF( KSchemeDelimiter() ) == KErrNotFound ) 
                 {
                 format.Set( KUrlFormatWithHttp() );
                 }
--- a/emailuis/emailui/src/FreestyleEmailUiHtmlViewerView.cpp	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailuis/emailui/src/FreestyleEmailUiHtmlViewerView.cpp	Tue Apr 27 16:20:14 2010 +0300
@@ -135,6 +135,7 @@
     iEmbeddedMessages = new (ELeave) CStack<CFSMailMessage, EFalse>();
     iNextOrPrevMessageSelected = EFalse; 
     iForwardingMessage = EFalse;
+    iMessageIsDeleted = EFalse;
     }
 
 // -----------------------------------------------------------------------------
@@ -757,7 +758,10 @@
             }
         case EFsEmailUiTbCmdDelete:
             {
-            HandleCommandL(EFsEmailUiCmdActionsDelete);
+            iAsyncCallback->Cancel();
+            iAsyncCallback->Set( TCallBack( DeleteMail, this ) );
+            iAsyncCallback->SetPriority( CActive::EPriorityHigh );
+            iAsyncCallback->CallBack();
             break;
             }
         case EFsEmailUiTbCmdReplyAll:
@@ -911,12 +915,15 @@
     // In usual case we use the base view implementation
     else
         {
-        
         iMessage = NULL;
-        
         CancelFetchings();
-             
         CFsEmailUiViewBase::NavigateBackL();
+
+        if ( iContainer )
+            {
+            HideContainer();
+            iContainer->ResetContent();
+            }
         }
     }
 
@@ -1169,7 +1176,16 @@
         }
     }
 
-void CFsEmailUiHtmlViewerView::DeleteMailL(TBool aSilentDelete)
+TInt CFsEmailUiHtmlViewerView::DeleteMail( TAny* aSelf )
+    {
+    FUNC_LOG;
+    CFsEmailUiHtmlViewerView* self =
+        static_cast<CFsEmailUiHtmlViewerView*>( aSelf );
+    TRAP_IGNORE( self->DeleteMailL( EFalse ) );
+    return KErrNone;
+    }
+
+void CFsEmailUiHtmlViewerView::DeleteMailL( TBool aSilentDelete )
     {
     FUNC_LOG;
 
@@ -1228,7 +1244,11 @@
             //Open the previous message or navigate back to list viewer
             if ( available )
                 {
-                iAppUi.MoveToPreviousMsgAfterDeleteL( prevMsgId );              
+				iMessageIsDeleted = ETrue;
+                TRAPD( err, iAppUi.MoveToPreviousMsgAfterDeleteL( prevMsgId ) );
+                iMessageIsDeleted = EFalse;
+                
+                User::LeaveIfError( err );
                 }   
             else
                 {
@@ -1264,7 +1284,7 @@
                 {                
                 cont = EFalse;
                 ChangeMskCommandL( R_FSE_QTN_MSK_EMPTY );
-                if(aEvent == TFSEventMailDeleted)
+                if( aEvent == TFSEventMailDeleted  && !iMessageIsDeleted )
                     {   //Delete event came from server; close the viewer.
                 	HandleCommandL( EAknSoftkeyBack );
                 	// The message we are viewing was deleted => stop here
@@ -1962,7 +1982,10 @@
             iAppUi.MoveToNextMsgL( currentMsgId, nextMsgId );
             // Next message is displayed in this view through doactivate, because view is re-activate by mail list
 
-            RestoreZoomLevelL();
+            if ( iContainer )
+                {
+			    RestoreZoomLevelL();
+                }
             }
         }
     }
@@ -2011,7 +2034,10 @@
             iAppUi.MoveToPreviousMsgL( currentMsgId, prevMsgId );
             // Previous message is displayed in this view through doactivate, because view is re-activate by mail list
 
-            RestoreZoomLevelL();
+            if ( iContainer )
+                {
+                RestoreZoomLevelL();
+                }
             }
         }
     }
@@ -2062,6 +2088,7 @@
                     iMoveDestinationFolder = aSelectedFolderId;
                     iAsyncCallback->Cancel(); // cancel any outstanding callback just to be safe
                     iAsyncCallback->Set( TCallBack( MoveToFolderAndExitL, this ) );
+                    iAsyncCallback->SetPriority( CActive::EPriorityLow );
                     iAsyncCallback->CallBack();
                     }
                     break;
--- a/emailuis/emailui/src/FreestyleEmailUiMailListVisualiser.cpp	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailuis/emailui/src/FreestyleEmailUiMailListVisualiser.cpp	Tue Apr 27 16:20:14 2010 +0300
@@ -57,6 +57,7 @@
 #include "mfsmailbrandmanager.h"
 #include <AknWaitDialog.h>
 #include <aknlayoutscalable_apps.cdl.h>
+#include <aknlayoutscalable_avkon.cdl.h>
 #include <layoutmetadata.cdl.h>
 #include <csxhelp/cmail.hlp.hrh>
 // Meeting request
@@ -1325,6 +1326,16 @@
 	{
     FUNC_LOG;
     TIMESTAMP( "Opening message list view" );
+    
+    if (iMarkingModeWaitingToExit)
+        {
+        if ( iAppUi.CurrentActiveView()->Id() == MailListId )
+            {
+            iMarkingModeWaitingToExit = EFalse;
+            TRAP_IGNORE( ExitMarkingModeL() );
+            }
+        }
+
     iShowReplyAll = EFalse;
 
 	if ( !iFirstStartCompleted )
@@ -2175,6 +2186,8 @@
 void CFSEmailUiMailListVisualiser::ExitMarkingModeL()
     {
     FUNC_LOG;	
+    // Hide marking mode text on the place of drop down menus
+    RemoveMarkingModeTitleTextL();	
     iMarkingMode = EFalse;
     UnmarkAllItemsL();
     // Change softkeys back to normal
@@ -2186,14 +2199,11 @@
     // Change background back to normal
     DisplayMarkingModeBgL( EFalse );   
     // Display drop down menu buttons
-    iNewEmailButton->ShowButtonL();
-    iFolderListButton->ShowButtonL();
-    iSortButton->ShowButtonL();
+    iControlBarControl->SetRectL( iAppUi.LayoutHandler()->GetControlBarRect() );
     iNewEmailButton->SetDimmed( EFalse );
     iFolderListButton->SetDimmed( EFalse );   
     iSortButton->SetDimmed( EFalse );
-    // Hide marking mode text on the place of drop down menus
-    RemoveMarkingModeTitleTextL();
+    ScaleControlBarL();
     }
 
 // ---------------------------------------------------------------------------
@@ -2224,12 +2234,11 @@
         }
     else
         {
-        iNewEmailButton->HideButton();
-        iFolderListButton->HideButton();
-        iSortButton->HideButton();
-        }
-    // Display marking mode text on the place of drop down menus   
-    DisplayMarkingModeTitleTextL();
+        TRect rect(0,0,0,0);
+        iControlBarControl->SetRectL( rect );
+        // Display marking mode text on the place of drop down menus   
+        DisplayMarkingModeTitleTextL();
+        }
     }
 
 // ---------------------------------------------------------------------------
@@ -2245,25 +2254,18 @@
         // Hide drop down menu buttons    
         if( !Layout_Meta_Data::IsLandscapeOrientation() )
             {
-            iNewEmailButton->ShowButtonL();
-            iNewEmailButton->HideButton();
-            iFolderListButton->ShowButtonL();
-            iFolderListButton->HideButton();
-            iSortButton->ShowButtonL();    
-            iSortButton->HideButton();
+            TRect rect(0,0,0,0);
+            iControlBarControl->SetRectL( rect );
+            DisplayMarkingModeTitleTextL();
             }
         else
             {
-            iNewEmailButton->ShowButtonL();
+            iControlBarControl->SetRectL( iAppUi.LayoutHandler()->GetControlBarRect() );
             iNewEmailButton->SetDimmed();
-            iFolderListButton->ShowButtonL();
             iFolderListButton->SetDimmed();
-            iSortButton->ShowButtonL();    
             iSortButton->SetDimmed();
-            }
-  
-        RemoveMarkingModeTitleTextL();
-        DisplayMarkingModeTitleTextL();
+            RemoveMarkingModeTitleTextL();
+            }
         }
     }
 
@@ -2516,15 +2518,6 @@
         iAsyncRedrawer->Cancel();
         DoRefresh( this );
         }
-
-    if (iMarkingModeWaitingToExit)
-        {
-        if ( iAppUi.CurrentActiveView()->Id() == MailListId )
-            {
-            iMarkingModeWaitingToExit = EFalse;
-            TRAP_IGNORE( ExitMarkingModeL() );
-            }
-        }
     }
 
 // ---------------------------------------------------------------------------
@@ -3454,7 +3447,7 @@
 //
 void CFSEmailUiMailListVisualiser::UpdateThemeL(const TBool aSystemUpdate)
     {
-    iSkinChanged = aSystemUpdate;
+    iSkinChanged = iSkinChanged || aSystemUpdate;
 
     TRgb focusedTextColor = iAppUi.LayoutHandler()->ListFocusedStateTextSkinColor();
     TRgb normalTextColor = iAppUi.LayoutHandler()->ListNormalStateTextSkinColor();
@@ -3467,15 +3460,14 @@
 
     iSortButton->SetNormalTextColor( normalTextColor );
     iSortButton->SetFocusedTextColor( focusedTextColor );
-    
-    //TJOS-83DELP fix/workaround 
+
     //sometimes theme wasn't properly refreshed on buttons, this helps
     iNewEmailButton->HideButton();
     iNewEmailButton->ShowButtonL();
-    
+
     iFolderListButton->HideButton();
     iFolderListButton->ShowButtonL();
-    
+
     iSortButton->HideButton();
     iSortButton->ShowButtonL();
     }
@@ -5633,6 +5625,13 @@
 void CFSEmailUiMailListVisualiser::ScaleControlBarL()
 	{
     FUNC_LOG;
+    
+    if( !Layout_Meta_Data::IsLandscapeOrientation() && iMarkingMode)
+        {
+        // No control bar buttons in portrait marking mode
+        return;    
+        }    
+    
     TRect screenRect = iAppUi.ClientRect();
 
 	// First set pos, widht and height
@@ -5658,12 +5657,10 @@
  	iSortButton->SetTextFontL( textLayout.Font()->FontSpecInTwips() );
 
  	UpdateThemeL(EFalse);
- 	if (!iMarkingMode)
- 	    {
-        iNewEmailButton->ShowButtonL();
-        iFolderListButton->ShowButtonL();
-        iSortButton->ShowButtonL();
- 	    }
+
+    iNewEmailButton->ShowButtonL();
+    iFolderListButton->ShowButtonL();
+    iSortButton->ShowButtonL();
 	}
 
 // ---------------------------------------------------------------------------
@@ -5846,6 +5843,14 @@
     // <cmail> Platform layout changes
     TRect listRect = iAppUi.LayoutHandler()->GetListRect();
 	// Set anchors so that list leaves space for control bar
+    if( Layout_Meta_Data::IsMirrored() ) 
+        { 
+        TInt tlX = listRect.iTl.iX; 
+        TInt brX = listRect.iBr.iX;
+        
+        listRect.iTl.iX = AknLayoutScalable_Avkon::Screen().LayoutLine().iW - brX; 
+        listRect.iBr.iX = AknLayoutScalable_Avkon::Screen().LayoutLine().iW - tlX; 
+        } 
     iScreenAnchorLayout->SetAnchor(EAlfAnchorTopLeft, 1,
         EAlfAnchorOriginLeft, EAlfAnchorOriginTop,
         EAlfAnchorMetricAbsolute, EAlfAnchorMetricAbsolute,
--- a/emailuis/emailui/src/FreestyleEmailUiSendAttachmentsListControl.cpp	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailuis/emailui/src/FreestyleEmailUiSendAttachmentsListControl.cpp	Tue Apr 27 16:20:14 2010 +0300
@@ -62,7 +62,7 @@
 
 // CLASS IMPLEMENTATION
 
-TInt KGenericTimerDialogInterval = 1000; // Interval for iDialogTimer
+const TInt KBigAttachmentSize = 200000; // in Bytes - Attachment is big when it's over this size
 
 // ---------------------------------------------------------------------------
 // Two-phased constructor.
@@ -122,7 +122,6 @@
 	iService = CFscContactActionService::NewL( iAppUi->GetVPbkManagerL() );
     iModel = CFSEmailUiSendAttachmentsListModel::NewL( iAppUi, Env(), this );
     iAttachmentAddingLocked = EFalse;
-    iDialogTimer = CFSEmailUiGenericTimer::NewL( this );
     }
 
 // ---------------------------------------------------------------------------
@@ -132,12 +131,7 @@
 CFreestyleEmailUiSendAttachmentsListControl::~CFreestyleEmailUiSendAttachmentsListControl()
     {
     FUNC_LOG;
-	if(iDialogTimer)
-		{
-	    iDialogTimer->Cancel();
-	    delete iDialogTimer;
-		}
-	delete iService;
+    delete iService;
     }
 
 // <cmail>
@@ -345,18 +339,6 @@
 	return iAttachmentAddingLocked;
 }
 
-
-// ---------------------------------------------------------------------------
-// TimerEventL
-// Timer that delays the dialog will open the dialog here
-// ---------------------------------------------------------------------------
-//
-void CFreestyleEmailUiSendAttachmentsListControl::TimerEventL( CFSEmailUiGenericTimer* /*aTriggeredTimer*/ )
-	{
-	TFsEmailUiUtility::ShowWaitNoteL( iWaitNote, R_FSE_WAIT_INSERTING_TEXT, EFalse,ETrue );
-	iDialogTimer->Cancel();
-	}
-
 // ---------------------------------------------------------------------------
 // AppendAttachmentToListL
 //
@@ -413,10 +395,34 @@
         
 	iAttachmentAddingLocked = ETrue;
 	
+	if( fetchOK )
+		{
+	    TInt size(0);  
+	    TInt err(KErrNone);
+	    // check if dialog could be shown if the attachment is not protected and have a propper size
+	    RFile file; 
+	    err = file.Open( CCoeEnv::Static()->FsSession(), filePath, EFileShareReadersOnly );
+	    if( err == KErrNone )
+	        {
+	        CleanupClosePushL( file );
+	        fetchOK = !FileDrmProtectedL( file ); // it's ok if it is NOT protected
+	   	    file.Size(size); //get size in bytes
+	        CleanupStack::PopAndDestroy( &file );
+	    	}
+	        
+	    // show dialog for multiple files or 
+	    // show if file is not protected and it's considered as the Big Attachment
+        if(( fetchOK && size > KBigAttachmentSize )  || err != KErrNone )
+            {
+		    TFsEmailUiUtility::ShowWaitNoteL( iWaitNote, R_FSE_WAIT_INSERTING_TEXT, EFalse,ETrue );
+		    iWaitNote->DrawNow();
+		    iWaitNote->FocusChanged(EDrawNow);
+		    }
+	    }
+    
+	
 	if ( fetchOK && filePath.Length() > 0 ) // </cmail>
 		{
-	    iDialogTimer->Start(KGenericTimerDialogInterval);   
-	
         if ( !FileDrmProtectedL( filePath ) )
 			{
 			// add file as a email message part
@@ -468,8 +474,7 @@
 			}
 		}
 
-	iDialogTimer->Cancel();
-	if(iWaitNote) 
+	if( iWaitNote ) 
 	  	{
 	    iWaitNote->ProcessFinishedL();
 	   	}
@@ -511,7 +516,7 @@
     RFile file;
     TInt err = file.Open( CCoeEnv::Static()->FsSession(), 
                           aFilePath, 
-                          EFileRead | EFileShareAny );
+                          EFileShareReadersOnly );
     User::LeaveIfError( err );
     CleanupClosePushL( file );
     isProtected = FileDrmProtectedL( file );
--- a/emailuis/emailui/src/FreestyleEmailUiViewBase.cpp	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailuis/emailui/src/FreestyleEmailUiViewBase.cpp	Tue Apr 27 16:20:14 2010 +0300
@@ -126,13 +126,23 @@
         	{
         	iAppUi.ReturnFromPluginSettingsView();
         	}
-        // View activated succesfully. Change visible control group, but not
-        // when application is being sent to background.
+
+        // View activated succesfully
         if ( !iAppUi.SwitchingToBackground() )
             {
+            // Change visible control group
             DoTransition( EFalse );
             ActivateControlGroup();
             }
+        else
+            {
+            // View activated but Mail application is switching to background.
+            // Mail application was invoked from other app and now we`re going back
+            // to this other app. We have to force, that after going back to Mail
+            // application, ActivateControlGroup will be invoked in
+            // HandleAppForegroundEventL method
+            iWasActiveControlGroup = ETrue;
+            }
         }
     else
         {
@@ -466,8 +476,10 @@
             iWasActiveControlGroup = EFalse;
             }
         }
-    else
+    else if ( !iWasActiveControlGroup ) // If activation of control group isn`t forced
         {
+        // Mail application is switching to background.
+        // Remember state of control group to restore it when Mail goes foreground.
         iWasActiveControlGroup = ControlGroup().AcceptInput();
         }
     }
--- a/emailuis/emailui/src/FreestyleMessageHeaderHTML.cpp	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailuis/emailui/src/FreestyleMessageHeaderHTML.cpp	Tue Apr 27 16:20:14 2010 +0300
@@ -77,7 +77,7 @@
 
 _LIT8( KDisplayImagesRightToLeft,
         "<script language=\"javascript\">var g_autoLoadImages = %d;</script><table style=\"display: none;\" id=\"displayImagesTable\" width=\"%dpx\"><tr><td align=\"left\"><input type=\"submit\" class=\"button\" value=\"%S\" onClick=\"displayImagesButtonPressed()\"/></td><td align=\"right\">%S</td></tr></table>" );
-
+_LIT8 ( KProtocolIdentifier, "://" );
 const TInt KMaxEventLength( 256 );
 const TInt KFreestyleMessageHeaderHTMLRightMarginInPx( 10 );
 const TInt KFreestyleMessageHeaderHTMLMaxBufferSizeForWidth( 5 );
@@ -1009,6 +1009,10 @@
 void CFreestyleMessageHeaderHTML::StartHyperlinkL( const TDesC8& aUrl ) const
     {
     iWriteStream.WriteL( _L8("<a href=\"") );
+    if ( aUrl.FindF( KProtocolIdentifier() ) == KErrNotFound )
+    	{
+        iWriteStream.WriteL( _L8("http://"));
+    	}
     iWriteStream.WriteL( aUrl );
     iWriteStream.WriteL( _L8("\">"));
     iWriteStream.CommitL();
--- a/emailuis/emailui/src/ncsaddressinputfield.cpp	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailuis/emailui/src/ncsaddressinputfield.cpp	Tue Apr 27 16:20:14 2010 +0300
@@ -431,7 +431,7 @@
 	if ( IsFocused() )
 		{
 		iTextEditor->SetFocus( ETrue, aDrawNow );
-        TRAP_IGNORE( iTextEditor->SetCursorPosL( iTextEditor->TextLength(), EFalse ) );
+        //TRAP_IGNORE( iTextEditor->SetCursorPosL( iTextEditor->TextLength(), EFalse ) );
 
         // make sure that control is visible on screen
 		if ( Rect().iTl.iY < 0 )
@@ -863,3 +863,8 @@
 	iPhysics = aPhysics;
     iTextEditor->EnableKineticScrollingL( aPhysics );
     }
+
+void CNcsAddressInputField::SetCursorVisible( TBool aCursorVisible )
+    {
+    iTextEditor->SetCursorVisible( aCursorVisible );
+    }
--- a/emailuis/emailui/src/ncsattachmentfield.cpp	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailuis/emailui/src/ncsattachmentfield.cpp	Tue Apr 27 16:20:14 2010 +0300
@@ -663,8 +663,8 @@
     FUNC_LOG;
     CCoeControl::HandlePointerEventL( aPointerEvent );
     
-    if ( Rect().Contains( aPointerEvent.iPosition ) &&
-         aPointerEvent.iType == TPointerEvent::EButton1Down )
+    if ( aPointerEvent.iType == TPointerEvent::EButton1Down  &&
+         Rect().Contains( aPointerEvent.iPosition ) )
         {
         TBool focusedAttachmentLabelIndexChanged( EFalse );
         TInt i( 0 );
@@ -706,7 +706,7 @@
                 iAttachmentLabels[i]->SetFocus( i==iFocusedLabelIndex );
                 }
             UpdateColors();
-            DrawNow();
+            DrawDeferred();
             }
         }
     }
--- a/emailuis/emailui/src/ncscomposeview.cpp	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailuis/emailui/src/ncscomposeview.cpp	Tue Apr 27 16:20:14 2010 +0300
@@ -52,6 +52,7 @@
 #include "FreestyleEmailUiConstants.h"
 #include "FSAutoSaver.h"
 #include "FSEmail.pan"
+#include "cmailmessageext.h"
 
 
 // line separators that should not appear in Subject
@@ -245,6 +246,9 @@
     else
         {
         DoSafeExit( ESaveDraft );
+
+        // cleaning - usefull when application is closed from task switcher
+        HideToolbar();
         }
 
     if( iFetchLogic )
@@ -710,17 +714,19 @@
     FUNC_LOG;
     if ( iContainer )
         {
-        // DimAllOptions if remotesearch is in progress, 
+        // Hide toolbar if remotesearch is in progress, 
         // because it takes you into a different view
-        TBool dimAllOptions = iContainer->IsRemoteSearchInprogress();
-        SetToolbarItemDimmed( EFsEmailUiTbCmdExpandActions, dimAllOptions );
-        SetToolbarItemDimmed( EFsEmailUiTbCmdExpandInsert, dimAllOptions );
-        SetToolbarItemDimmed( EFsEmailUiTbCmdSend, dimAllOptions 
-            || iContainer->AreAddressFieldsEmpty() );
+        TBool hideToolbar = iContainer->IsRemoteSearchInprogress();
+        SetToolbarItemDimmed( EFsEmailUiTbCmdSend, iContainer->AreAddressFieldsEmpty() );
+     
+        CAknToolbar* toolbar(Toolbar());
+        if (toolbar)
+            {
+            toolbar->SetToolbarVisibility(!hideToolbar);
+            }
         }
     }
 
-
 // -----------------------------------------------------------------------------
 // CNcsComposeView::ChildDoDeactivate()
 // Deactivate the Compose view
@@ -1346,27 +1352,29 @@
     // show file dialog and get file name
     TBool ok = EFalse;
     TInt error = KErrNone;
-    if( ! self->Toolbar()->IsDimmed())
+    CAknToolbar* toolbar = self->Toolbar();
+    if ( !toolbar->IsDimmed() )
         {
-	self->Toolbar()->SetDimmed(ETrue); 
-	}
-	
+        toolbar->SetDimmed(ETrue); 
+        }
+
     self->iContainer->SwitchChangeMskOff( ETrue );
-	TRAP( error, ok = attachmentControl->AppendAttachmentToListL(
+    TRAP( error, ok = attachmentControl->AppendAttachmentToListL(
                 self->iAttachmentAddType) );
     self->iContainer->SwitchChangeMskOff( EFalse );
-    
-	if ( ok && error == KErrNone )
-	    {
-	    TRAP( error, self->SetAttachmentLabelContentL() );
-            }
-  	
-	if(! attachmentControl->IsAttachmentAddingLocked())
-	    {
-	    self->Toolbar()->SetDimmed(EFalse); 
-	    TRAP( error, self->UpdateToolbarL());
-	    }
-	return error;
+
+    if ( ok && error == KErrNone )
+        {
+        TRAP( error, self->SetAttachmentLabelContentL() );
+        }
+
+    if ( !attachmentControl->IsAttachmentAddingLocked() )
+        {
+        toolbar->SetDimmed(EFalse);
+        self->RefreshToolbar();
+        toolbar->DrawDeferred();
+        }
+    return error;
     }
 
 // -----------------------------------------------------------------------------
@@ -2022,7 +2030,7 @@
 // -----------------------------------------------------------------------------
 //
 void CNcsComposeView::CommitL( TBool aParseAddresses,
-    TFieldToCommit aFieldToCommit, TBool aSaveNow )
+    TFieldToCommit aFieldToCommit, TBool aSaveNow, TCommitType aType  )
     {
     FUNC_LOG;
     __ASSERT_DEBUG( iNewMessage, Panic( ENcsBasicUi ) );
@@ -2118,6 +2126,19 @@
     if ( aSaveNow )
         {
         SaveMessageL();
+        
+        // If this is final commit, then inform it via extension
+        if ( aType == EFinal )
+            {
+            CMailMessageExtension* messageExtension = 
+                    static_cast<CMailMessageExtension*>
+                        ( iNewMessage->ExtensionL( KEmailMessageExtensionUid ) );
+            if ( messageExtension )
+                {
+                messageExtension->CommitL( *iNewMessage ) ;
+                iNewMessage->ReleaseExtension( messageExtension );
+                }
+            }
         }
     }
 
@@ -2754,7 +2775,7 @@
         {
         AppUi()->AddToStackL( iContainer );
         iContainer->SetMenuBar( Cba() );
-        iContainer->UpdateScrollBarL();
+        iContainer->UpdateScrollBar();
 
         // Set title pane text
         const TDesC& mbName = iMailBox->GetName();
@@ -2889,7 +2910,7 @@
         __ASSERT_DEBUG( iNewMessage, Panic( ENcsBasicUi ) );
 
         iFakeSyncGoingOn = ETrue;
-        TRAPD( error, CommitL( aParseAddresses, EAllFields, ETrue ) );
+        TRAPD( error, CommitL( aParseAddresses, EAllFields, ETrue, EFinal ) );
         iFakeSyncGoingOn = EFalse;
         User::LeaveIfError( error );
 
--- a/emailuis/emailui/src/ncscomposeviewcontainer.cpp	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailuis/emailui/src/ncscomposeviewcontainer.cpp	Tue Apr 27 16:20:14 2010 +0300
@@ -160,11 +160,11 @@
     iMessageField->SetupEditorL();
     iReadOnlyQuoteField->SetupEditorL();
 
-    SetRect( aRect );
-
     iBgContext = CAknsBasicBackgroundControlContext::NewL(
         KAknsIIDQsnBgAreaMain, Rect(), EFalse );
 
+    SetRect( aRect );
+
     iLongTapDetector = CAknLongTapDetector::NewL( this );
 
     ActivateL();
@@ -172,7 +172,6 @@
 
     // activate auto save functionality
     iAutoSaver.Enable( ETrue );
-
     }
 
 // ---------------------------------------------------------------------------
@@ -257,9 +256,6 @@
         const TPointerEvent& aPointerEvent )
     {
     FUNC_LOG;
-
-    CCoeControl::HandlePointerEventL( aPointerEvent );
-
     if ( aPointerEvent.iType != TPointerEvent::EButton1Down &&
          iHeader->NeedsLongTapL( aPointerEvent.iPosition ) )
         {
@@ -296,16 +292,12 @@
                     iMessageField->SetFocus( EFalse, ENoDrawNow );
                     iFocused = iHeader;
                     iHeader->SetFocus( ETrue,ENoDrawNow );
-                    iHeader->MakeVisible( ETrue );
-                    CommitL( EBodyField );
-                    iView.HandleContainerChangeRequiringToolbarRefresh();
                     }
                 else if ( iFocused == iReadOnlyQuoteField )
                     {
-                    iFocused = iMessageField;
                     iReadOnlyQuoteField->SetFocus( EFalse, ENoDrawNow );
+                    iFocused = iHeader;
                     iHeader->SetFocus( ETrue, ENoDrawNow );
-                    iView.HandleContainerChangeRequiringToolbarRefresh();
                     }
                 }
             else if ( iReadOnlyQuoteField->Rect().Contains( 
@@ -313,49 +305,36 @@
                 {
                 if ( iFocused == iMessageField )
                     {
+                    iMessageField->SetFocus( EFalse, ENoDrawNow );
                     iFocused = iReadOnlyQuoteField;
                     iReadOnlyQuoteField->SetFocus( ETrue, ENoDrawNow );
-                    iMessageField->SetFocus( EFalse, ENoDrawNow );
                     iReadOnlyQuoteField->SetCursorPosL( 0, EFalse );
-                    iView.HandleContainerChangeRequiringToolbarRefresh();
                     }
                 else if ( iFocused == iHeader )
                     {
+                    iHeader->SetFocus( EFalse, ENoDrawNow );
                     iFocused = iReadOnlyQuoteField;
                     iReadOnlyQuoteField->SetFocus( ETrue, ENoDrawNow );
-                    iHeader->SetFocus( EFalse, ENoDrawNow );
                     iReadOnlyQuoteField->SetCursorPosL( 0, EFalse );
-                    iView.HandleContainerChangeRequiringToolbarRefresh();
                     }
                 }
             else 
                 {
                 if ( iFocused == iHeader )
                     {
-                    //TRAP_IGNORE( DoUpdateSubjectL() );
-
                     iHeader->SetFocus( EFalse, ENoDrawNow );
                     iFocused = iMessageField;
                     iMessageField->SetFocus( ETrue, ENoDrawNow );
-                    iView.HandleContainerChangeRequiringToolbarRefresh();
                     }
                 else if ( iFocused == iReadOnlyQuoteField )
                     {
+                    iReadOnlyQuoteField->SetFocus( EFalse, ENoDrawNow );
                     iFocused = iMessageField;
-                    iReadOnlyQuoteField->SetFocus( EFalse, ENoDrawNow );
                     iMessageField->SetFocus( ETrue, ENoDrawNow );
-                    iView.HandleContainerChangeRequiringToolbarRefresh();
                     }
-                else 
+                else
                     {
-					iMessageField->ClearSelectionL();
-
-                    const TRect messageFieldRect( iMessageField->Rect() );
-                    if ( !messageFieldRect.Contains( aPointerEvent.iPosition ) && 
-                         aPointerEvent.iPosition.iY >= messageFieldRect.iTl.iY )
-                        {
-                        iMessageField->OpenVirtualKeyBoardL();
-                        }
+                    iMessageField->ClearSelectionL();
                     }
                 }
 
@@ -366,7 +345,7 @@
     		{
             if( iIsDragging && iPhysics )
                 {
-                TPoint drag( iOriginalPosition - aPointerEvent.iParentPosition );
+                TPoint drag( iOriginalPosition - aPointerEvent.iPosition );
                 iPhysics->StartPhysics( drag, iStartTime );
                 iIsFlicking = ETrue;
                 iIsDragging = EFalse;
@@ -383,6 +362,9 @@
                     {
 					// If user started dragging, cancel hotspot actions
 					iIsDragging = ETrue;
+					iMessageField->SetCursorVisible( EFalse );
+					iReadOnlyQuoteField->SetCursorVisible( EFalse );
+					iHeader->SetPhysicsEmulationOngoing( ETrue );
                     }
                 }
 
@@ -420,7 +402,7 @@
                                         totalHeight - areaHeight );
 					}
 
-				ScrollL( scrollOffset );
+				Scroll( scrollOffset );
 				}
            
 			// Save current position as previous pos for future calculations
@@ -441,6 +423,8 @@
         {
         iLongTapDetector->PointerEventL( aPointerEvent );
         }
+
+    CCoeControl::HandlePointerEventL( aPointerEvent );
     }
 
 // -----------------------------------------------------------------------------
@@ -613,7 +597,7 @@
         iReadOnlyQuoteField->SetPosition( quotePos );
 
         iSeparatorLineYPos += moveY;
-        UpdateScrollBarL();
+        UpdateScrollBar();
         }
     }
 
@@ -626,31 +610,30 @@
     {
     FUNC_LOG;
 
-	// We may not be completely constructed
-	if ( iHeader && iMessageField && iReadOnlyQuoteField )
-	    {
-	    // First, move all the controls in the header
-	    iHeader->UpdateFieldPosition( aAnchor );
+    // We may not be completely constructed
+    if ( iHeader && iMessageField && iReadOnlyQuoteField )
+        {
+        // First, move all the controls in the header
+        iHeader->UpdateFieldPosition( aAnchor );
+
+        // Then, move the body field below the header
+        TRect headerRect = iHeader->Rect();
 
-	    // Then, move the body field below the header
-	    TRect headerRect = iHeader->Rect();
-	            
-		const TSize separatorSize( 
-		        NcsUtility::SeparatorSizeInThisResolution() );
-		iSeparatorLineYPos = headerRect.iBr.iY;
-			
-		TPoint bodyPos( iMessageField->Position() );
-		bodyPos.iY = iSeparatorLineYPos + separatorSize.iHeight;
-		iMessageField->SetPosition( bodyPos );
-		
-		TPoint quotePos( iReadOnlyQuoteField->Position() );
-		quotePos.iY = iMessageField->Rect().iBr.iY;
-		iReadOnlyQuoteField->SetPosition( quotePos );
+        const TSize separatorSize( 
+            NcsUtility::SeparatorSizeInThisResolution() );
+        iSeparatorLineYPos = headerRect.iBr.iY;
+
+        TPoint bodyPos( iMessageField->Position() );
+        bodyPos.iY = iSeparatorLineYPos + separatorSize.iHeight;
+        iMessageField->SetPosition( bodyPos );
 
-	    TRAP_IGNORE( UpdateScrollBarL() );
+        TPoint quotePos( iReadOnlyQuoteField->Position() );
+        quotePos.iY = iMessageField->Rect().iBr.iY;
+        iReadOnlyQuoteField->SetPosition( quotePos );
 
-	    DrawDeferred();
-	    }
+        UpdateScrollBar();
+        DrawDeferred();
+        }
 
     }
 
@@ -723,18 +706,17 @@
     {
     FUNC_LOG;
 
-	// We may not have finished construction
-	if ( iHeader && iMessageField && iReadOnlyQuoteField && !aDoScroll )
-	    {
-	    SizeChanged();
-	    DrawDeferred();
-	    }
-	if ( iHeader && aDoScroll )
-	    {
-	    iHeader->DoScrollL();
-	    }
+    // We may not have finished construction
+    if ( iHeader && iMessageField && iReadOnlyQuoteField && !aDoScroll )
+        {
+        SizeChanged();
+        }
+    if ( iHeader && aDoScroll )
+        {
+        iHeader->DoScroll();
+        }
 
-	return EFalse;
+    return EFalse;
     }
 
 // -----------------------------------------------------------------------------
@@ -780,18 +762,16 @@
         readOnlyQuoteFieldHeight = iReadOnlyQuoteField->Rect().Height();
         }
 
-    if ( iBgContext )
-        {
-        iBgContext->SetRect( Rect() );
-        }  
+    iBgContext->SetRect( Rect() );
     iMessageField->SetRealRect( Rect() );
     iReadOnlyQuoteField->SetRealRect( Rect() );
-    
+
     TInt messageLineHeigth = 
         NcsUtility::HeaderCaptionPaneRect( cmailPaneRect ).Height();
+    iSeparatorHeight = NcsUtility::SeparatorSizeInThisResolution().iHeight;
     iMessageEditorMinHeigth = 
         cmailPaneRect.Height() - iHeader->Size().iHeight -
-        NcsUtility::SeparatorSizeInThisResolution().iHeight -
+        iSeparatorHeight -
         readOnlyQuoteFieldHeight;
     
     iMessageEditorMinHeigth -= iMessageEditorMinHeigth % messageLineHeigth;
@@ -808,9 +788,21 @@
         iMessageEditorMinHeigth = messageLineHeigth;
         }
 
-    TRAP_IGNORE( UpdateScrollBarL() );
-    DrawNow();
+	// update some layout variables
+    TRect headerRect = iHeader->Rect();
+    TRect bodyRect = iMessageField->Rect();
+    TRect quoteRect = iReadOnlyQuoteField->Rect();
+
+    iTotalComposerHeight = headerRect.Height() + iSeparatorHeight * 2 + 
+							   bodyRect.Height() + quoteRect.Height();
     
+    iVisibleAreaHeight = Rect().Height();
+        
+    UpdateScrollBar();
+
+    iScrollBarModel.SetScrollSpan( iTotalComposerHeight );
+    iScrollBarModel.SetWindowSize( iVisibleAreaHeight );
+    DrawDeferred();
     }
 
 // -----------------------------------------------------------------------------
@@ -822,14 +814,11 @@
     {
     FUNC_LOG;
 
-    if ( iBgContext )
+    CWindowGc& gc = SystemGc();
+    MAknsSkinInstance* skin = AknsUtils::SkinInstance();
+    if ( skin )
         {
-        CWindowGc& gc = SystemGc();
-        MAknsSkinInstance* skin = AknsUtils::SkinInstance();
-        if ( skin )
-            {
-            AknsDrawUtils::Background( skin, iBgContext, this, gc, aRect );
-            }
+        AknsDrawUtils::Background( skin, iBgContext, this, gc, aRect );
         }
     }
 
@@ -886,7 +875,7 @@
     HBufC* message = HBufC::NewLC( messageLength );
     TPtr messagePtr = message->Des();
     iMessageField->GetText( messagePtr );
-    NcsUtility::ConvertLineEndingsL( message );
+
     CleanupStack::Pop();
     CleanupStack::PushL( message );
     messageLength = message->Length();
@@ -939,7 +928,7 @@
         
     ClosePopupContactListL();
 
-    ScrollL( aScrollBar->ThumbPosition() );
+    Scroll( aScrollBar->ThumbPosition() );
     }
 
 // -----------------------------------------------------------------------------
@@ -1019,7 +1008,7 @@
             // Update screen position and scroll bar when text changed
             // or cursor moved
             UpdateScreenPositionL();
-            UpdateScrollBarL();
+            UpdateScrollBar();
             DrawDeferred();
             }
         }
@@ -1042,7 +1031,7 @@
         {
         if ( aDesirableEdwinSize.iHeight < iMessageEditorMinHeigth )
             {
-            ScrollL( 0 );
+            Scroll( 0 );
             }
         }
 
@@ -1079,33 +1068,27 @@
 TTypeUid::Ptr CNcsComposeViewContainer::MopSupplyObject( TTypeUid aId )
     {
     FUNC_LOG;
+    if ( aId.iUid == MAknsControlContext::ETypeId )
+        {
+        return MAknsControlContext::SupplyMopObject( aId, iBgContext );
+        }
     return CCoeControl::MopSupplyObject( aId );
     }
 
 // -----------------------------------------------------------------------------
-// CNcsComposeViewContainer::UpdateScrollBarL()
+// CNcsComposeViewContainer::UpdateScrollBar()
 // -----------------------------------------------------------------------------
 //
-void CNcsComposeViewContainer::UpdateScrollBarL()
+void CNcsComposeViewContainer::UpdateScrollBar()
     {
     FUNC_LOG;
 
     TRect headerRect = iHeader->Rect();
-    TRect bodyRect = iMessageField->Rect();
-    TRect quoteRect = iReadOnlyQuoteField->Rect();
-    const TSize separatorSize( NcsUtility::SeparatorSizeInThisResolution() );
-
-    TInt totalComposerHeight = headerRect.Height() + separatorSize.iHeight*2 + 
-							   bodyRect.Height() + quoteRect.Height();
-    
-    TInt visibleAreaHeight = Rect().Height();
     TInt visiblePosition = -headerRect.iTl.iY;
 
-    iScrollBarModel.SetScrollSpan( totalComposerHeight );
-    iScrollBarModel.SetWindowSize( visibleAreaHeight );
     iScrollBarModel.SetFocusPosition( visiblePosition );
 
-    iScrollBar->SetModelL( &iScrollBarModel );
+    iScrollBar->SetModel( &iScrollBarModel );
     iScrollBar->MakeVisible( IsVisible() );
     }
 
@@ -1808,7 +1791,7 @@
         }
     // force recalculation of the position of every component
     UpdateFieldPosition( NULL );
-    UpdateScrollBarL();
+    UpdateScrollBar();
     }
 
 // -----------------------------------------------------------------------------
@@ -1843,11 +1826,9 @@
 //
 TInt CNcsComposeViewContainer::ContentTotalHeight()
     {
-    FUNC_LOG;
-    const TSize separatorSize( NcsUtility::SeparatorSizeInThisResolution() );
-	
+    FUNC_LOG;	
 	TInt totalHeight( iHeader->Size().iHeight + 
-					  separatorSize.iHeight*2 + 
+	                  iSeparatorHeight * 2 + 
 					  iMessageField->Size().iHeight );
 
 	if( iReadOnlyQuoteField->IsVisible() )
@@ -1918,38 +1899,46 @@
     }
 
 // -----------------------------------------------------------------------------
-// CNcsComposeViewContainer::ScrollL()
+// CNcsComposeViewContainer::Scroll()
 // -----------------------------------------------------------------------------
 //
-void CNcsComposeViewContainer::ScrollL( TInt aTargetPos )
-	{
+void CNcsComposeViewContainer::Scroll( TInt aTargetPos, TBool aDrawNow )
+    {
     FUNC_LOG;
 	TPoint headerPos( iHeader->Position() );
-	
 	TInt moveY = -headerPos.iY - aTargetPos;
 	
-	if( moveY )
-		{
-		headerPos.iY += moveY;
-		iHeader->SetPosition( headerPos );
-		
-		TPoint msgPos( iMessageField->Position() );
-		msgPos.iY += moveY;
-		iMessageField->SetPosition( msgPos );
-		
-		if( iReadOnlyQuoteField->IsVisible() )
+    if ( aDrawNow )
+    	{
+		moveY = iTotalMoveY + moveY;
+		iTotalMoveY = 0;
+		if ( moveY )
 			{
-			TPoint readOnlyPos( iReadOnlyQuoteField->Position() );
-			readOnlyPos.iY += moveY;
-			iReadOnlyQuoteField->SetPosition( readOnlyPos );
+			headerPos.iY += moveY;
+			iHeader->SetPosition( headerPos );
+	
+			TPoint msgPos( iMessageField->Position() );
+			msgPos.iY += moveY;
+			iMessageField->SetPosition( msgPos );
+	
+			if( iReadOnlyQuoteField->IsVisible() )
+				{
+				TPoint readOnlyPos( iReadOnlyQuoteField->Position() );
+				readOnlyPos.iY += moveY;
+				iReadOnlyQuoteField->SetPosition( readOnlyPos );
+				}
+	
+			iSeparatorLineYPos += moveY;
+
+			UpdateScrollBar();
+			DrawNow();
 			}
-		
-		iSeparatorLineYPos += moveY;
-	
-		UpdateScrollBarL();
-		DrawDeferred();
-		}
-	}
+    	}
+    else
+    	{
+		iTotalMoveY += moveY;
+    	}    	
+    }
 
 // -----------------------------------------------------------------------------
 // CNcsComposeViewContainer::ViewPositionChanged
@@ -1957,15 +1946,12 @@
 // -----------------------------------------------------------------------------
 //
 void CNcsComposeViewContainer::ViewPositionChanged(
-        const TPoint& aNewPosition,
-        TBool /*aDrawNow*/,
-        TUint /*aFlags*/ )
+    const TPoint& aNewPosition, TBool aDrawNow, TUint /*aFlags*/ )
     {
     FUNC_LOG;
-	TInt scrollOffset = aNewPosition.iY - Rect().Size().iHeight / 2;
-
-	TRAP_IGNORE( ScrollL( scrollOffset ) );
-	}
+    TInt scrollOffset = aNewPosition.iY - iVisibleAreaHeight / 2;
+    Scroll( scrollOffset, aDrawNow );
+    }
 
 // -----------------------------------------------------------------------------
 // CNcsComposeViewContainer::PhysicEmulationEnded
@@ -1976,6 +1962,9 @@
     {
     FUNC_LOG;
     iIsFlicking = EFalse;
+    iMessageField->SetCursorVisible( ETrue );
+    iReadOnlyQuoteField->SetCursorVisible( ETrue );
+    iHeader->SetPhysicsEmulationOngoing( EFalse );
     }
 
 // -----------------------------------------------------------------------------
@@ -1986,7 +1975,7 @@
 TPoint CNcsComposeViewContainer::ViewPosition() const
     {
     FUNC_LOG;
-    return TPoint(0, -iHeader->Position().iY + Rect().Size().iHeight / 2 );
+    return TPoint(0, -iHeader->Position().iY  + iVisibleAreaHeight / 2 );
     }
 
 
--- a/emailuis/emailui/src/ncseditor.cpp	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailuis/emailui/src/ncseditor.cpp	Tue Apr 27 16:20:14 2010 +0300
@@ -83,15 +83,8 @@
 CNcsEditor::~CNcsEditor()
     {
     FUNC_LOG;
-    // <cmail> Platform layout change
-    delete iBgContext;
-    // </cmail>
     delete iGlobalCharFormat;
-    
-    if ( iEditorCustomDrawer )
-        {
-        delete iEditorCustomDrawer;        
-        }
+    delete iEditorCustomDrawer;
     delete iCaptionText;
     }
 
@@ -196,17 +189,6 @@
     }
 
 // -----------------------------------------------------------------------------
-// CNcsEditor::SetRect
-// -----------------------------------------------------------------------------
-//
-void CNcsEditor::SetRect( const TRect& aRect )
-    {
-    FUNC_LOG;
-    //CCoeControl::SetRect( aRect );
-    CEikRichTextEditor::SetRect( aRect );
-    }
-
-// -----------------------------------------------------------------------------
 // CNcsEditor::HandleResourceChange
 // -----------------------------------------------------------------------------
 //
@@ -217,8 +199,6 @@
 
     if ( aType == KAknsMessageSkinChange )
         {
-        // S60 skin support
-        UpdateGraphics();
         UpdateFontSize();
         UpdateColors();
         if ( iCustomDrawer )
@@ -292,10 +272,7 @@
     SetCursorPosL(0,EFalse);
     UpdateFontSize();
     UpdateColors();
-    // <cmail> S60 skin support
-    UpdateGraphics();
-    // </cmail>
-	}
+    }
 
 // -----------------------------------------------------------------------------
 // CNcsEditor::LineCount() const
@@ -496,41 +473,6 @@
     GlobalText()->SetGlobalCharFormat( iGlobalCharFormat );
     }
 
-// </cmail>
-
-// -----------------------------------------------------------------------------
-// CNcsEditor::UpdateGraphics
-// -----------------------------------------------------------------------------
-//
-void CNcsEditor::UpdateGraphics()
-    {
-    TRAP_IGNORE( DoUpdateGraphicsL() );
-    }
-
-// -----------------------------------------------------------------------------
-// CNcsEditor::DoUpdateGraphicsL
-// -----------------------------------------------------------------------------
-//
-void CNcsEditor::DoUpdateGraphicsL()
-    {
-	// <cmail> S60 Skin support
-    delete iBgContext;
-    iBgContext = NULL;
-
-    TSize mainPaneSize;
- 	AknLayoutUtils::LayoutMetricsSize(
- 	    AknLayoutUtils::EMainPane, mainPaneSize );
-
-    iBgContext = CAknsBasicBackgroundControlContext::NewL(
-        //KAknsIIDQgnFsGrafEmailContent,
-        KAknsIIDQsnBgAreaMain,
-        TRect( mainPaneSize ),
-        EFalse );
-
-    SetSkinBackgroundControlContextL( iBgContext );
-	// </cmail>
-    }
-
 // ---------------------------------------------------------------------------
 // CNcsEditor::GetLabelText
 // ---------------------------------------------------------------------------
--- a/emailuis/emailui/src/ncseditorcustomdraw.cpp	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailuis/emailui/src/ncseditorcustomdraw.cpp	Tue Apr 27 16:20:14 2010 +0300
@@ -82,36 +82,43 @@
     TRect& aDrawn ) const
     {
     FUNC_LOG;
-    iCustomDrawer->DrawBackground( aParam, aBackground, aDrawn );
-    TInt lineHeigth( 0 );
-    TRAP_IGNORE( lineHeigth = iEditor->GetLineHeightL() );
-
-    TAknTextDecorationMetrics decorationMetrics( iTextPaneLayout.LayoutLine().FontId() );
-    TInt topMargin, bottomMargin;
-    decorationMetrics.GetTopAndBottomMargins( topMargin, bottomMargin );
-
-    TInt lineOffset = iTextPaneLayout.H() + topMargin + bottomMargin;
+    if ( iPrevBrX == 0 )
+        {
+        const_cast<CNcsEditorCustomDraw*>(this)->iPrevBrX = aParam.iDrawRect.iBr.iX;
+        }
+    
+    // draw background if text selection is ongoing
+    if ( iEditor->SelectionLength() )
+    	{
+		iCustomDrawer->DrawBackground( aParam, aBackground, aDrawn );
+    	}
+    else
+    	{
+        aDrawn = aParam.iDrawRect;
+    	}
+    	
+    if ( aParam.iDrawRect.iTl.iX < iPrevBrX )
+        {
+        aParam.iGc.SetPenColor( iLineColor );
     
-    TRgb lineColor = NcsUtility::CalculateMsgBodyLineColor( KFSColorDarkeningDegree, 
-                                                            NcsUtility::SeparatorLineColor() );
-    aParam.iGc.SetPenColor( lineColor );
-
-    TInt margin( 0 );
-    if ( aParam.iDrawRect.Height() < lineHeigth ||
-         aParam.iDrawRect.Height() == lineOffset )
-        {
-        margin = 1;
-        }
-
-    TRect currentRect( aParam.iDrawRect.iTl , TPoint( aParam.iDrawRect.iBr.iX, aParam.iDrawRect.iTl.iY + lineOffset - margin ));
+        TInt margin( 0 );
+        if ( aParam.iDrawRect.Height() < iLineHeigth ||
+             aParam.iDrawRect.Height() == iLineOffset )
+            {
+            margin = 1;
+            }
     
-    while ( currentRect.iBr.iY <= aParam.iDrawRect.iBr.iY )
-        {
-        if ( currentRect.iTl.iY >= aParam.iDrawRect.iTl.iY  )
+        TRect currentRect( aParam.iDrawRect.iTl , TPoint( aParam.iDrawRect.iBr.iX, aParam.iDrawRect.iTl.iY + iLineOffset - margin ));
+        
+        while ( currentRect.iBr.iY <= aParam.iDrawRect.iBr.iY )
             {
-            aParam.iGc.DrawLine( TPoint( currentRect.iTl.iX, currentRect.iBr.iY), currentRect.iBr );
+            if ( currentRect.iTl.iY >= aParam.iDrawRect.iTl.iY  )
+                {
+                aParam.iGc.DrawLine( TPoint( currentRect.iTl.iX, currentRect.iBr.iY), currentRect.iBr );
+                }
+            currentRect.Move( 0, iLineHeigth );
             }
-        currentRect.Move( 0, lineHeigth );
+        const_cast<CNcsEditorCustomDraw*>(this)->iPrevBrX = aParam.iDrawRect.iBr.iX;
         }
     }
 
@@ -164,4 +171,12 @@
 void CNcsEditorCustomDraw::UpdateLayout( TAknTextComponentLayout aLayout )
     {
     iTextPaneLayout = aLayout;
+    TRAP_IGNORE( iLineHeigth = iEditor->GetLineHeightL() );
+    iLineColor = NcsUtility::CalculateMsgBodyLineColor( KFSColorDarkeningDegree, 
+                                                            NcsUtility::SeparatorLineColor() );
+    TAknTextDecorationMetrics decorationMetrics( iTextPaneLayout.LayoutLine().FontId() );
+    TInt topMargin, bottomMargin;
+    decorationMetrics.GetTopAndBottomMargins( topMargin, bottomMargin );
+
+    iLineOffset = iTextPaneLayout.H() + topMargin + bottomMargin;
     }
--- a/emailuis/emailui/src/ncsheadercontainer.cpp	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailuis/emailui/src/ncsheadercontainer.cpp	Tue Apr 27 16:20:14 2010 +0300
@@ -170,9 +170,6 @@
 	        this, iMailBox, *this, remoteLookupSupported );
 	iAacListBox->MakeVisible( EFalse );
 
-    iBgContext = CAknsBasicBackgroundControlContext::NewL(
-        KAknsIIDQsnBgAreaMain, Rect(), EFalse );
-
     iRALInProgress = EFalse;
 
     iToField->EnableKineticScrollingL( iPhysics );
@@ -194,7 +191,6 @@
     delete iAttachmentField;
 	delete iAacListBox;
 	delete iLongTapDetector;
-	delete iBgContext;
 	}
 
 // ---------------------------------------------------------------------------
@@ -263,18 +259,6 @@
 void CNcsHeaderContainer::Draw( const TRect& /*aRect*/ ) const
 	{
     FUNC_LOG;
-
-    if ( iBgContext )
-        {
-        CWindowGc& gc = SystemGc();
-
-        MAknsSkinInstance* skin = AknsUtils::SkinInstance();
-
-        if ( skin )
-            {
-            AknsDrawUtils::Background( skin, iBgContext, this, gc, Rect() );
-            }
-        }
 	}
 
 // -----------------------------------------------------------------------------
@@ -401,7 +385,7 @@
 				
 				CNcsComposeViewContainer* container = 
 					static_cast<CNcsComposeViewContainer*>( &iParent );
-				container->UpdateScrollBarL();
+				container->UpdateScrollBar();
 				}
 			
 			if( iLongTapEventConsumed )
@@ -425,10 +409,7 @@
 	        }
         }
 
-    if ( aPointerEvent.iType != TPointerEvent::EDrag )
-    	{
-		CCoeControl::HandlePointerEventL( aPointerEvent );
-    	}
+	CCoeControl::HandlePointerEventL( aPointerEvent );
     }
 
 // -----------------------------------------------------------------------------
@@ -463,7 +444,6 @@
     {
 	FUNC_LOG;
 
-    CCoeControl* control = FindFocused();
     TRect rect = iAttachmentField->Rect();
     TBool result( EFalse );
 	if( iAttachmentField->IsVisible() && rect.Contains( aPenEventLocation ) &&
@@ -572,7 +552,7 @@
 
     if( doScroll )
     	{
-    	DoScrollL();
+    	DoScroll();
     	}
 
     return ret;
@@ -665,8 +645,8 @@
     // if focus was changed, update scroll bar
     if ( ret == EKeyWasConsumed )
         {
-        container->UpdateScrollBarL();
-        DoScrollL();
+        container->UpdateScrollBar();
+        DoScroll();
         }
 
 	// NOTE: If we're leaving the header (down was pushed on last control)
@@ -765,10 +745,9 @@
 // set size
 // -----------------------------------------------------------------------------
 void CNcsHeaderContainer::PositionChanged()
-	{
+    {
     FUNC_LOG;
-	DrawDeferred();
-	}
+    }
 
 // -----------------------------------------------------------------------------
 // CNcsHeaderContainer::ChangePositions()
@@ -1328,10 +1307,10 @@
 // CNcsHeaderContainer::CalculatePopupRect
 // -----------------------------------------------------------------------------
 TRect CNcsHeaderContainer::CalculatePopupRect()
-	{
+    {
     FUNC_LOG;
     // get focused control rect
-	TRect popupRect;
+    TRect popupRect;
 
     CCoeControl* focused = FindFocused();
     if ( IsAddressInputField( focused ) )
@@ -1339,18 +1318,18 @@
         CNcsAddressInputField* aifEditor =
             static_cast<CNcsAddressInputField*>( focused );
 
+        TPoint editorPos = aifEditor->Editor()->PositionRelativeToScreen();
         TRect editorRect = aifEditor->Editor()->Rect();
-        
-        popupRect.iTl =
-            TPoint( editorRect.iTl.iX - 1, 
-                    editorRect.iTl.iY + aifEditor->CursorPosition() + 1 );
-        
-        popupRect.iBr = 
-            TPoint( editorRect.iBr.iX + 1, iParent.Rect().iBr.iY );
+
+        popupRect.iTl = TPoint( editorPos.iX, 
+            editorPos.iY + aifEditor->CursorPosition() + 1 );
+
+        popupRect.iBr = TPoint( editorPos.iX + editorRect.Width(),
+            iParent.PositionRelativeToScreen().iY + iParent.Rect().Height() );
         }
 
     return popupRect;
-	}
+    }
 
 // -----------------------------------------------------------------------------
 // CNcsHeaderContainer::DoPopupSelect
@@ -1403,11 +1382,19 @@
                 // selected contact doesn't have email address, launch remote
                 // contact lookup rcl must be usable, since otherwise there 
                 // couldn't be any items without email addresses
+                iRALInProgress = ETrue; 
                 CPbkxRemoteContactLookupServiceUiContext::TResult::TExitReason
                     exitReason;
                 CNcsEmailAddressObject* remAddress = ExecuteRemoteSearchL(
                     exitReason,
                     emailAddress->DisplayName() );
+                iRALInProgress = EFalse;
+                // Refresh the toolbar. It was hidden during the remote search 
+                // and now it needs to be shown. FocusChanged () will do it. 
+                CNcsComposeViewContainer& parent = 
+                    static_cast<CNcsComposeViewContainer&>( iParent );
+                parent.FocusChanged( EDrawNow );
+                
                 if ( remAddress )
                     {
                     CleanupStack::PushL( remAddress );
@@ -1795,7 +1782,7 @@
     	aifFocused = static_cast<CNcsAddressInputField*>( focused );
     	aifFocused->AddAddressL( aEml );
 	    }
-	DoScrollL();
+    DoScroll();
     }
 
 // ---------------------------------------------------------------------------
@@ -2036,10 +2023,10 @@
     }
 
 // -----------------------------------------------------------------------------
-// CNcsHeaderContainer::DoScrollL
+// CNcsHeaderContainer::DoScroll
+// -----------------------------------------------------------------------------
 // 
-// -----------------------------------------------------------------------------
-void CNcsHeaderContainer::DoScrollL()
+void CNcsHeaderContainer::DoScroll()
     {
     // scroll the screen if the cursor goes beyond the screen
     CNcsComposeViewContainer& parent = static_cast<CNcsComposeViewContainer&>( iParent );
@@ -2048,17 +2035,27 @@
     TInt cursorPos( CursorPosition() );
     TInt lineHeight( Rect().Height() / LineCount() );
     TInt screenHeight( parent.Rect().Height() );
-    
-    if( cursorPos - lineHeight < screenPos )
+
+    if ( cursorPos - lineHeight < screenPos )
         {
         screenPos = cursorPos - lineHeight;             
         }
-    else
-    if( cursorPos + lineHeight > screenPos + screenHeight )
+    else if( cursorPos + lineHeight > screenPos + screenHeight )
         {
         screenPos = cursorPos + lineHeight - screenHeight;
         }
-    
-    parent.ScrollL( screenPos );
-    PositionChanged();    
+
+    parent.Scroll( screenPos );
     }
+
+// ---------------------------------------------------------------------------
+// CNcsHeaderContainer::SetPhysicsEmulationOngoing
+// ---------------------------------------------------------------------------
+//
+void CNcsHeaderContainer::SetPhysicsEmulationOngoing( TBool aPhysOngoing )
+    {
+    iToField->SetCursorVisible( !aPhysOngoing );
+    iCcField->SetCursorVisible( !aPhysOngoing );
+    iBccField->SetCursorVisible( !aPhysOngoing );
+    iSubjectField->SetCursorVisible( !aPhysOngoing );
+    }
--- a/emailuis/emailui/src/ncspopuplistbox.cpp	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailuis/emailui/src/ncspopuplistbox.cpp	Tue Apr 27 16:20:14 2010 +0300
@@ -26,6 +26,8 @@
 #include <aknnotewrappers.h>					//For LanguageNotSupported errorNote
 #include <aknsdrawutils.h>
 #include <aknsutils.h>
+#include <aknlayoutscalable_apps.cdl.h>
+#include <aknlayoutscalable_avkon.cdl.h>
 
 #include "ncspopuplistbox.h"
 #include "ncsemailaddressobject.h"					// CNcsEmailAddressObject
@@ -39,7 +41,6 @@
 #include "FSDelayedLoader.h"
 #include "FreestyleEmailUiCLSItem.h"
 
-const TInt KBackgroundFrameWidth = 4;
 const TInt KHighlightFrameWidth = 2;
 
 // ========================= MEMBER FUNCTIONS ==================================
@@ -67,10 +68,14 @@
 CNcsPopupListBox::CNcsPopupListBox( CNcsHeaderContainer& aHeaderContainer, 
                                     TBool aRemoteLookupSupported, 
                                     CFSMailBox& aMailBox)
-	: iHeaderContainer( aHeaderContainer ),iMailBox( aMailBox ),
-	  iRemoteLookupSupported( aRemoteLookupSupported ),iCachingInProgress( EFalse )
+    : iHeaderContainer( aHeaderContainer ),
+      iMailBox( aMailBox ),
+      iRemoteLookupSupported( aRemoteLookupSupported ),
+      iCachingInProgress( EFalse ),
+      iAppUi( static_cast<CFreestyleEmailUiAppUi*>( iEikonEnv->AppUi() ) )
     {
     FUNC_LOG;
+    iPopupMaxRect = TRect( 100, 100, 100, 100 );
     }
 
 // -----------------------------------------------------------------------------
@@ -79,9 +84,11 @@
 void CNcsPopupListBox::ConstructL( const CCoeControl* aParent )
     {
     FUNC_LOG;
-    CEikTextListBox::ConstructL( aParent, CEikListBox::EPopout );
-    // Create non-window-owning scrollbar to avoid flickering.
-    CEikScrollBarFrame* frame = CreateScrollBarFrameL( EFalse, EFalse, EFalse );
+    CEikTextListBox::ConstructL( NULL, CEikListBox::EPopout );
+    SetMopParent( const_cast<CCoeControl*>( aParent ) );
+    User::LeaveIfError( SetParent( const_cast<CCoeControl*>( aParent ) ) );
+
+    CEikScrollBarFrame* frame = CreateScrollBarFrameL( EFalse, EFalse, ETrue );
 
     CEikTextListBox::SetBorder( TGulBorder::ENone );
 
@@ -89,7 +96,7 @@
     CEikTextListBox::SetItemHeightL( font->FontMaxHeight() + 12 );
 
     iBackgroundContext = CAknsFrameBackgroundControlContext::NewL(
-        KAknsIIDQsnFrPopup, Rect(), Rect(), EFalse );
+        KAknsIIDQsnFrPopupSub, Rect(), Rect(), EFalse );
     UpdateTextColors();
 
     iContactHandler = CFsDelayedLoader::InstanceL()->GetContactHandlerL();
@@ -98,7 +105,6 @@
         iContactHandler = NULL;
         }
 
-    iAppUi = static_cast<CFreestyleEmailUiAppUi*>( iEikonEnv->AppUi() );
     SetListBoxObserver( this );
     }
 
@@ -155,12 +161,17 @@
 void CNcsPopupListBox::SizeChanged()
     {
     FUNC_LOG;
-    TRect outerRect = Rect();
-    TRect innerRect = outerRect;
-    innerRect.Shrink( KBackgroundFrameWidth, KBackgroundFrameWidth );
+    const TRect outerRect = Rect();
+
+    TAknLayoutRect subpane;
+    subpane.LayoutRect( outerRect, 
+        AknLayoutScalable_Avkon::bg_popup_sub_pane_g1() );
+    const TRect innerRect = subpane.Rect();
+
+    iBackgroundContext->SetFrameRects( outerRect, innerRect );
+
     SetViewRectFromClientRect( innerRect );
     TRAP_IGNORE( HandleViewRectSizeChangeL() );
-    iBackgroundContext->SetFrameRects( outerRect, innerRect );
     }
 
 void CNcsPopupListBox::HandleResourceChange( TInt aType )
@@ -174,32 +185,7 @@
 
 void CNcsPopupListBox::HandlePointerEventL( const TPointerEvent& aPointerEvent )
     {
-    // When scrollbar is non-window-owning, the pointer events should be passed
-    // to it through control hierachy, but the CEikTextListBox does not seem to 
-    // do that, so that is handled here.
-    CEikScrollBar* sb = iSBFrame->VerticalScrollBar();
-    if ( aPointerEvent.iType == TPointerEvent::EButton1Down )
-        {
-        if ( sb && sb->Rect().Contains( aPointerEvent.iPosition ) )
-            {
-            sb->ClaimPointerGrab( EFalse );
-            sb->HandlePointerEventL( aPointerEvent );
-            }
-        else
-            {
-            ClaimPointerGrab( EFalse );
-            }
-        }
-
-    CCoeControl* pointerRecipient = GrabbingComponent();
-    if ( sb && pointerRecipient == sb )
-        {
-        sb->HandlePointerEventL( aPointerEvent );
-        }
-    else
-        {
-        CEikTextListBox::HandlePointerEventL( aPointerEvent );
-        }
+    CEikTextListBox::HandlePointerEventL( aPointerEvent );
     }
 
 // -----------------------------------------------------------------------------
@@ -372,7 +358,8 @@
     {
     FUNC_LOG;
     iPopupMaxRect = aPopupMaxRect;
-    SetPopupHeight();
+
+    SetPopupRect();
     TRAP_IGNORE( UpdateScrollBarsL() );
     TRAP_IGNORE( SetScrollBarVisibilityL() );
     }
@@ -449,82 +436,116 @@
 	// Update rmlu item
 	SetRemoteLookupItemFirstToTheListL();
 	
-	SetPopupHeight();
+	SetPopupRect();
 	SetScrollBarVisibilityL();
 	HandleItemAdditionL();
-	
-	if( iItemTextsArray && iItemTextsArray->Count() > 0 ) 
-		SetCurrentItemIndex( 0 );
+
+    if ( iItemTextsArray && iItemTextsArray->Count() > 0 )
+        {
+        SetCurrentItemIndex( 0 );
+        }
 
-	if( IsVisible() )
-		DrawDeferred();
-	}
+    if ( IsVisible() )
+        {
+        DrawDeferred();
+        }
+    }
 
 // -----------------------------------------------------------------------------
 // CNcsPopupListBox::RoundToItemHeight
 // -----------------------------------------------------------------------------
 TInt CNcsPopupListBox::RoundToItemHeight(const TInt aPopupHeight) const
     {
-	TReal fullItems; // number of full visible items in window
-	TInt err = Math::Round(fullItems, (aPopupHeight / ItemHeight()), 0);
-	if(err == KErrNone)
-	    {
-	    return (TInt)(fullItems * ItemHeight()); 
-	    }
-	return aPopupHeight; // in case of error
+    TReal fullItems; // number of full visible items in window
+    TInt err = Math::Round(fullItems, (aPopupHeight / ItemHeight()), 0);
+    if (err == KErrNone)
+        {
+        return (TInt)(fullItems * ItemHeight()); 
+        }
+    return aPopupHeight; // in case of error
     }
 
 // -----------------------------------------------------------------------------
-// CNcsPopupListBox::SetPopupHeight
+// CNcsPopupListBox::SetPopupRect
 // -----------------------------------------------------------------------------
-void CNcsPopupListBox::SetPopupHeight()
+void CNcsPopupListBox::SetPopupRect()
     {
     FUNC_LOG;
+    // The popup width and horizontal position is adjusted so that it
+    // will be within the area specified in both layout data and the set
+    // maximum rect.
+    TAknLayoutRect editorPane;
+    editorPane.LayoutRect( iAppUi->ClientRect(),
+        TAknWindowComponentLayout::Compose(
+            TAknWindowComponentLayout::Compose(
+                AknLayoutScalable_Apps::list_cmail_pane(),
+                AknLayoutScalable_Apps::list_single_cmail_header_detail_pane( 0 ) ),
+            AknLayoutScalable_Apps::list_single_cmail_header_editor_pane_bg( 4 ) ) );
+    TRect editorPaneRect = editorPane.Rect();
+
+    TRect newRect = iPopupMaxRect;
+    newRect.iTl.iX = Max( iPopupMaxRect.iTl.iX, editorPaneRect.iTl.iX );
+    newRect.iBr.iX = Min( iPopupMaxRect.iBr.iX, editorPaneRect.iBr.iX );
+
+    // Thhe popup height and vertical position is adjusted based on the
+    // available space below and above the cursor and the number of items
+    // in the list.
+    const TRect rect = iPopupMaxRect;
+    TAknLayoutRect subpane;
+    subpane.LayoutRect( rect, AknLayoutScalable_Avkon::bg_popup_sub_pane_g1() );
+    const TRect subpaneRect = subpane.Rect();
+
+    const TInt frameHeights = iPopupMaxRect.Height() - subpaneRect.Height();
+
     // This is the total height in pixels needed to show all items
-    TInt minimumHeight = 2 * KBackgroundFrameWidth +
+    TInt minimumHeight = frameHeights + 
         CalcHeightBasedOnNumOfItems( Model()->NumberOfItems() );
-    TRect newRect = iPopupMaxRect;
-    TInt areaHeight = Parent()->Parent()->Rect().Height();
-    TInt halfAreaHeight = areaHeight/2;
+
+    CCoeControl* container = Parent()->Parent();
+    TInt containerTop = container->PositionRelativeToScreen().iY;
+    TInt containerHeight = container->Rect().Height();
+    TInt containerCenter = containerTop + containerHeight / 2;
 
     // Get height of one line in Address field
     CNcsHeaderContainer* headerObj = static_cast<CNcsHeaderContainer* >(Parent());
     TInt toLineHeight = headerObj->GetToLineHeight(); // height of one line height
-    if(toLineHeight == 0)
-    	{
+    if ( toLineHeight == 0 )
+        {
         toLineHeight = ItemHeight();
-    	}
-    
+        }
+
     TInt newHeight = minimumHeight; // default window height
-    
-    //latch listbox on the bottom of the editor field
-    if ( newRect.iTl.iY <= halfAreaHeight ) 
+
+    // latch listbox on the bottom of the editor field
+    if ( newRect.iTl.iY <= containerCenter ) 
         {
-        newHeight = RoundToItemHeight( areaHeight - newRect.iTl.iY );
-        if(newHeight > minimumHeight)
-        	{
+        TInt maxHeight = containerHeight - ( newRect.iTl.iY - containerTop ); 
+        newHeight = RoundToItemHeight( maxHeight - frameHeights ) + frameHeights;
+        if ( newHeight > minimumHeight )
+            {
             newHeight = minimumHeight; // shrink window (if needed)
-          	}
+            }
         }
-    //latch listbox on the top of the editor field
+    // latch listbox on the top of the editor field
     else
-     	{
+        {
         TInt yOffset = -minimumHeight - toLineHeight; // how much up
         TInt newTlY = newRect.iTl.iY + yOffset;       // new Top Left Y coordinate
-        if(newTlY>=0)
-          	{
+        if ( newTlY >= containerTop )
+            {
             newRect.Move( 0, yOffset );
             }
         else
-        	{
+            {
             // shrink height to visible area and move
-            newHeight = RoundToItemHeight( minimumHeight + newTlY);
-            newRect.Move( 0, -newHeight - toLineHeight);
+            TInt maxHeight = newRect.iTl.iY - toLineHeight - containerTop;
+            newHeight = RoundToItemHeight( maxHeight - frameHeights ) + frameHeights;
+            newRect.Move( 0, -newHeight - toLineHeight );
             }
-     	}
-    newRect.SetHeight(newHeight); // set new height
-	SetRect( newRect );
-	}
+        }
+    newRect.SetHeight( newHeight ); // set new height
+    SetRect( newRect );
+    }
 
 // -----------------------------------------------------------------------------
 // CNcsPopupListBox::SetScrollBarVisibilityL
@@ -669,8 +690,16 @@
     { 
     // temporary const_cast to get the scrollbar width
     CNcsPopupListBox& tmpListBox = const_cast<CNcsPopupListBox&>( iListBox );
-    itemRect.Resize( -tmpListBox.ScrollBarFrame()->ScrollBarBreadth(
-        CEikScrollBar::EVertical ) + KBackgroundFrameWidth, 0 );
+    const TInt scrollbarBreadth = tmpListBox.ScrollBarFrame()->
+        ScrollBarBreadth( CEikScrollBar::EVertical );
+    if ( AknLayoutUtils::LayoutMirrored() )
+        {
+        itemRect.iTl.iX = iListBox.Rect().iTl.iX + scrollbarBreadth;
+        }
+    else
+        {
+        itemRect.iBr.iX = iListBox.Rect().iBr.iX - scrollbarBreadth;
+        }
     }
 
     TRect textRect = itemRect;
@@ -683,11 +712,11 @@
     MAknsControlContext* cc = AknsDrawUtils::ControlContext( &iListBox );
     if ( cc )
         {
-        AknsDrawUtils::Background( skin, cc, *iGc, itemRect );
+        AknsDrawUtils::Background( skin, cc, *iGc, aActualItemRect );
         }
     else
         {
-        iGc->Clear( itemRect );
+        iGc->Clear( aActualItemRect );
         }
 
     // Draw the highlight, when necessary.
@@ -881,19 +910,20 @@
         }
     }
 
-void CNcsPopupListBox::Draw( const TRect& aRect ) const
+void CNcsPopupListBox::Draw( const TRect& /*aRect*/ ) const
     {
     CWindowGc& gc = SystemGc();
     MAknsSkinInstance* skin = AknsUtils::SkinInstance();
     if ( iBackgroundContext )
         {
-        AknsDrawUtils::Background( skin, iBackgroundContext, gc, aRect );
+        AknsDrawUtils::DrawBackground( skin, iBackgroundContext, this, gc,
+            Rect().iTl, Rect(), KAknsDrawParamNoClearUnderImage );
         }
     else
         {
-        gc.Clear( aRect );
+        gc.Clear( Rect() );
         }
-    CEikListBox::Draw( aRect );
+    CEikListBox::Draw( Rect() );
     }
 
 // End of File
--- a/emailuis/emailui/src/ncssubjectfield.cpp	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailuis/emailui/src/ncssubjectfield.cpp	Tue Apr 27 16:20:14 2010 +0300
@@ -253,7 +253,7 @@
 	if ( IsFocused() )
 		{
 		iTextEditor->SetFocus( ETrue );
-		TRAP_IGNORE( iTextEditor->SetCursorPosL( iTextEditor->TextLength(), EFalse ) ); 
+		//TRAP_IGNORE( iTextEditor->SetCursorPosL( iTextEditor->TextLength(), EFalse ) ); 
 
 		// make sure that control is visible on screen
 		if ( Rect().iTl.iY < 0 )
@@ -601,3 +601,8 @@
     {
     iTextEditor->EnableKineticScrollingL(aPhysics);
     }
+
+void CNcsSubjectField::SetCursorVisible( TBool aCursorVisible )
+    {
+    iTextEditor->SetCursorVisible( aCursorVisible );
+    }
--- a/emailuis/uicomponents/group/fs_generic.mmp	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailuis/uicomponents/group/fs_generic.mmp	Tue Apr 27 16:20:14 2010 +0300
@@ -140,7 +140,8 @@
 LIBRARY               flogger.lib
 LIBRARY               aknphysics.lib
 LIBRARY               cmaillogger.lib
-LIBRARY 			  aknicon.lib
+LIBRARY               aknicon.lib
+LIBRARY               aknlayout2.lib
 LIBRARY               touchfeedback.lib
 
 DEFFILE               fs_generic_alf.def
--- a/emailuis/uicomponents/inc/cuicscrollbar.h	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailuis/uicomponents/inc/cuicscrollbar.h	Tue Apr 27 16:20:14 2010 +0300
@@ -173,6 +173,11 @@
      */
     void SetThumbAnchors();
 
+    /**
+     * Reads values from layout
+     */
+    void UpdateLayoutValues();
+
 private:
 
     /**
--- a/emailuis/uicomponents/src/cuicscrollbar.cpp	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailuis/uicomponents/src/cuicscrollbar.cpp	Tue Apr 27 16:20:14 2010 +0300
@@ -24,6 +24,8 @@
 #include <alf/alftexture.h>
 #include <alf/alfanchorlayout.h>
 #include <alf/alfdecklayout.h>
+#include <AknUtils.h>
+#include <aknlayoutscalable_apps.cdl.h>
 
 // Constants
 
@@ -34,11 +36,27 @@
 // Background opacity (visible)
 const TReal32 KVisibleOpacityBackground = 0.65f;
 // How long scrollbar will be visible after change
-const TReal32 KVisibleTimeout = 500;
+const TReal32 KVisibleTimeout = 250;
 // How long fading will take
 const TReal32 KFadeTimeout = 500;
-// Width of the scrollbar (this will be replaced with value from layout)
-const TInt KScrollBarWidth = 18;
+
+// Local methods
+
+// ---------------------------------------------------------------------------
+// ScrollBarWidth
+// ---------------------------------------------------------------------------
+TInt ScrollBarWidth()
+    {
+    FUNC_LOG;
+    TRect mainPaneRect;
+    AknLayoutUtils::LayoutMetricsRect( AknLayoutUtils::EMainPane, mainPaneRect );
+    TAknLayoutRect layoutRect;
+    layoutRect.LayoutRect( mainPaneRect, AknLayoutScalable_Apps::main_sp_fs_email_pane() );
+    layoutRect.LayoutRect( layoutRect.Rect(), AknLayoutScalable_Apps::listscroll_cmail_pane() );
+    layoutRect.LayoutRect( layoutRect.Rect(), AknLayoutScalable_Apps::list_cmail_pane() );    
+    layoutRect.LayoutRect( layoutRect.Rect(), AknLayoutScalable_Apps::sp_fs_scroll_pane_cp02() );
+    return layoutRect.Rect().Width();
+    }
 
 // CUiCCompositeImage
 
@@ -111,6 +129,8 @@
 void CUiCCompositeImage::SetAnchors()
     {
     FUNC_LOG;
+    const TInt width( ScrollBarWidth() );
+    
     // iTop
     iLayout->SetAnchor(
             EAlfAnchorTopLeft, 0,
@@ -121,26 +141,26 @@
             EAlfAnchorBottomRight, 0,
             EAlfAnchorOriginRight, EAlfAnchorOriginTop,
             EAlfAnchorMetricAbsolute, EAlfAnchorMetricAbsolute,
-            TAlfTimedPoint( 0, KScrollBarWidth  ) );
+            TAlfTimedPoint( 0, width  ) );
 
     // iMiddle
     iLayout->SetAnchor(
             EAlfAnchorTopLeft, 1,
             EAlfAnchorOriginLeft, EAlfAnchorOriginTop,
             EAlfAnchorMetricAbsolute, EAlfAnchorMetricAbsolute,
-            TAlfTimedPoint( 0, KScrollBarWidth ) );
+            TAlfTimedPoint( 0, width ) );
     iLayout->SetAnchor(
             EAlfAnchorBottomRight, 1,
             EAlfAnchorOriginRight, EAlfAnchorOriginBottom,
             EAlfAnchorMetricAbsolute, EAlfAnchorMetricAbsolute,
-            TAlfTimedPoint( 0, -KScrollBarWidth  ) );
+            TAlfTimedPoint( 0, -width  ) );
 
     // iBottom
     iLayout->SetAnchor(
             EAlfAnchorTopLeft, 2,
             EAlfAnchorOriginLeft, EAlfAnchorOriginBottom,
             EAlfAnchorMetricAbsolute, EAlfAnchorMetricAbsolute,
-            TAlfTimedPoint( 0, -KScrollBarWidth ) );
+            TAlfTimedPoint( 0, -width ) );
     iLayout->SetAnchor(
             EAlfAnchorBottomRight, 2,
             EAlfAnchorOriginRight, EAlfAnchorOriginBottom,
@@ -332,13 +352,15 @@
 
     if ( aBitmap )
         {
+        const TInt width( ScrollBarWidth() );
+
         TAknContentDimensions origDim;
         AknIconUtils::GetContentDimensions( aBitmap, origDim );
         TSize iconSize( origDim.iWidth, origDim.iHeight );
-        if (iconSize.iWidth != KScrollBarWidth && iconSize.iWidth > 0)
+        if (iconSize.iWidth != width && iconSize.iWidth > 0)
             {
-            iconSize.iHeight = iconSize.iHeight * KScrollBarWidth / iconSize.iWidth;
-            iconSize.iWidth = KScrollBarWidth;
+            iconSize.iHeight = iconSize.iHeight * width / iconSize.iWidth;
+            iconSize.iWidth = width;
             }
         AknIconUtils::DisableCompression( aBitmap );
         AknIconUtils::SetSize( aBitmap, iconSize, EAspectRatioNotPreserved );
@@ -400,7 +422,7 @@
             Env().TextureManager().CreateTextureL( EThumbMiddle, this, EAlfTextureFlagSkinContent ),
             Env().TextureManager().CreateTextureL( EThumbBottom, this, EAlfTextureFlagSkinContent ) );
     iThumbVisual->Layout().SetFlags( EAlfVisualFlagDrawAfterOthers );
-    SetAnchors();
+    SetAnchors();    
     }
 
 // ---------------------------------------------------------------------------
@@ -425,7 +447,7 @@
             EAlfAnchorTopLeft, 0,
             EAlfAnchorOriginRight, EAlfAnchorOriginTop,
             EAlfAnchorMetricAbsolute, EAlfAnchorMetricAbsolute,
-            TAlfTimedPoint( -KScrollBarWidth, 0 ) );
+            TAlfTimedPoint( -ScrollBarWidth(), 0 ) );
     iBgLayout->SetAnchor(
             EAlfAnchorBottomRight, 0,
             EAlfAnchorOriginRight, EAlfAnchorOriginBottom,
@@ -445,7 +467,7 @@
             EAlfAnchorTopLeft, 0,
             EAlfAnchorOriginRight, EAlfAnchorOriginTop,
             EAlfAnchorMetricAbsolute, EAlfAnchorMetricAbsolute,
-            TAlfTimedPoint( -KScrollBarWidth, iModel.ThumbPosition() ) );
+            TAlfTimedPoint( -ScrollBarWidth(), iModel.ThumbPosition() ) );
     iThumbLayout->SetAnchor(
             EAlfAnchorBottomRight, 0,
             EAlfAnchorOriginRight, EAlfAnchorOriginTop,
--- a/emailuis/uicomponents/src/fstreeplaintwolineitemvisualizer.cpp	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailuis/uicomponents/src/fstreeplaintwolineitemvisualizer.cpp	Tue Apr 27 16:20:14 2010 +0300
@@ -12,7 +12,7 @@
 * Contributors:
 *
 *  Description : A visualizer for data items with plain text.
-*  Version     : %version: tr1sido#16 %
+*  Version     : %version: tr1sido#17 %
 *
 */
 
@@ -1247,13 +1247,8 @@
         if ((iFlags & KFsTreeListItemAlwaysExtended) ||
                 (iFlags & KFsTreeListItemExtended))
             {
-            TRect secondLineParentRect;
-            
-            // WORKAROUND FIX FOR LAYOUT PROBLEM -- RETURN THIS TO NORMAL WHEN LAYOUT'S ARE OK
-            //CFsLayoutManager::LayoutMetricsRect(currentSize, CFsLayoutManager::EFsLmListSingleDycRowPane, secondLineParentRect, 1, 1);
-            CFsLayoutManager::LayoutMetricsRect(currentSize, CFsLayoutManager::EFsLmListSingleDycRowPane, secondLineParentRect, 2, 1);
-            // WORKAROUND FIX FOR LAYOUT PROBLEM -- RETURN THIS TO NORMAL WHEN LAYOUT'S ARE OK
-            
+            TRect secondLineParentRect;            
+            CFsLayoutManager::LayoutMetricsRect(currentSize, CFsLayoutManager::EFsLmListSingleDycRowPane, secondLineParentRect, 1, 1);            
             CFsLayoutManager::LayoutMetricsRect(secondLineParentRect, CFsLayoutManager::EFsLmListSingleDycRowTextPane, secondLineParentRect, secondLineTextVariety);
             CFsLayoutManager::LayoutMetricsText(secondLineParentRect,
                     secondLineTextMetrics, subjTextInfo, secondLineTextVariety);
--- a/emailuis/widget/emailwidgetsettings/src/emailwidgetsettingsappui.cpp	Wed Apr 14 15:42:15 2010 +0300
+++ b/emailuis/widget/emailwidgetsettings/src/emailwidgetsettingsappui.cpp	Tue Apr 27 16:20:14 2010 +0300
@@ -62,6 +62,7 @@
     const TInt count = args->Count();
     if (count!=2)
         {
+        CleanupStack::PopAndDestroy(args);
         Exit();
         }
   
@@ -69,7 +70,7 @@
     CleanupStack::PushL(view);
 
     AddViewL(view);     // transfer ownership to CAknViewAppUi
-    CleanupStack::Pop(); //view
+    CleanupStack::Pop(view); //view
 
     view->ConstructL();
     SetDefaultViewL(*view);
Binary file help/data/xhtml.zip has changed
--- a/help/inc/cmail.hlp.hrh	Wed Apr 14 15:42:15 2010 +0300
+++ b/help/inc/cmail.hlp.hrh	Tue Apr 27 16:20:14 2010 +0300
@@ -9,7 +9,7 @@
 * Initial Contributors:
 * Nokia Corporation - initial contribution.
 *
-* Contributors: .
+* Contributors:
 * 
 * Description:
 *
@@ -79,5 +79,6 @@
 _LIT(KFSE_HLP_SETT, "FSE_HLP_SETT"); // 
 _LIT(KFSE_HLP_ACCT_INFO, "FSE_HLP_ACCT_INFO"); // 
 _LIT(KFSE_HLP_SYNC_SETT, "FSE_HLP_SYNC_SETT"); // 
+_LIT(KFS_VIEWER_HLP_MR_RECEIVED, "FS_VIEWER_HLP_MR_RECEIVED"); // 
 
 #endif 
\ No newline at end of file
--- a/ipsservices/ipssosplugin/inc/ipsplgsosbaseplugin.h	Wed Apr 14 15:42:15 2010 +0300
+++ b/ipsservices/ipssosplugin/inc/ipsplgsosbaseplugin.h	Tue Apr 27 16:20:14 2010 +0300
@@ -562,6 +562,21 @@
         CMsvEntry*& aMessageEntry,
         CImEmailMessage*& aImEmailMessage );
 
+    /**
+	 * Takes ownership of the cached objects or creates new ones
+	 */     	 
+	void TakeMessageEntryLC(
+		TMsvId aId,
+        CMsvEntry*& aMessageEntry,
+        CImEmailMessage*& aImEmailMessage );
+    
+    /**
+     * Return objects to cache, deleting old ones in the cache if necessary
+     */         
+    void ReturnMessageEntry(
+        CMsvEntry* aMessageEntry,
+        CImEmailMessage* aImEmailMessage );
+        
     /*
      * Cleans up the cached messages entries that have accessed with
      * GetMessageEntryL()
--- a/ipsservices/ipssosplugin/src/ipsplgmsgmapper.cpp	Wed Apr 14 15:42:15 2010 +0300
+++ b/ipsservices/ipssosplugin/src/ipsplgmsgmapper.cpp	Tue Apr 27 16:20:14 2010 +0300
@@ -191,10 +191,10 @@
             {
             CMsvStore* store( NULL );
             CMsvEntry* cEntry = iSession.GetEntryL( aEntry.Id() );
-            CleanupStack::PushL( cEntry );
 
             if ( cEntry )
             	{
+                CleanupStack::PushL( cEntry );
             	if ( cEntry->HasStoreL() )
 					{
 					store = cEntry->ReadStoreL();
--- a/ipsservices/ipssosplugin/src/ipsplgsosbaseplugin.cpp	Wed Apr 14 15:42:15 2010 +0300
+++ b/ipsservices/ipssosplugin/src/ipsplgsosbaseplugin.cpp	Tue Apr 27 16:20:14 2010 +0300
@@ -999,28 +999,34 @@
     file.Size( fileSize );
     file.Close();
 
-    // Initialize CMsvAttachment instance for the attachment creation
-    CMsvAttachment* info = CMsvAttachment::NewL( CMsvAttachment::EMsvFile );
-    CleanupStack::PushL( info );
-
-    info->SetAttachmentNameL( aFilePath );
-    info->SetSize( fileSize );
-
-    // Create/acquire Symbian message entry objects
-    GetMessageEntryL( aMessageId.Id(), cEntry, message );
-
+  // Take ownership of message entry objects since thanks to
+    // "clever" use of active scheduler waits we can re-enter 
+    // this function leading to crashes if somebody clears the cache
+    // while this iteration still needs them
+    TakeMessageEntryLC( aMessageId.Id(), cEntry, message );
+	
     // Operation waiter needed to implement synchronous operation
     // on the top of async API
     CIpsPlgOperationWait* waiter = CIpsPlgOperationWait::NewL();
     CleanupStack::PushL( waiter );
 
+    // Initialize CMsvAttachment instance for the attachment creation
+    CMsvAttachment* info = CMsvAttachment::NewL( CMsvAttachment::EMsvFile );
+    CleanupStack::PushL( info );
+    info->SetAttachmentNameL( aFilePath );
+    info->SetSize( fileSize );
+
     // Start attachment creation
     message->AttachmentManager().AddAttachmentL(
         aFilePath, info, waiter->iStatus );
+    CleanupStack::Pop( info ); // attachment manager takes ownership
 
     waiter->Start();
     CleanupStack::PopAndDestroy( waiter );
-    CleanupStack::Pop( info ); // attachment manager takes ownership
+    	
+    // Return message entry objects back to cache
+    CleanupStack::Pop( 2 ); // cEntry, message
+    ReturnMessageEntry( cEntry, message );
 
     // Dig out the entry ID of the new attachment (unbelievable that
     // there seems to be no better way to do this)
@@ -1126,9 +1132,16 @@
     TInt fileSize( 0 );
     TBuf<KMaxFileName> fileName;
 
-    // Create/acquire Symbian message entry objects
-    CleanCachedMessageEntries();
-    GetMessageEntryL( aMessageId.Id(), cEntry, message );
+ // Take ownership of message entry objects since thanks to
+    // "clever" use of active scheduler waits we can re-enter 
+    // this function leading to crashes if somebody clears the cache
+    // while this iteration still needs them
+    TakeMessageEntryLC( aMessageId.Id(), cEntry, message );
+
+    // Operation waiter needed to implement synchronous operation
+    // on the top of async API
+    CIpsPlgOperationWait* waiter = CIpsPlgOperationWait::NewL();
+    CleanupStack::PushL( waiter );
 
     // Initialize CMsvAttachment instance for the attachment creation
     CMsvAttachment* info = CMsvAttachment::NewL( CMsvAttachment::EMsvFile );
@@ -1142,14 +1155,15 @@
     User::LeaveIfError( aFile.FullName( fileName ) );
     info->SetAttachmentNameL( fileName );
 
-    // Operation waiter needed to implement synchronous operation
-    // on the top of async API
-    CIpsPlgOperationWait* waiter = CIpsPlgOperationWait::NewL();
-    CleanupStack::PushL( waiter );
     message->AttachmentManager().AddAttachmentL( aFile, info, waiter->iStatus );
+    CleanupStack::Pop( info ); // attachment manager takes ownership
+    
     waiter->Start();
     CleanupStack::PopAndDestroy( waiter );
-    CleanupStack::Pop( info ); // attachment manager takes ownership
+
+ 	// Return message entry objects back to cache
+ 	CleanupStack::Pop( 2 ); // cEntry, message
+ 	ReturnMessageEntry( cEntry, message );
 
     // Dig out the entry ID of the new attachment
     message->GetAttachmentsListL( cEntry->Entry().Id( ),
@@ -1269,8 +1283,14 @@
          ( tEntry.iType == KUidMsvAttachmentEntry ) )
         {
         CImEmailMessage* message( NULL );
+  
         // We trust that the message ID really refers to a message
-        GetMessageEntryL( aMessageId.Id(), cEntry, message );
+        
+        // Take ownership of message entry objects since thanks to
+        // "clever" use of active scheduler waits we can re-enter 
+        // this function leading to crashes if somebody clears the cache
+        // while this iteration still needs them
+        TakeMessageEntryLC( aMessageId.Id(), cEntry, message );
 
         MMsvAttachmentManager& attachmentMgr( message->AttachmentManager() );
 
@@ -1282,6 +1302,10 @@
 
         waiter->Start();
         CleanupStack::PopAndDestroy( waiter );
+        	
+        // Return message entry objects to cache
+        CleanupStack::Pop( 2 ); // cEntry, message
+        ReturnMessageEntry( cEntry, message );
         }
     else if ( ( status == KErrNone ) &&
               ( tEntry.iType == KUidMsvFolderEntry ) )
@@ -1462,8 +1486,12 @@
     CMsvEntry* cEntry( NULL );
     CImEmailMessage* message( NULL );
 
-    // We trust that the message ID really refers to a message
-    GetMessageEntryL( aMessageId.Id(), cEntry, message );
+    // Take ownership of message entry objects since thanks to
+    // "clever" use of active scheduler waits we can re-enter 
+    // this function leading to crashes if somebody clears the cache
+    // while this iteration still needs them
+    TakeMessageEntryLC( aMessageId.Id(), cEntry, message );
+    
 	if ( message )
 	    {
 
@@ -1496,6 +1524,10 @@
 	    		}
 	    	}
 	    }
+	
+	// Return message entry objects to cache
+	CleanupStack::Pop( 2 ); // cEntry, message
+	ReturnMessageEntry( cEntry, message );
 	}
 
 // ----------------------------------------------------------------------------
@@ -1723,7 +1755,7 @@
 
     TMsvEntry parentEntry;
 
-    for(TInt i=0; i<count; i++)
+   for(TInt i=0; i<count; i++)
         {
         iSession->GetEntry( aMessages[i].Id(), service, tEntry );
 
@@ -1915,6 +1947,60 @@
     aImEmailMessage = iCachedEmailMessage;
     }
 
+    
+// ----------------------------------------------------------------------------
+// CIpsPlgSosBasePlugin::TakeMessageEntryL( )
+// Takes ownership of the cached objects or creates new ones
+// ----------------------------------------------------------------------------
+
+void CIpsPlgSosBasePlugin::TakeMessageEntryLC(
+    TMsvId aId,
+    CMsvEntry*& aMessageEntry,
+    CImEmailMessage*& aImEmailMessage )
+    {
+    FUNC_LOG;
+    if ( !iCachedEntry || ( aId != iCachedEntry->Entry().Id() ) ||
+            iCachedEmailMessage->IsActive() )
+        {
+        // Can't use the ones that are in cache, create new ones and don't replace the ones in cache
+        aMessageEntry = iSession->GetEntryL( aId );
+        aImEmailMessage = 0;
+        
+        if ( aMessageEntry->Entry().iType == KUidMsvMessageEntry )
+            {
+            CleanupStack::PushL( aMessageEntry );
+            aImEmailMessage = CImEmailMessage::NewL( *aMessageEntry );
+            CleanupStack::Pop();
+            }
+        }
+    else
+    	{
+    	// Take ownership of the cached objects
+    	aMessageEntry = iCachedEntry;
+    	aImEmailMessage = iCachedEmailMessage;
+    	iCachedEntry = 0;
+    	iCachedEmailMessage = 0;
+    	}
+    	
+    // Ownership is transferred to the caller
+    CleanupStack::PushL( aMessageEntry );
+    CleanupStack::PushL( aImEmailMessage );
+    }
+
+// ----------------------------------------------------------------------------
+// ----------------------------------------------------------------------------
+void CIpsPlgSosBasePlugin::ReturnMessageEntry(
+        CMsvEntry* aMessageEntry,
+        CImEmailMessage* aImEmailMessage )
+	{
+	// Clean old ones from the cache
+	CleanCachedMessageEntries();
+	
+	// Always save the latest ones in the cache
+	iCachedEntry = aMessageEntry;
+	iCachedEmailMessage = aImEmailMessage;
+    }
+   
 // ----------------------------------------------------------------------------
 // ----------------------------------------------------------------------------
 //
--- a/meetingrequest/mrdb/inc/cesmrcaldbmgr.h	Wed Apr 14 15:42:15 2010 +0300
+++ b/meetingrequest/mrdb/inc/cesmrcaldbmgr.h	Tue Apr 27 16:20:14 2010 +0300
@@ -69,7 +69,7 @@
      * @return instance view pointer, ownership not transferred
      */
     virtual CCalInstanceView* NormalDbInstanceView() = 0;
-    
+
     /**
      * Accessor for Agenda Model CCalInstanceView owned by this utility.
      * Returns a valid array of pointer if status is EAvailable or
@@ -235,32 +235,38 @@
      * @param aCalendarName Reference to calendar name
      * @return calendar's color rgb value
      */
-    virtual TRgb GetCalendarColorByNameL( TDesC& aCalendarName ) = 0;
+    virtual TRgb GetCalendarColorByNameL( const TDesC& aCalendarName ) = 0;
 
-    /*
+    /**
      * Set current calendar by pass calendar index to it
      * @param aIndex current calendar index
      */
     virtual void SetCurCalendarByIndex( TInt aIndex ) = 0;
 
-    /*
+    /**
      * Set current calendar by pass calendar name to it
      * @param aCalendarName current calendar name
      */
-    virtual void SetCurCalendarByNameL( TDesC& aCalendarName ) = 0;
+    virtual void SetCurCalendarByNameL( const TDesC& aCalendarName ) = 0;
 
-    /*
+    /**
      * Set current calendar by pass entry
      * @param aColId current calendar collectionID
      */
     virtual void SetCurCalendarByColIdL( TInt aColId ) = 0;
-    
-    /*
+
+    /**
      * Set current calendar by pass entry
      * @param aEntry entry which belongs current calendar
      */
     virtual void SetCurCalendarByEntryL( MESMRCalEntry& aEntry ) = 0;
 
+    /**
+     * Sets current calendar by calendar database file id.
+     * @param aDbId calendar database file id to use
+     */
+    virtual void SetCurCalendarByDbIdL( TCalFileId aDbId ) = 0;
+
     /*
      * Get color of current calendar
      * @return current calendar's color(rgb value)
@@ -272,7 +278,7 @@
      * @return current calendar's colId
      */
     virtual TInt GetCurCalendarColIdL() = 0;
-    
+
     /*
      * Get index of current calendar
      * @return current calendar's index
@@ -292,7 +298,7 @@
      * @return a CCalInstanceView that aCalEntry belongs
      */
     virtual CCalInstanceView* InstanceViewL(const CCalEntry& aCalEntry ) = 0;
-    
+
     /*
      * Get current entryview
      * @return current entryView
@@ -387,15 +393,16 @@
     TPtrC GetCalendarNameByEntryL(
             MESMRCalEntry& aEntry);
     TRgb GetCalendarColorByNameL(
-            TDesC& aCalendarName);
+            const TDesC& aCalendarName);
     void SetCurCalendarByNameL(
-            TDesC& aCalendarName );
+            const TDesC& aCalendarName );
     void SetCurCalendarByIndex(
             TInt aIndex );
     void SetCurCalendarByColIdL(
             TInt aColId );
     void SetCurCalendarByEntryL(
             MESMRCalEntry& aEntry );
+    void SetCurCalendarByDbIdL( TCalFileId aDbId );
     TRgb GetCurCalendarColor();
     TInt GetCurCalendarColIdL();
     TInt GetCurCalendarIndex();
--- a/meetingrequest/mrdb/src/cesmrcaldbmgr.cpp	Wed Apr 14 15:42:15 2010 +0300
+++ b/meetingrequest/mrdb/src/cesmrcaldbmgr.cpp	Tue Apr 27 16:20:14 2010 +0300
@@ -778,7 +778,7 @@
 // CESMRCalDbMgr::GetCalendarColorByNameL
 // ----------------------------------------------------------------------------
 //
-TRgb CESMRCalDbMgr::GetCalendarColorByNameL(TDesC& aCalendarName)
+TRgb CESMRCalDbMgr::GetCalendarColorByNameL( const TDesC& aCalendarName )
     {
     FUNC_LOG;
     TInt count = iCalendarInfoArray.Count();
@@ -799,7 +799,7 @@
 // CESMRCalDbMgr::SetCurCalendarByNameL
 // ----------------------------------------------------------------------------
 //
-void CESMRCalDbMgr::SetCurCalendarByNameL( TDesC& aCalendarName )
+void CESMRCalDbMgr::SetCurCalendarByNameL(  const TDesC& aCalendarName )
     {
     FUNC_LOG;
     TInt count = iCalendarInfoArray.Count();
@@ -854,6 +854,27 @@
     }
 
 // ----------------------------------------------------------------------------
+// CESMRCalDbMgr::SetCurCalendarByDbIdL
+// ----------------------------------------------------------------------------
+//
+void CESMRCalDbMgr::SetCurCalendarByDbIdL( TCalFileId aDbId )
+    {
+    FUNC_LOG;
+
+    for ( TInt i = 0; i < iCalSessionArray.Count(); ++i )
+        {
+        TCalFileId fileId( KNullFileId );
+        iCalSessionArray[ i ]->FileIdL( fileId );
+
+        if ( fileId == aDbId )
+            {
+            iCurCalenIndex = i;
+            break;
+            }
+        }
+    }
+
+// ----------------------------------------------------------------------------
 // CESMRCalDbMgr::GetCurCalendarColor
 // ----------------------------------------------------------------------------
 //
--- a/meetingrequest/mrentry/inc/cesmrfsmailboxutils.h	Wed Apr 14 15:42:15 2010 +0300
+++ b/meetingrequest/mrentry/inc/cesmrfsmailboxutils.h	Tue Apr 27 16:20:14 2010 +0300
@@ -20,6 +20,8 @@
 
 #include <e32base.h>
 #include <cmrmailboxutils.h>
+#include <calcommon.h>
+
 #include "esmrdef.h"
 #include "cfsmailcommon.h"
 
@@ -35,15 +37,15 @@
 NONSHARABLE_CLASS( CESMRFsMailboxUtils ): public CBase
     {
 public:
-    
+
     /**
      * Enumeration for mailbox capabilities
      */
     enum TMRMailboxCapability
         {
         EMRCapabilityAttachment
-        };    
-    
+        };
+
 public: // Constructors and destructors
 
     /**
@@ -112,7 +114,18 @@
      */
     IMPORT_C TBool DefaultMailboxSupportCapabilityL(
             TMRMailboxCapability aCapability );
-    
+
+    /**
+     * Gets the calendar database id used by mail plugin
+     *
+     * @param aPlugin mail plugin in use
+     * @param aDbId on return contains the database id or KNullFileId
+     *              if plugin does not provide database id information.
+     */
+    void GetCalendarDatabaseIdL(
+            TESMRMailPlugin aPlugin,
+            TCalFileId& aDbId );
+
 private: // Implementation
     CESMRFsMailboxUtils(
             CMRMailboxUtils& aMailboxUtils );
@@ -128,7 +141,7 @@
 
     CFSMailClient& MailClientL();
     CFSMailBox* DefaultMailboxL();
-    
+
 private: // Data
     /// Ref: Reference to S60 mailbox utilities
     CMRMailboxUtils& iMRMailboxUtils;
--- a/meetingrequest/mrentry/inc/cesmrmeetingrequestentry.h	Wed Apr 14 15:42:15 2010 +0300
+++ b/meetingrequest/mrentry/inc/cesmrmeetingrequestentry.h	Tue Apr 27 16:20:14 2010 +0300
@@ -76,7 +76,7 @@
             TESMRRecurrenceValue& aRecurrence,
             TTime& aUntil) const;
     TESMRRecurrenceModifyingRule RecurrenceModRule() const;
-    void SetModifyingRuleL(TESMRRecurrenceModifyingRule aRule, 
+    void SetModifyingRuleL(TESMRRecurrenceModifyingRule aRule,
     		const TBool aTypeChanging = EFalse );
     void SetAllDayEventL(
             TTime aStartDate,
@@ -144,13 +144,13 @@
     void UpdateComparativeEntry(
             CCalEntry* aNewComparativeEntry );
     MESMRCalDbMgr& GetDBMgr();
-    TBool SupportsCapabilityL( 
+    TBool SupportsCapabilityL(
             MESMRCalEntry::TMREntryCapability aCapability ) const;
-    TBool ContainsRemoteAttachmentsL();    
+    TBool ContainsRemoteAttachmentsL();
     TBool SendCanellationAvailable();
     void SetSendCanellationAvailable (TBool aSendCanellation);
     void SetTypeChanged( TBool aTypeChanged );
-    
+
 private: // Implementaton
     CESMRMeetingRequestEntry(
             CMRMailboxUtils& aMRMailboxUtils,
@@ -163,6 +163,7 @@
             const TDesC& aTarget,
             const TDesC& aFindString,
             const TDesC& aReplacement );
+    void SetDefaultDatabaseL();
 
 private: // Data
     /// Own: Calendar entry
--- a/meetingrequest/mrentry/src/cesmrfsmailboxutils.cpp	Wed Apr 14 15:42:15 2010 +0300
+++ b/meetingrequest/mrentry/src/cesmrfsmailboxutils.cpp	Tue Apr 27 16:20:14 2010 +0300
@@ -16,19 +16,21 @@
 */
 
 
-#include "emailtrace.h"
 #include "cesmrfsmailboxutils.h"
+
 #include "esmrhelper.h"
 #include "esmrinternaluid.h"
 
+#include "cfsmailclient.h"
+#include "cfsmailbox.h"
+#include "cmrcalendarinfo.h"
+
 #include <calentry.h>
-//<cmail>
-#include "CFSMailClient.h"
-#include "CFSMailBox.h"
-//</cmail>
 #include <caluser.h>
 #include <ct/rcpointerarray.h>
 
+#include "emailtrace.h"
+
 // Unnamed namespace for local definitions
 namespace {
 
@@ -49,6 +51,35 @@
             msgId,
             aMailboxes );
     }
+
+/**
+ * Helper class for Email extension cleanup
+ */
+class TExtensionCleanup
+    {
+    public:
+
+    TExtensionCleanup(
+            CFSMailBox* aMailbox,
+            CEmailExtension* aExtension )
+        : iMailbox( aMailbox ),
+          iExtension( aExtension )
+        {
+        }
+
+    void Close()
+        {
+        iMailbox->ReleaseExtension( iExtension );
+        }
+
+    private:
+        /// Not own: mailbox
+        CFSMailBox* iMailbox;
+        // Not own: mailbox extension
+        CEmailExtension* iExtension;
+    };
+
+
 }
 
 // ======== MEMBER FUNCTIONS ========
@@ -134,7 +165,7 @@
             aCalEntry.SetPhoneOwnerL( phoneOwner );
             err = KErrNone;
             }
-        
+
         CleanupStack::PopAndDestroy( &mailboxes );
         }
     return err;
@@ -264,32 +295,101 @@
 // ----------------------------------------------------------------------------
 //
 EXPORT_C TBool CESMRFsMailboxUtils::DefaultMailboxSupportCapabilityL(
-        CESMRFsMailboxUtils::TMRMailboxCapability aCapability ) 
+        CESMRFsMailboxUtils::TMRMailboxCapability aCapability )
     {
     FUNC_LOG;
-    
-    TBool retValue( EFalse );    
-   
+
+    TBool retValue( EFalse );
+
     CFSMailBox* defaultMailbox = DefaultMailboxL();
     CleanupStack::PushL( defaultMailbox );
     ASSERT( defaultMailbox );
-    
+
     switch ( aCapability )
         {
         case CESMRFsMailboxUtils::EMRCapabilityAttachment:
             {
-            retValue = defaultMailbox->HasCapability( 
+            retValue = defaultMailbox->HasCapability(
                             EFSMboxCapaSupportsAttahmentsInMR );
             }
             break;
         }
-    
+
     CleanupStack::PopAndDestroy( defaultMailbox );
-    
+
     return retValue;
     }
 
 // ----------------------------------------------------------------------------
+// CESMRFsMailboxUtils::GetCalendarDatabaseIdL
+// ----------------------------------------------------------------------------
+//
+void CESMRFsMailboxUtils::GetCalendarDatabaseIdL(
+            TESMRMailPlugin aPlugin,
+            TCalFileId& aDbId )
+    {
+    FUNC_LOG;
+
+    TUid pluginUid( TUid::Null() );
+    aDbId = KNullFileId;
+
+    switch ( aPlugin )
+        {
+        case EESMRActiveSync:
+            {
+            pluginUid = TUid::Uid( KEasFreestylePlugin );
+            break;
+            }
+        case EESMRIntelliSync:
+            {
+            pluginUid = TUid::Uid( KIntellisync );
+            break;
+            }
+        default:
+            {
+            break;
+            }
+        }
+
+    if ( pluginUid != TUid::Null() )
+        {
+        RCPointerArray<CFSMailBox> mailboxes;
+        CleanupClosePushL( mailboxes );
+
+        ListMailBoxesL(
+                MailClientL(),
+                mailboxes );
+
+        for ( TInt i = 0; i < mailboxes.Count(); ++i )
+            {
+            CFSMailBox* mailbox = mailboxes[ i ];
+            if ( mailbox->GetId().PluginId() == pluginUid )
+                {
+                // Resolve database id using mailbox extension
+                CEmailExtension* extension =
+                        mailbox->ExtensionL( KMailboxExtMrCalInfo );
+
+                TExtensionCleanup cleanup( mailbox, extension );
+                CleanupClosePushL( cleanup );
+
+                CMRCalendarInfo* calInfo =
+                        static_cast< CMRCalendarInfo* >( extension );
+
+                if ( calInfo )
+                    {
+                    calInfo->GetCalendarDatabaseIdL( aDbId );
+                    }
+
+                CleanupStack::PopAndDestroy( &cleanup ); // Release extension
+                break;
+                }
+            }
+
+        CleanupStack::PopAndDestroy( &mailboxes );
+        }
+    }
+
+// ----------------------------------------------------------------------------
 // CESMRFsMailboxUtils::PhoneOwnerL
 // ----------------------------------------------------------------------------
 //
@@ -376,26 +476,26 @@
 CFSMailBox* CESMRFsMailboxUtils::DefaultMailboxL()
     {
     FUNC_LOG;
-    
+
     CFSMailBox* defaultMailbox( NULL );
-    
+
     CMRMailboxUtils::TMailboxInfo mailboxInfo;
     TInt err = iMRMailboxUtils.GetDefaultMRMailBoxL( mailboxInfo );
-    
+
     if ( KErrNone == err )
         {
         RCPointerArray<CFSMailBox> mailboxes;
         CleanupClosePushL( mailboxes );
-        
+
         ListMailBoxesL( MailClientL(), mailboxes );
-        
+
         TInt mailboxCount( mailboxes.Count() );
         for (TInt j(0); j < mailboxCount && !defaultMailbox; ++j )
             {
             TPtrC mailboxOwnerAddName(
                     mailboxes[j]->OwnMailAddress().GetEmailAddress() );
-    
-            if ( KEqualEmailAddress == 
+
+            if ( KEqualEmailAddress ==
                  mailboxOwnerAddName.CompareF( mailboxInfo.iEmailAddress) )
                 {
                 // Default mailbox is found
@@ -403,10 +503,10 @@
                 mailboxes.Remove( j );
                 }
             }
-        
+
         CleanupStack::PopAndDestroy( &mailboxes );
         }
-    
+
     return defaultMailbox;
     }
 
--- a/meetingrequest/mrentry/src/cesmrmeetingrequestentry.cpp	Wed Apr 14 15:42:15 2010 +0300
+++ b/meetingrequest/mrentry/src/cesmrmeetingrequestentry.cpp	Tue Apr 27 16:20:14 2010 +0300
@@ -29,7 +29,7 @@
 #include "mmrinfoobject.h"
 #include "mmrattendee.h"
 
-#include "CFSMailMessage.h"
+#include "cfsmailmessage.h"
 
 #include "esmrconfig.hrh"
 #include "cesmrfeaturesettings.h"
@@ -42,12 +42,12 @@
 #include <calinstanceview.h>
 #include <caluser.h>
 #include <calattachment.h>
-#include <caleninterimutils2.h>
+#include <CalenInterimUtils2.h>
 #include <cmrmailboxutils.h>
 #include <calrrule.h>
 #include <centralrepository.h>
 #include <calalarm.h>
-#include <calendarinternalcrkeys.h>
+#include <CalendarInternalCRKeys.h>
 #include <data_caging_path_literals.hrh>
 #include <coemain.h>
 #include <calentryview.h>
@@ -241,16 +241,22 @@
     CleanupStack::PopAndDestroy( newDescription );
 
     __ASSERT_DEBUG( iEntry->PhoneOwnerL(), Panic( EESMRPhoneOwnerNotSet) );
-    
+
     CESMRFeatureSettings* settings = CESMRFeatureSettings::NewL();
     if ( settings->FeatureSupported(
             CESMRFeatureSettings::EMRUIMeetingRequestViewerCmailOnly ) )
         {
         // Meeting request viewer available only from email.
-        // Remove attachments from entry.  
+        // Remove attachments from entry.
         iRemoveAttachments = ETrue;
         }
     delete settings;
+
+    if ( CurrentPluginL() == EESMRActiveSync )
+        {
+        // Set correct calendar database
+        SetDefaultDatabaseL();
+        }
     }
 
 // ---------------------------------------------------------------------------
@@ -383,7 +389,7 @@
     __ASSERT_DEBUG( iEntry, Panic(EESMREntryNotExist ) );
 
     TBool canSetRecurrence( ETrue );
-    
+
     if ( iEntry->EntryTypeL() == CCalEntry::EAppt &&
             ESMREntryHelper::IsRepeatingMeetingL(*iEntry) &&
         (!ESMREntryHelper::IsModifyingEntryL(*iEntry) &&
@@ -640,15 +646,15 @@
                 }
             }
         }
-    else if ( ERecurrenceNot != orginalRecurrence && 
+    else if ( ERecurrenceNot != orginalRecurrence &&
     		aTypeChanging && !modifyingEntry )
     	{
-		// if entry( in the memory) is a recurrent event 
+		// if entry( in the memory) is a recurrent event
 		// ,and if entry type is changing, and not in modifying status then EESMRAllInSeries
 		iRecurrenceModRule = EESMRAllInSeries ;
 		return;
     	}
-    
+
     iRecurrenceModRule = aRule;
 
     }
@@ -872,7 +878,7 @@
 TBool CESMRMeetingRequestEntry::IsEntryTypeChangedL() const
     {
     FUNC_LOG;
-    
+
     return iTypeChanged;
     }
 
@@ -1461,7 +1467,15 @@
     currentTimeUtc.UniversalTime();
 
     TTime startTimeUtc = iEntry->StartTimeL().TimeUtcL();
-
+    
+    if( IsRecurrentEventL() &&
+    		IsOpenedFromMail() &&
+    		EESMRAllInSeries == iRecurrenceModRule )
+    	{
+		// Get recurrence
+		TESMRRecurrenceValue recValue( ERecurrenceNot ); 
+		GetRecurrenceL( recValue, startTimeUtc );
+    	}
 
     return (startTimeUtc < currentTimeUtc);
     }
@@ -1665,7 +1679,7 @@
         {
         // Remove attachments from the entry
         TInt count( entry->AttachmentCountL() );
-        
+
         for ( TInt i = 0; i < count; ++i )
             {
             CCalAttachment* attachment = entry->AttachmentL( i );
@@ -1817,7 +1831,7 @@
         aStartupParams.iCalEntry       = iESMRInputParams->iCalEntry;
         aStartupParams.iMRInfoObject   = iESMRInputParams->iMRInfoObject;
         aStartupParams.iMailMessage    = iESMRInputParams->iMailMessage;
-        aStartupParams.iMailClient     = iESMRInputParams->iMailClient;        
+        aStartupParams.iMailClient     = iESMRInputParams->iMailClient;
         aStartupParams.iSpare          = iESMRInputParams->iSpare;
         }
     return retValue;
@@ -2158,14 +2172,14 @@
 
     CCalInstance* instance = InstanceL();
     CleanupStack::PushL( instance );
-    
+
     TCalCollectionId colId = instance->InstanceIdL().iCollectionId;
     CleanupStack::PopAndDestroy( instance );
-    
+
     conflictCheckker->FindInstancesForEntryL( aStart,
                                               aEnd,
                                               *iEntry,
-                                              colId, 
+                                              colId,
                                               entries );
 
     if ( entries.Count() )
@@ -2245,11 +2259,11 @@
 // CESMRMeetingRequestEntry::SupportsCapabilityL
 // ---------------------------------------------------------------------------
 //
-TBool CESMRMeetingRequestEntry::SupportsCapabilityL( 
+TBool CESMRMeetingRequestEntry::SupportsCapabilityL(
         MESMRCalEntry::TMREntryCapability aCapability ) const
     {
     TBool retValue( EFalse );
-    
+
     switch( aCapability )
         {
         case MESMRCalEntry::EMRCapabilityAttachments:
@@ -2260,11 +2274,11 @@
 
             retValue = fsMbUtils->DefaultMailboxSupportCapabilityL(
                     CESMRFsMailboxUtils::EMRCapabilityAttachment );
-            CleanupStack::PopAndDestroy( fsMbUtils );        
+            CleanupStack::PopAndDestroy( fsMbUtils );
             }
             break;
         }
-    
+
     return retValue;
     }
 
@@ -2275,22 +2289,22 @@
 TBool CESMRMeetingRequestEntry::ContainsRemoteAttachmentsL()
     {
     FUNC_LOG;
-    
+
     TBool retValue( EFalse );
-    
+
     TInt attachmentCount( iEntry->AttachmentCountL() );
-    
+
     for ( TInt i(0); i < attachmentCount && !retValue; ++i )
         {
-        CCalAttachment* attachment = iEntry->AttachmentL(i);        
+        CCalAttachment* attachment = iEntry->AttachmentL(i);
         CCalAttachment::TType type( attachment->Type() );
-        
+
         if ( CCalAttachment::EFile != type )
             {
             retValue = ETrue;
-            }        
+            }
         }
-    
+
     return retValue;
     }
 
@@ -2320,8 +2334,39 @@
 void CESMRMeetingRequestEntry::SetTypeChanged( TBool aTypeChanged )
     {
     FUNC_LOG;
-    
+
     iTypeChanged = aTypeChanged;
     }
 
+// ---------------------------------------------------------------------------
+// CESMRMeetingRequestEntry::SetDefaultDatabaseL
+// ---------------------------------------------------------------------------
+//
+void CESMRMeetingRequestEntry::SetDefaultDatabaseL()
+    {
+    FUNC_LOG;
+
+    if ( !IsStoredL() )
+        {
+        // If entry has not been stored, set database manager to use correct
+        // database supported by plugin sync solution.
+        CESMRFsMailboxUtils* fsMbUtils =
+                CESMRFsMailboxUtils::NewL( iMRMailboxUtils );
+        CleanupStack::PushL( fsMbUtils );
+        TCalFileId aDbId( KNullFileId );
+        fsMbUtils->GetCalendarDatabaseIdL( CurrentPluginL(), aDbId );
+        CleanupStack::PopAndDestroy( fsMbUtils );
+
+        if ( aDbId != KNullFileId )
+            {
+            iCalDb.SetCurCalendarByDbIdL( aDbId );
+            }
+        else if ( CurrentPluginL() == EESMRActiveSync )
+            {
+            _LIT( KMfeDb, "Mail for Exchange" );
+            iCalDb.SetCurCalendarByNameL( KMfeDb );
+            }
+        }
+    }
+
 // EOF
--- a/meetingrequest/mrgui/mrfieldbuildercommon/src/cesmrrichtextviewer.cpp	Wed Apr 14 15:42:15 2010 +0300
+++ b/meetingrequest/mrgui/mrfieldbuildercommon/src/cesmrrichtextviewer.cpp	Tue Apr 27 16:20:14 2010 +0300
@@ -12,7 +12,7 @@
 * Contributors:
 *
 *  Description : CEikRichTextEditor based Rich Text viewer
-*  Version     : %version: e002sa32#37 %
+*  Version     : %version: e002sa33#40 %
 *
 */
 
@@ -34,9 +34,9 @@
 #include <commonphoneparser.h>
 #include <finditemengine.h>
 #include <txtrich.h>
-#include <aknsutils.h>
-#include <aknbiditextutils.h>
-#include <aknutils.h>
+#include <AknsUtils.h>
+#include <AknBidiTextUtils.h>
+#include <AknUtils.h>
 #include <eikenv.h>
 #include <data_caging_path_literals.hrh>
 #include <baclipb.h> // for clipboard copy
@@ -130,7 +130,7 @@
     // Gaining focus
     if ( IsFocused()
          && iLinkList.Count() > 0
-         && selection.Length() == 0 )
+         && ( selection.Length() == 0 ) )
         {
         // We need the field indexes, cast required
         CESMRField* parent = static_cast< CESMRField* >( Parent() );
@@ -373,7 +373,8 @@
                 if ( link
                      && ( menuAvailable
                      || link->Type() == CESMRRichTextLink::ETypeLocationUrl
-                     || link->Type() == CESMRRichTextLink::ETypeAttachment ) )
+                     || link->Type() == CESMRRichTextLink::ETypeAttachment
+                     || link->Type() == CESMRRichTextLink::ETypeShowAll ) )
                     {
                     linkFound = ETrue;
 
--- a/meetingrequest/mrgui/mrfieldbuilderplugin/src/cesmrvieweralldayeventfield.cpp	Wed Apr 14 15:42:15 2010 +0300
+++ b/meetingrequest/mrgui/mrfieldbuilderplugin/src/cesmrvieweralldayeventfield.cpp	Tue Apr 27 16:20:14 2010 +0300
@@ -27,8 +27,8 @@
 #include <caluser.h>
 #include <calalarm.h>
 #include <calentry.h>
-#include <stringloader.h>
-#include <aknlayout2scalabledef.h>
+#include <StringLoader.h>
+#include <AknLayout2ScalableDef.h>
 #include <esmrgui.rsg>
 
 #include "emailtrace.h"
@@ -155,7 +155,10 @@
     	}
 
     TRect viewerRect( viewerLayoutText.TextRect() );    
-    iLabel->SetRect( viewerRect );
+    iLabel->SetRect( viewerRect );    
+    // Setting font for the label also
+    iLabel->SetFont( viewerLayoutText.Font() );
+
 
     // Move focus rect so that it's relative to field's position.
     viewerRect.Move( -Position() );
--- a/meetingrequest/mrgui/mrfieldbuilderplugin/src/cesmrviewerdescriptionfield.cpp	Wed Apr 14 15:42:15 2010 +0300
+++ b/meetingrequest/mrgui/mrfieldbuilderplugin/src/cesmrviewerdescriptionfield.cpp	Tue Apr 27 16:20:14 2010 +0300
@@ -31,8 +31,8 @@
 #include "cesmrurlparserplugin.h"
 //</cmail>
 #include <calentry.h>
-#include <aknutils.h>
-#include <stringloader.h>
+#include <AknUtils.h>
+#include <StringLoader.h>
 #include <esmrgui.rsg>
 #include <avkon.rsg>
 #include <txtrich.h>
@@ -185,6 +185,8 @@
 //
 void CESMRViewerDescriptionField::SizeChanged()
     {
+    // Store iRichTextViewer original width.
+    TInt richTextViewerWidth = iRichTextViewer->Size().iWidth;
     TRect rect( Rect() );
     rect = NMRLayoutManager::GetFieldRowLayoutRect( rect, 1 ).Rect();
 
@@ -211,12 +213,19 @@
             iRichTextViewer->ApplyLayoutChangesL();
             );
 
-    iRichTextViewer->SetRect(
-            TRect( viewerRect.iTl,
-                    TSize( viewerRect.Width(), iSize.iHeight ) ) );
-
-    bgRect.SetHeight( iRichTextViewer->Rect().Height() );
-    SetFocusRect( bgRect );
+    if ( iRichTextViewer->Size().iWidth != richTextViewerWidth )
+        {
+        // Most of this case is screen orientation, in this case we need to 
+        // Record the index of focusing link, after updating link array, then 
+        // reset the focusing to original one.
+        TInt focusingIndex = iRichTextViewer->GetFocusLink();
+        if ( KErrNotFound != focusingIndex )
+            {
+            iRichTextViewer->SetFocusLink( focusingIndex );
+            //wake up current contact menu selection by calling this
+            iRichTextViewer->FocusChanged(ENoDrawNow);
+            }
+        } 
     }
 
 // ---------------------------------------------------------------------------
--- a/meetingrequest/mrgui/mrfieldbuilderplugin/src/cesmrviewerdetailedsubjectfield.cpp	Wed Apr 14 15:42:15 2010 +0300
+++ b/meetingrequest/mrgui/mrfieldbuilderplugin/src/cesmrviewerdetailedsubjectfield.cpp	Tue Apr 27 16:20:14 2010 +0300
@@ -27,9 +27,9 @@
 #include "cesmrglobalnote.h"
 
 #include <esmrgui.rsg>
-#include <stringloader.h>
+#include <StringLoader.h>
 #include <calentry.h>
-#include <aknlayout2scalabledef.h>
+#include <AknLayout2ScalableDef.h>
 
 // DEBUG
 #include "emailtrace.h"
@@ -512,6 +512,8 @@
 //
 void CESMRViewerDetailedSubjectField::SizeChanged( )
     {
+    // Store iRichTextViewer original width.
+    TInt richTextViewerWidth = iRichTextViewer->Size().iWidth;
     TRect rect( Rect() );
 
     TAknLayoutRect rowLayoutRect( 
@@ -570,6 +572,20 @@
             // Try applying changes
             iRichTextViewer->ApplyLayoutChangesL();
             );
+
+    if ( iRichTextViewer->Size().iWidth != richTextViewerWidth )
+        {
+        // Most of this case is screen orientation, in this case we need to 
+        // Record the index of focusing link, after updating link array, then 
+        // reset the focusing to original one.
+        TInt focusingIndex = iRichTextViewer->GetFocusLink();
+        if ( KErrNotFound != focusingIndex )
+            {
+            iRichTextViewer->SetFocusLink( focusingIndex );
+            //wake up current contact menu selection by calling this
+            iRichTextViewer->FocusChanged(ENoDrawNow);
+            }
+        }
     }
 
 // ---------------------------------------------------------------------------
--- a/meetingrequest/mrgui/mrfieldbuilderplugin/src/cesmrviewerlocationfield.cpp	Wed Apr 14 15:42:15 2010 +0300
+++ b/meetingrequest/mrgui/mrfieldbuilderplugin/src/cesmrviewerlocationfield.cpp	Tue Apr 27 16:20:14 2010 +0300
@@ -28,9 +28,9 @@
 #include <calentry.h>
 #include <esmrgui.rsg>
 #include <data_caging_path_literals.hrh>
-#include <aknlayout2scalabledef.h>
+#include <AknLayout2ScalableDef.h>
 #include <gulicon.h>
-#include <stringloader.h>
+#include <StringLoader.h>
 
 // LOCAL DEFINITIONS
 
@@ -343,6 +343,8 @@
 //
 void CESMRViewerLocationField::SizeChanged( )
     {
+    // Store iRichTextViewer original width.
+    TInt richTextViewerWidth = iRichTextViewer->Size().iWidth;
     TRect rect( Rect() );
 
     TAknLayoutRect rowLayoutRect(
@@ -401,6 +403,20 @@
     		// Try applying changes
     		iRichTextViewer->ApplyLayoutChangesL();
 				);
+
+    if ( iRichTextViewer->Size().iWidth != richTextViewerWidth )
+        {
+        // Most of this case is screen orientation, in this case we need to 
+        // Record the index of focusing link, after updating link array, then 
+        // reset the focusing to original one.
+        TInt focusingIndex = iRichTextViewer->GetFocusLink();
+        if ( KErrNotFound != focusingIndex )
+            {
+            iRichTextViewer->SetFocusLink( focusingIndex );
+            //wake up current contact menu selection by calling this
+            iRichTextViewer->FocusChanged(ENoDrawNow);
+            }
+        }  
     }
 
 // ---------------------------------------------------------------------------
--- a/meetingrequest/mrgui/mrfieldbuilderpluginextension/src/cesmrviewerattendeesfield.cpp	Wed Apr 14 15:42:15 2010 +0300
+++ b/meetingrequest/mrgui/mrfieldbuilderpluginextension/src/cesmrviewerattendeesfield.cpp	Tue Apr 27 16:20:14 2010 +0300
@@ -25,10 +25,10 @@
 
 #include <caluser.h>
 #include <calentry.h>
-#include <stringloader.h>
+#include <StringLoader.h>
 #include <esmrgui.rsg>
-#include <cpbkcontactengine.h>
-#include <aknbiditextutils.h>
+#include <CPbkContactEngine.h>
+#include <AknBidiTextUtils.h>
 
 // DEBUG
 #include "emailtrace.h"
@@ -296,9 +296,9 @@
         if ( KErrNotFound != focusingIndex )
             {
             iRichTextViewer->SetFocusLink( focusingIndex );
+            //wake up current contact menu selection by calling this
+            iRichTextViewer->FocusChanged(ENoDrawNow);
             }
-        //wake up current contact menu selection by calling this
-        iRichTextViewer->FocusChanged(ENoDrawNow);
         }
     }