Revision: 201007 RCL_3
authorDremov Kirill (Nokia-D-MSW/Tampere) <kirill.dremov@nokia.com>
Fri, 12 Mar 2010 15:43:57 +0200
branchRCL_3
changeset 9 2eb74cf6572e
parent 5 82749d516180
child 10 7403edfcf0fb
Revision: 201007 Kit: 201008
imagehandlinglib/Src/CIHLImageViewerExtJpg.cpp
imagehandlingutilities/thumbnailmanager/inc/thumbnaillog.h
imagehandlingutilities/thumbnailmanager/inc/thumbnailmanagerconstants.h
imagehandlingutilities/thumbnailmanager/plugins/audio/src/thumbnailaudioprovider.cpp
imagehandlingutilities/thumbnailmanager/plugins/audio/src/thumbnailimagedecoderv3.cpp
imagehandlingutilities/thumbnailmanager/plugins/image/src/thumbnailimagedecoder.cpp
imagehandlingutilities/thumbnailmanager/plugins/image/src/thumbnailimagedecoderv2.cpp
imagehandlingutilities/thumbnailmanager/plugins/video/inc/thumbnailvideoprovider.h
imagehandlingutilities/thumbnailmanager/sis/thumbnailmanager/ThumbnailManager_0x102830AB_v9.20.3_SA_S60.50_Euro1.sis
imagehandlingutilities/thumbnailmanager/sis/thumbnailmanager/package.pkg
imagehandlingutilities/thumbnailmanager/sis/thumbnailmanager/stub.pkg
imagehandlingutilities/thumbnailmanager/sis/thumbnailmanager/thumbnailmanager_stub.sis
imagehandlingutilities/thumbnailmanager/sis/thumbnailmanagercenrep/package.pkg
imagehandlingutilities/thumbnailmanager/thumbagdaemon/group/thumbagdaemon.mmp
imagehandlingutilities/thumbnailmanager/thumbagdaemon/inc/thumbagdaemon.h
imagehandlingutilities/thumbnailmanager/thumbagdaemon/inc/thumbagprocessor.h
imagehandlingutilities/thumbnailmanager/thumbagdaemon/src/thumbagdaemon.cpp
imagehandlingutilities/thumbnailmanager/thumbagdaemon/src/thumbagprocessor.cpp
imagehandlingutilities/thumbnailmanager/thumbnailclient/inc/thumbnailsession.h
imagehandlingutilities/thumbnailmanager/thumbnailclient/src/thumbnailrequestactive.cpp
imagehandlingutilities/thumbnailmanager/thumbnailclient/src/thumbnailsession.cpp
imagehandlingutilities/thumbnailmanager/thumbnailserver/group/thumbnailserver.mmp
imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/thumbnailcenrep.h
imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/thumbnailgeneratetask.h
imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/thumbnailmdsquerytask.h
imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/thumbnailscaletask.h
imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/thumbnailserver.h
imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/thumbnailserversession.h
imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/thumbnailsql.h
imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/thumbnailstore.h
imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailcenrep.cpp
imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailgeneratetask.cpp
imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailmdsquerytask.cpp
imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailscaletask.cpp
imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailserver.cpp
imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailserversession.cpp
imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailstore.cpp
imagehandlingutilities/thumbnailmanager/tmcommon/inc/tmactivitymanager.h
imagehandlingutilities/thumbnailmanager/tmcommon/inc/tmrpropertyobserver.h
imagehandlingutilities/thumbnailmanager/tmcommon/src/tmactivitymanager.cpp
imagehandlingutilities/thumbnailmanager/tmcommon/src/tmsrproptertyobserver.cpp
--- a/imagehandlinglib/Src/CIHLImageViewerExtJpg.cpp	Fri Feb 19 23:07:36 2010 +0200
+++ b/imagehandlinglib/Src/CIHLImageViewerExtJpg.cpp	Fri Mar 12 15:43:57 2010 +0200
@@ -24,7 +24,7 @@
 #include "IHLImplementationIds.h"
 #include <IHLInterfaceIds.h>
 #include <IclExtJpegApi.h>
-#include <ImageCodecData.h>
+#include <imagecodecdata.h>
 #include <MIHLViewerObserver.h>
 #include "MIHLFileImageExtJpg.h"
 #include <fbs.h>
--- a/imagehandlingutilities/thumbnailmanager/inc/thumbnaillog.h	Fri Feb 19 23:07:36 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/inc/thumbnaillog.h	Fri Mar 12 15:43:57 2010 +0200
@@ -25,6 +25,8 @@
 //log to file instead of RDebug
 //#define LOG_TO_FILE
 
+//#define _DEBUG
+
 #ifdef _DEBUG
 #ifdef LOG_TO_FILE
 //
@@ -76,6 +78,13 @@
 EFileLoggingModeAppend, \
 _L( s ), a, b, c, d, e );
 
+#define TN_DEBUG7( s, a, b, c, d, e, f ) \
+RFileLogger::WriteFormat( \
+KThumbnailLogDir, \
+KThumbnailLogFile, \
+EFileLoggingModeAppend, \
+_L( s ), a, b, c, d, e, f );
+
 #else // LOG_TO_FILE
 //
 // Log to RDebug
@@ -86,6 +95,7 @@
 #define TN_DEBUG4( s, a, b, c )        RDebug::Print( _L( s ), a, b, c )
 #define TN_DEBUG5( s, a, b, c, d )     RDebug::Print( _L( s ), a, b, c, d )
 #define TN_DEBUG6( s, a, b, c, d, e )  RDebug::Print( _L( s ), a, b, c, d, e )
+#define TN_DEBUG7( s, a, b, c, d, e, f )  RDebug::Print( _L( s ), a, b, c, d, e, f )
 
 #endif // LOG_TO_FILE
 
@@ -99,7 +109,7 @@
 #define TN_DEBUG4( s, a, b, c )
 #define TN_DEBUG5( s, a, b, c, d )
 #define TN_DEBUG6( s, a, b, c, d, e )
-
+#define TN_DEBUG7( s, a, b, c, d, e, f )
 #endif // _DEBUG
 
 #endif // THUMBNAILLOG_H
--- a/imagehandlingutilities/thumbnailmanager/inc/thumbnailmanagerconstants.h	Fri Feb 19 23:07:36 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/inc/thumbnailmanagerconstants.h	Fri Mar 12 15:43:57 2010 +0200
@@ -43,17 +43,24 @@
 const TInt KMdSShutdown = 0x00000002;
 //used to signal from server side when it's idle
 const TInt KIdle = 0x00000004;
+//daemon exposes items in processing queues
+const TInt KItemsleft = 0x00000008;
+const TInt KForceBackgroundGeneration = 0x00000010;
+const TInt KMPXHarvesting = 0x00000020;
+const TInt KDaemonProcessing = 0x00000040;
 
 //insert to temp table first wo indexing and move data to main table as batch
-const TUint KMaxBatchItems = 18;
+const TUint KMaxBatchItems = 36;
+//how many items daemon will query at once from MDS
+const TUint KMaxQueryItems = 100;
 
-const TUint KMaxQueryItems = 1;
-
-// maximum number of active client queue requests
+// maximum number of active client side queue requests
 const TUint KMaxClientRequests = 2;
 
 // maximum number of active daemon requests
-const TUint KMaxDaemonRequests = 3;
+const TUint KMaxDaemonRequests = 2;
+
+const TUint KMdEReconnect = 100000; //100 ms
 
 const TUint KClientRequestTimeout = 60000000; //60 sec
 const TUint KClientRequestStartErrorTimeout = 100000; //100 ms
@@ -69,10 +76,19 @@
 
 const TInt KPSKeyTimeout = 10000000; //10 sec
 //Store's auto flush timeout
-const TInt KAutoFlushTimeout = 30000000; //30 sec
+const TInt KAutoFlushTimeout = 65; //65 sec
 
 // minimum background generation idle time seconds
-const TInt KBackgroundGenerationIdle = 2;
+const TInt KBackgroundGenerationIdle = 60;
+// minimum store maintenance idle time seconds
+const TInt KStoreMaintenanceIdle = 300; // 5 min
+// interval for store maintenance rounds
+const TInt KStoreMaintenancePeriodic = 100000; //100 ms
+
+// maximum number of rows deleted in one transaction
+const TInt KStoreMaintenanceDeleteLimit = 10;
+// maximum number of thumbs checked for source file existance
+const TInt KStoreMaintenanceExistLimit = 50;
 
 // video decoder timeout
 const TInt KVideoDecoderTimeout = 5000000; // 5 seconds
@@ -86,7 +102,7 @@
 //required amount of memory to keep bitmaps on RAM in bits
 const TInt KMemoryNeed = 5000000;
 
-const TInt64 KDiskFullThreshold = 1024*1024*1; // 1 MB
+const TInt64 KDiskFullThreshold = 1024*1024*10; // 10 MB
 
 _LIT( KThumbnailServerName, "ThumbnailServer" );
 _LIT( KThumbnailServerProcess, "*ThumbnailServer*" );
@@ -249,9 +265,18 @@
      * Control flags set by the server for handling specific situations
      * (for example for distinguishing between preview thumbnails and
      * final thumbnails).
+	 * Control flags may be modified by server to signal client side what actually was done, like preview TN
      */
     TThumbnailControlFlags iControlFlags;
     
+	
+    /**
+     * Original control flags set by the server for handling specific situations
+     * (for example for distinguishing between preview thumbnails and
+     * final thumbnails).
+     */
+    TThumbnailControlFlags iOriginalControlFlags;
+    
     /**
      * Thumbnail's modify timestamp
      */
@@ -365,8 +390,8 @@
     EChangePriority, 
 
     /**
-     * Create thumbnails for a file. File path is passed as a
-     * parameter.
+     * Deprecated
+     *
      */
     ECreateThumbnails, 
 
@@ -520,10 +545,6 @@
 enum TMDSQueryType
     {
     /**
-     * Query Id by Path
-     */
-    EId,
-    /**
      * Query Path by Id
      */
     EURI
--- a/imagehandlingutilities/thumbnailmanager/plugins/audio/src/thumbnailaudioprovider.cpp	Fri Feb 19 23:07:36 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/plugins/audio/src/thumbnailaudioprovider.cpp	Fri Mar 12 15:43:57 2010 +0200
@@ -23,8 +23,8 @@
 #include "thumbnailimagedecoderv3.h"
 #include "thumbnailmanageruids.hrh"
 #include "thumbnaillog.h"
-#include <metadatautility.h>
-#include <metadatafieldcontainer.h>
+#include <MetaDataUtility.h>
+#include <MetaDataFieldContainer.h>
 #include "thumbnailmanagerconstants.h"
 
 
@@ -82,6 +82,7 @@
     TDataType& aMimeType  , const CThumbnailManager::TThumbnailFlags aFlags,
     const TDisplayMode /*aDisplayMode*/, const CThumbnailManager::TThumbnailQualityPreference /*aQualityPreference*/  )
     {   
+    TN_DEBUG1( "CThumbnailAudioProvider::GetThumbnailL() - rfile " );
     CMetaDataUtility* metaDataUtil = CMetaDataUtility::NewL();
     CleanupStack::PushL( metaDataUtil );
     
@@ -129,7 +130,8 @@
     TDataType& /*aMimeType */, const CThumbnailManager::TThumbnailFlags /* aFlags */,
     const TDisplayMode /* aDisplayMode */, const CThumbnailManager::TThumbnailQualityPreference /*aQualityPreference*/ )
     {
-
+    TN_DEBUG1( "CThumbnailAudioProvider::GetThumbnailL() - buffer" );
+	__ASSERT_DEBUG((EFalse), User::Panic(_L("CThumbnailAudioProvider::GetThumbnailL"), KErrNotSupported));
     }
 
 // ---------------------------------------------------------------------------
@@ -139,7 +141,8 @@
 //
 void CThumbnailAudioProvider::GetThumbnailL( RFs& /* aFs */, TDesC8& /*aBuffer */)
     {
-    User::Leave( KErrNotSupported );
+    TN_DEBUG1( "CThumbnailAudioProvider::GetThumbnailL() - buffer no mime" );
+	__ASSERT_DEBUG((EFalse), User::Panic(_L("CThumbnailAudioProvider::GetThumbnailL"), KErrNotSupported));
     }
 
 // ---------------------------------------------------------------------------
--- a/imagehandlingutilities/thumbnailmanager/plugins/audio/src/thumbnailimagedecoderv3.cpp	Fri Feb 19 23:07:36 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/plugins/audio/src/thumbnailimagedecoderv3.cpp	Fri Mar 12 15:43:57 2010 +0200
@@ -19,9 +19,9 @@
 //INCLUDE FILES
 #include <e32base.h>
 #include <imageconversion.h>
-#include <exifread.h>
+#include <ExifRead.h>
 
-#include <iclextjpegapi.h>
+#include <IclExtJpegApi.h>
 #include "thumbnailimagedecoderv3.h"
 #include "thumbnaillog.h"
 #include "thumbnailpanic.h"
--- a/imagehandlingutilities/thumbnailmanager/plugins/image/src/thumbnailimagedecoder.cpp	Fri Feb 19 23:07:36 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/plugins/image/src/thumbnailimagedecoder.cpp	Fri Mar 12 15:43:57 2010 +0200
@@ -20,10 +20,10 @@
 //INCLUDE FILES
 #include <e32base.h>
 #include <imageconversion.h>
-#include <exifread.h>
+#include <ExifRead.h>
 #include <e32math.h>
 
-#include <iclextjpegapi.h>
+#include <IclExtJpegApi.h>
 #include "thumbnailimagedecoder.h"
 #include "thumbnaillog.h"
 #include "thumbnailpanic.h"
--- a/imagehandlingutilities/thumbnailmanager/plugins/image/src/thumbnailimagedecoderv2.cpp	Fri Feb 19 23:07:36 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/plugins/image/src/thumbnailimagedecoderv2.cpp	Fri Mar 12 15:43:57 2010 +0200
@@ -19,9 +19,9 @@
 //INCLUDE FILES
 #include <e32base.h>
 #include <imageconversion.h>
-#include <exifread.h>
+#include <ExifRead.h>
 
-#include <iclextjpegapi.h>
+#include <IclExtJpegApi.h>
 #include "thumbnailimagedecoderv2.h"
 #include "thumbnaillog.h"
 #include "thumbnailpanic.h"
--- a/imagehandlingutilities/thumbnailmanager/plugins/video/inc/thumbnailvideoprovider.h	Fri Feb 19 23:07:36 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/plugins/video/inc/thumbnailvideoprovider.h	Fri Mar 12 15:43:57 2010 +0200
@@ -20,7 +20,7 @@
 #define THUMBNAILVIDEOPROVIDER_H
 
 #include <ecom.h>
-#include <tnevideoclipinfo.h>
+#include <TNEVideoClipInfo.h>
 
 #include "thumbnailprovider.h"
 
Binary file imagehandlingutilities/thumbnailmanager/sis/thumbnailmanager/ThumbnailManager_0x102830AB_v9.20.3_SA_S60.50_Euro1.sis has changed
--- a/imagehandlingutilities/thumbnailmanager/sis/thumbnailmanager/package.pkg	Fri Feb 19 23:07:36 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/sis/thumbnailmanager/package.pkg	Fri Mar 12 15:43:57 2010 +0200
@@ -17,7 +17,7 @@
 &EN
 
 ; Header
-#{"Thumbnail Manager"},(0x102830AB), 9, 20, 2, TYPE=SA, RU
+#{"Thumbnail Manager"},(0x102830AB), 9, 20, 3, TYPE=SA, RU
 
 ; Localised Vendor name
 %{"Nokia"}
--- a/imagehandlingutilities/thumbnailmanager/sis/thumbnailmanager/stub.pkg	Fri Feb 19 23:07:36 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/sis/thumbnailmanager/stub.pkg	Fri Mar 12 15:43:57 2010 +0200
@@ -17,7 +17,7 @@
 &EN
 
 ; Header
-#{"ThumbnailManager"},(0x102830AB), 9, 20, 2, TYPE=SA
+#{"ThumbnailManager"},(0x102830AB), 9, 20, 3, TYPE=SA
 
 ; Localised Vendor name
 %{"Nokia"}
Binary file imagehandlingutilities/thumbnailmanager/sis/thumbnailmanager/thumbnailmanager_stub.sis has changed
--- a/imagehandlingutilities/thumbnailmanager/sis/thumbnailmanagercenrep/package.pkg	Fri Feb 19 23:07:36 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/sis/thumbnailmanagercenrep/package.pkg	Fri Mar 12 15:43:57 2010 +0200
@@ -17,7 +17,7 @@
 &EN
 
 ; Header
-#{"Thumbnail Manager Cenrep"},(0x10202BE9), 9, 20, 2, TYPE=SP
+#{"Thumbnail Manager Cenrep"},(0x10202BE9), 9, 20, 3, TYPE=SP
 
 ; Localised Vendor name
 %{"Symbian Software Ltd."}
--- a/imagehandlingutilities/thumbnailmanager/thumbagdaemon/group/thumbagdaemon.mmp	Fri Feb 19 23:07:36 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbagdaemon/group/thumbagdaemon.mmp	Fri Mar 12 15:43:57 2010 +0200
@@ -36,14 +36,18 @@
 
 EPOCPROCESSPRIORITY 	background
 
+//MACRO MDS_URI_OBSERVER
+MACRO TWO_PHASED_TN_GENERATION
+
 SOURCEPATH              ../src
 SOURCE                  thumbagdaemon.cpp
-SOURCE					thumbagprocessor.cpp
+SOURCE			thumbagprocessor.cpp
 
-SOURCEPATH 				../../tmcommon/src
-SOURCE					tmactivitymanager.cpp 
-SOURCE					tmshutdownobserver.cpp 
-SOURCE					tmformatobserver.cpp
+SOURCEPATH 		../../tmcommon/src
+SOURCE			tmactivitymanager.cpp 
+SOURCE			tmshutdownobserver.cpp 
+SOURCE			tmformatobserver.cpp 
+SOURCE			tmsrproptertyobserver.cpp
 
 // Default system include paths for middleware layer modules.
 MW_LAYER_SYSTEMINCLUDE
--- a/imagehandlingutilities/thumbnailmanager/thumbagdaemon/inc/thumbagdaemon.h	Fri Feb 19 23:07:36 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbagdaemon/inc/thumbagdaemon.h	Fri Mar 12 15:43:57 2010 +0200
@@ -39,6 +39,9 @@
                                      public MMdEObjectObserver,
                                      public MTMShutdownObserver,
                                      public MMdEObjectPresentObserver
+#ifdef MDS_URI_OBSERVER
+                                     ,public MMdEObjectObserverWithUri
+#endif
                                      
     {
 public:
@@ -97,6 +100,13 @@
                                   TObserverNotificationType aType,
                                   const RArray<TItemId>& aObjectIdArray);
     
+#ifdef MDS_URI_OBSERVER
+    void HandleUriObjectNotification(CMdESession& aSession, 
+                            TObserverNotificationType aType,
+                            const RArray<TItemId>& aObjectIdArray,
+                            const RPointerArray<HBufC>& aObjectUriArray);
+#endif
+    
     void HandleObjectPresentNotification(CMdESession& aSession, 
                 TBool aPresent, const RArray<TItemId>& aObjectIdArray);
     
@@ -142,6 +152,13 @@
      * @since S60 v5.2
      */
     void InitializeL();
+    
+    /**
+     * Callback for reconnect timer
+     *
+     * @since S60 v5.0
+     */
+    static TInt ReconnectCallBack(TAny* aAny);
 
 private:
 	
@@ -153,6 +170,9 @@
     
     TBool iShutdown;
  
+    // reconnect timer
+    CPeriodic* iReconnect;
+    
 #ifdef _DEBUG
     TUint32 iAddCounter;
     TUint32 iModCounter;
--- a/imagehandlingutilities/thumbnailmanager/thumbagdaemon/inc/thumbagprocessor.h	Fri Feb 19 23:07:36 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbagdaemon/inc/thumbagprocessor.h	Fri Mar 12 15:43:57 2010 +0200
@@ -29,9 +29,9 @@
 #include <harvesterclient.h>
 #include <e32property.h>
 #include <mpxcollectionobserver.h>
-#include <hwrmlight.h>
 #include "tmactivitymanager.h"
 #include "tmformatobserver.h"
+#include "tmrpropertyobserver.h"
 
 //FORWARD DECLARATIONS
 class MMPXCollectionUtility;
@@ -46,9 +46,9 @@
                          public MMdEQueryObserver,
                          public MHarvesterEventObserver,
                          public MMPXCollectionObserver,
-                         public MHWRMLightObserver,
                          public MTMActivityManagerObserver,
-                         public MTMFormatObserver
+                         public MTMFormatObserver,
+                         public MTMRPropertyObserver
     {
 public:
 
@@ -102,12 +102,11 @@
     /// See @ref MMPXCollectionObserver::HandleCollectionMediaL
     void HandleCollectionMediaL( const CMPXMedia& aMedia, TInt aError );
     
-private: //From MHWRMLightObserver
-    void LightStatusChanged(TInt aTarget, CHWRMLight::TLightStatus aStatus);
+private: //From MTMActivityManagerObserver
+    void ActivityChanged(const TBool aActive);
     
-private: //From MTMActivityManagerObserver
-    void ActivityDetected();
-    void InactivityDetected();
+private: //From MTMRPropertyObserver
+    void RPropertyNotification(const TInt aError, const TUid aKeyCategory, const TUint aPropertyKey, const TInt aValue);
     
 public:     
     
@@ -127,7 +126,7 @@
      * @param aIDArray IDs for thumbnail creation
      * @param aForce pass ETrue if processor is forced to run without waiting harvesting complete
      */
-    void AddToQueueL( TObserverNotificationType aType, const RArray<TItemId>& aIDArray, TBool aPresent );
+    void AddToQueueL( TObserverNotificationType aType, const RArray<TItemId>& aIDArray, const RPointerArray<HBufC>& aObjectUriArray, TBool aPresent );
     
     /**
      * Calls Thumbnail Manager to create thumbnails
@@ -147,8 +146,6 @@
     
     void SetForceRun( const TBool aForceRun );
     
-    TBool IsInactive();
-    
 protected:
     
     void QueryAllItemsL();
@@ -237,6 +234,14 @@
      * @since S60 v5.0
      */
     void CancelTimeout();
+   
+    /**
+     * Update KItemsLeft PS value
+     * 
+     * @since S60 v5.0
+ 	 * @param aDefine (re)define PS key before setting value
+     */
+    void UpdatePSValues(const TBool aDefine = EFalse);
        
 private:
     
@@ -252,10 +257,15 @@
     
     RArray<TItemId> iAddQueue;
     RArray<TItemId> iModifyQueue;
-    RArray<TItemId> iRemoveQueue;
+    RPointerArray<HBufC> iRemoveQueue;
     RArray<TItemId> iQueryQueue;
     RArray<TItemId> iPlaceholderQueue;
+    //not processing queue, used to keep KItemsLeft PS correct
+    RArray<TItemId> i2ndRoundGenerateQueue;
+	//reference to current processing queue
+    RArray<TItemId>* iLastQueue;
     
+    TBool i2ndRound;    
     
     TBool iQueryActive;
     TBool iQueryReady;
@@ -279,23 +289,21 @@
     //Set when running RunL() first time
     TBool iInit;
     
+    //2nd phase init after MDE session is open
+    TBool iInit2;
+    
     // auto create
     TBool iAutoImage;
     TBool iAutoVideo;
     TBool iAutoAudio;
     
-#ifdef _DEBUG
-    TUint32 iAddCounter;
-    TUint32 iModCounter;
-    TUint32 iDelCounter;
-#endif
-
+    // in case of modified files force TN update
     TBool iForceRun; 
+    // controlled by Photos application to run TN generation on foreground
+    TBool iForegroundRun;
 	//request pending in TNM side
     TBool iActive;
-    //PS key to get info server's idle status
-    RProperty iProperty;
-    
+   
     CTMFormatObserver* iFormatObserver;
    
     TBool iFormatting;
@@ -312,15 +320,14 @@
     //overall status of device
     TBool iIdle;
     
-    //Backlight control 
-    CHWRMLight* iLight;
-	#ifdef _DEBUG 
-    TInt iLightMask;
-	#endif
-    //backlight status
-    TBool iLights;
+    CTMActivityManager* iActivityManager;
     
-    CTMActivityManager* iActivityManager;
+	//Observer foreground generation 
+    CTMRPropertyObserver* iForegroundGenerationObserver;
+    
+	//Previously notified amount of items in processing queues (add/modify)
+    TInt iPreviousItemsLeft;
+    TBool iPreviousDaemonProcessing; 
 };
 
 #endif // THUMBAGPROCESSOR_H
--- a/imagehandlingutilities/thumbnailmanager/thumbagdaemon/src/thumbagdaemon.cpp	Fri Feb 19 23:07:36 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbagdaemon/src/thumbagdaemon.cpp	Fri Mar 12 15:43:57 2010 +0200
@@ -85,6 +85,8 @@
 #endif
     
     InitializeL();
+    
+    iReconnect = CPeriodic::NewL(CActive::EPriorityIdle);
     	
 	TN_DEBUG1( "CThumbAGDaemon::ConstructL() - end" );
 	}
@@ -163,6 +165,13 @@
     delete iMDSShutdownObserver;
     delete iShutdownObserver;
     
+    if(iReconnect)
+        {
+        iReconnect->Cancel();
+        delete iReconnect;
+        iReconnect = NULL;
+        }
+    
     if (iProcessor)
         {
         delete iProcessor;
@@ -171,10 +180,16 @@
     
     if (iMdESession)
         {
-        // 3 observers
+        // 2 observers
         TRAP_IGNORE( iMdESession->RemoveObjectObserverL( *this ) );
-        TRAP_IGNORE( iMdESession->RemoveObjectObserverL( *this ) );
-        TRAP_IGNORE( iMdESession->RemoveObjectObserverL( *this ) );
+//modify        TRAP_IGNORE( iMdESession->RemoveObjectObserverL( *this ) );
+        
+#ifdef MDS_URI_OBSERVER
+        // remove observer with uri
+        TRAP_IGNORE( iMdESession->RemoveObjectObserverWithUriL( *this ) );
+#endif
+        
+        //present observer
         TRAP_IGNORE(iMdESession->RemoveObjectPresentObserverL( * this  ));
         
         delete iMdESession;
@@ -264,12 +279,52 @@
     TN_DEBUG2( "CThumbAGDaemon::HandleSessionError == %d", aError );
     if (aError != KErrNone)
         {
-        delete iMdESession;
-        iMdESession = NULL;
-        TRAP_IGNORE(InitializeL());
+        // kill processor right away, because it also has MdESession
+        if(iProcessor)
+            {
+            delete iProcessor;
+            iProcessor = NULL; 
+            }
+    
+        if (!iShutdown)
+            {
+            if (!iReconnect->IsActive())
+                {
+                iReconnect->Start( KMdEReconnect, KMdEReconnect, 
+                                   TCallBack(ReconnectCallBack, this));
+                
+                TN_DEBUG1( "CThumbAGDaemon::HandleSessionError() - reconnect timer started" );
+                }
+            }
+
         }   
     }
 
+#ifdef MDS_URI_OBSERVER
+// -----------------------------------------------------------------------------
+// CThumbAGDaemon::HandleObjectNotification
+// -----------------------------------------------------------------------------
+//
+
+void CThumbAGDaemon::HandleUriObjectNotification(CMdESession& aSession, 
+        TObserverNotificationType aType,
+        const RArray<TItemId>& aObjectIdArray,
+        const RPointerArray<HBufC>& aObjectUriArray)
+    {
+    TN_DEBUG1( "CThumbAGDaemon::HandleUriObjectNotification() - begin" );
+    
+    if(aType == ENotifyRemove)
+        {
+        TN_DEBUG1( "CThumbAGDaemon::HandleUriObjectNotification() - removed");
+        TInt err(0);
+        TRAP(err, iProcessor->AddToQueueL(aType, aObjectIdArray, aObjectUriArray, EFalse));
+        __ASSERT_DEBUG((err==KErrNone), User::Panic(_L("CThumbAGDaemon::HandleUriObjectNotification()"), err));
+        err = KErrNone;
+        }
+    TN_DEBUG1( "CThumbAGDaemon::HandleUriObjectNotification() - end" );
+    }
+#endif
+
 // -----------------------------------------------------------------------------
 // CThumbAGDaemon::HandleObjectNotification
 // -----------------------------------------------------------------------------
@@ -290,17 +345,17 @@
     if (aType == ENotifyAdd)
         {
         TN_DEBUG2( "CThumbAGDaemon::HandleObjectNotification() - ENotifyAdd %d", aObjectIdArray.Count() );
-        iAddCounter = iAddCounter + aObjectIdArray.Count();
+        iAddCounter = aObjectIdArray.Count();
         }
     else if (aType == ENotifyModify)
         {
         TN_DEBUG2( "CThumbAGDaemon::HandleObjectNotification() - ENotifyModify %d", aObjectIdArray.Count() );
-        iModCounter = iModCounter + aObjectIdArray.Count();
+        iModCounter = aObjectIdArray.Count();
         }
     else if (aType == ENotifyRemove)
         {
         TN_DEBUG2( "CThumbAGDaemon::HandleObjectNotification() - ENotifyRemove %d", aObjectIdArray.Count() );
-        iDelCounter = iDelCounter + aObjectIdArray.Count();
+        iDelCounter = aObjectIdArray.Count();
         }
 #endif
     
@@ -316,7 +371,9 @@
             }
         
         // Add event to processing queue by type and enable force run
-        TRAPD(err, iProcessor->AddToQueueL(aType, aObjectIdArray, EFalse));
+        
+        RPointerArray<HBufC> dummyArray;
+        TRAPD(err, iProcessor->AddToQueueL(aType, aObjectIdArray, dummyArray, EFalse));
         if (err != KErrNone)
             {
             TN_DEBUG1( "CThumbAGDaemon::HandleObjectNotification() - error adding to queue" );
@@ -328,8 +385,12 @@
         }
     
 #ifdef _DEBUG
-    TN_DEBUG6( "CThumbAGDaemon::IN-COUNTERS---------- Type: %d Amount: %d, Add = %d Modify = %d Delete = %d", 
-               aType, aObjectIdArray.Count(), iAddCounter, iModCounter, iDelCounter );
+    TN_DEBUG4( "CThumbAGDaemon::IN-COUNTERS---------- Add = %d Modify = %d Delete = %d", 
+               iAddCounter, iModCounter, iDelCounter );
+    iModCounter = 0;
+    iDelCounter = 0;
+    iAddCounter = 0;
+    
 #endif
 
     TN_DEBUG1( "CThumbAGDaemon::HandleObjectNotification() - end" );
@@ -338,7 +399,7 @@
 // -----------------------------------------------------------------------------
 // CThumbAGDaemon::HandleObjectPresentNotification
 // -----------------------------------------------------------------------------
-//b
+//
 void CThumbAGDaemon::HandleObjectPresentNotification(CMdESession& /*aSession*/, 
                TBool aPresent, const RArray<TItemId>& aObjectIdArray)
     {
@@ -358,12 +419,13 @@
         if ( aObjectIdArray.Count() > 0) 
             {
 		    // do not force run of these items
-            TRAP(err, iProcessor->AddToQueueL(ENotifyAdd, aObjectIdArray, ETrue));
+            RPointerArray<HBufC> dummyArray;
+            TRAP(err, iProcessor->AddToQueueL(ENotifyAdd, aObjectIdArray, dummyArray, ETrue));
            
             TN_DEBUG2( "CThumbAGDaemon::HandleObjectPresentNotification() - ENotifyAdd %d", aObjectIdArray.Count() );     
            
            #ifdef _DEBUG
-           iAddCounter = iAddCounter + aObjectIdArray.Count();
+           iAddCounter = aObjectIdArray.Count();
            if (err != KErrNone)
                {
                TN_DEBUG1( "CThumbAGDaemon::HandleObjectPresentNotification() - error adding to queue" );
@@ -382,7 +444,7 @@
             }
         else
             {
-            iAddCounter = iAddCounter - aObjectIdArray.Count();
+            iDelCounter = aObjectIdArray.Count();
             }
         #endif
            
@@ -393,8 +455,11 @@
         }
     
     #ifdef _DEBUG
-    TN_DEBUG5( "CThumbAGDaemon::IN-COUNTERS---------- Amount: %d, Add = %d Modify = %d Delete = %d", 
-               aObjectIdArray.Count(), iAddCounter, iModCounter, iDelCounter );
+    TN_DEBUG4( "CThumbAGDaemon::IN-COUNTERS---------- Add = %d Modify = %d Delete = %d", 
+               iAddCounter, iModCounter, iDelCounter );
+    iModCounter = 0;
+    iDelCounter = 0;
+    iAddCounter = 0;
     #endif
     
     TN_DEBUG1( "CThumbAGDaemon::HandleObjectPresentNotification() - end" );
@@ -443,12 +508,14 @@
     
     // add observer
     iMdESession->AddObjectObserverL( *this, addCondition, ENotifyAdd ); 
-    
-    // modify observer
-    iMdESession->AddObjectObserverL( *this, modifyCondition, ENotifyModify );
+
+   // modify observer
+   //iMdESession->AddObjectObserverL( *this, modifyCondition, ENotifyModify );
  
-    // remove observer
-    iMdESession->AddObjectObserverL( *this, NULL, ENotifyRemove );
+#ifdef MDS_URI_OBSERVER
+    // remove observer with uri
+    iMdESession->AddObjectObserverWithUriL( *this, NULL, ENotifyRemove );
+#endif
     
     // object present observer
     iMdESession->AddObjectPresentObserverL( *this );
@@ -475,6 +542,26 @@
     }
 
 // ---------------------------------------------------------------------------
+// CThumbAGDaemon::ReconnectCallBack()
+// ---------------------------------------------------------------------------
+//
+TInt CThumbAGDaemon::ReconnectCallBack(TAny* aAny)
+    {
+    TN_DEBUG1( "CThumbAGDaemon::ReconnectCallBack() - reinitialize");
+    
+    CThumbAGDaemon* self = static_cast<CThumbAGDaemon*>( aAny );
+    
+    self->iReconnect->Cancel();
+    
+    // reconnect to MDS
+    TRAP_IGNORE( self->InitializeL() );
+    
+    TN_DEBUG1( "CThumbAGDaemon::ReconnectCallBack() - done");
+    
+    return KErrNone;
+    }
+
+// ---------------------------------------------------------------------------
 // E32Main
 // ---------------------------------------------------------------------------
 //
--- a/imagehandlingutilities/thumbnailmanager/thumbagdaemon/src/thumbagprocessor.cpp	Fri Feb 19 23:07:36 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbagdaemon/src/thumbagprocessor.cpp	Fri Mar 12 15:43:57 2010 +0200
@@ -24,7 +24,7 @@
 #include <mpxcollectionutility.h>
 #include <mpxmessagegeneraldefs.h>
 #include <mpxcollectionmessage.h>
-#include <CoreApplicationUIsDomainPSKeys.h> 
+#include <coreapplicationuisdomainpskeys.h> 
 
 #include "thumbagprocessor.h"
 #include "thumbnaillog.h"
@@ -65,12 +65,6 @@
     {
     TN_DEBUG1( "CThumbAGProcessor::ConstructL() - begin" );
     
-#ifdef _DEBUG
-    iAddCounter = 0;
-    iModCounter = 0;
-    iDelCounter = 0;
-#endif
-    
     iTMSession = CThumbnailManager::NewL( *this );
     iQueryAllItems = NULL;
     iQueryPlaceholders = NULL;
@@ -86,9 +80,7 @@
     
     iPeriodicTimer = CPeriodic::NewL(CActive::EPriorityIdle);
     
-    //do some initializing async in RunL()
-    iInit = ETrue;
-    iForceRun = EFalse;    
+    SetForceRun( EFalse );    
     iActive = EFalse;
     
     iFormatObserver = CTMFormatObserver::NewL( *this );
@@ -98,19 +90,20 @@
     
     iCollectionUtility = NULL;
     
-    iLight = CHWRMLight::NewL(this);
+    iActivityManager = CTMActivityManager::NewL( this, KBackgroundGenerationIdle);
+
+    UpdatePSValues(ETrue);
 
-#ifdef _DEBUG 
-    if(iLight)
-        {
-        iLightMask = iLight->SupportedTargets();
-        TN_DEBUG2( "CThumbAGProcessor::ConstructL() - iLightMask == %d", iLightMask );
-        }
-#endif
-        
-    iActivityManager = CTMActivityManager::NewL( this, KBackgroundGenerationIdle);
+    if(iForegroundGenerationObserver)
+      {
+      delete iForegroundGenerationObserver;
+      iForegroundGenerationObserver = NULL;
+      }
     
-    ActivateAO();
+    RProperty::Define(KTAGDPSNotification, KMPXHarvesting, RProperty::EInt);
+    
+	//start foreground generation observer
+    iForegroundGenerationObserver = CTMRPropertyObserver::NewL( *this, KTAGDPSNotification, KForceBackgroundGeneration, ETrue );  
     
     TN_DEBUG1( "CThumbAGProcessor::ConstructL() - end" );
     }
@@ -123,6 +116,12 @@
     {
     TN_DEBUG1( "CThumbAGProcessor::~CThumbAGProcessor() - begin" );
     
+    if(iForegroundGenerationObserver)
+      {
+      delete iForegroundGenerationObserver;
+      iForegroundGenerationObserver = NULL;
+      }
+    
     if(iActivityManager)
         {
         delete iActivityManager;
@@ -144,8 +143,9 @@
     
     if (!iInit)
         {
+    /*
         iHarvesterClient.RemoveHarvesterEventObserver(*this);
-        iHarvesterClient.Close();
+        iHarvesterClient.Close();*/
         }
     
     if ( iCollectionUtility )
@@ -176,12 +176,14 @@
        delete iQueryAllItems;
        iQueryAllItems = NULL;
        }
-    
+
     iAddQueue.Close();
     iModifyQueue.Close();
-    iRemoveQueue.Close();
+    iRemoveQueue.ResetAndDestroy();
     iQueryQueue.Close();
     iPlaceholderQueue.Close();
+	  
+    i2ndRoundGenerateQueue.Close();
     
     if (iTMSession)
         {
@@ -191,9 +193,6 @@
     
     delete iFormatObserver;
     
-    delete iLight;
-    iLight = NULL;
-    
     TN_DEBUG1( "CThumbAGProcessor::~CThumbAGProcessor() - end" );
     }
 
@@ -264,7 +263,7 @@
                     continue;
                     }
                
-                if (iAddQueue.Find( object->Id() ) == KErrNotFound)
+                if (iAddQueue.Find( object->Id() ) == KErrNotFound && iModifyQueue.Find( object->Id()) == KErrNotFound  )
                     {
                     TRAP_IGNORE( iAddQueue.AppendL( object->Id() ));
                     }
@@ -280,6 +279,7 @@
     else if(&aQuery == iQuery )
         {
         TN_DEBUG1( "CThumbAGProcessor::HandleQueryCompleted - Query completed");
+        
         if(iQueryActive)
             {
             iQueryReady = ETrue;
@@ -290,9 +290,30 @@
         if (aError == KErrNone && iQuery)
             {
             iProcessingCount = iQuery->Count();
+			
+            if( !iProcessingCount)
+                {
+                delete iQuery;
+                iQuery = NULL;
+                iProcessingCount = 0;
+                iModify = EFalse;
+                }
             }
         else
             {
+            TInt itemIndex(KErrNotFound);
+            
+            //cleanup current queue
+            while(iQueryQueue.Count())
+                {
+                itemIndex = iLastQueue->Find(iQueryQueue[0]);
+                if(itemIndex >= 0)
+                    {
+                    iLastQueue->Remove( itemIndex );
+                    }
+                iQueryQueue.Remove(0);
+                }
+        
             delete iQuery;
             iQuery = NULL;
             iProcessingCount = 0;
@@ -315,6 +336,7 @@
 void CThumbAGProcessor::ThumbnailPreviewReady( MThumbnailData& /*aThumbnail*/, 
                                                TThumbnailRequestId /*aId*/)
     {
+    TN_DEBUG1( "CThumbAGProcessor::ThumbnailPreviewReady()");
     // No implementation required
     }
 
@@ -326,8 +348,14 @@
                                         TThumbnailRequestId /*aId*/ )
     {
     TN_DEBUG2( "CThumbAGProcessor::ThumbnailReady() aError == %d", aError );
- 
-    iActive = EFalse; 
+    
+    iActiveCount--;
+    
+    if(iActiveCount <= 0)
+        {
+        iActiveCount = 0;
+        iActive = EFalse;
+        }
     
     // TNM server died, delete session
     if( aError == KErrServerTerminated )
@@ -349,6 +377,7 @@
         }
     
     ActivateAO();
+	
     TN_DEBUG1( "CThumbAGProcessor::ThumbnailReady() - end" );
     }
 
@@ -362,14 +391,18 @@
     
     iMdESession = aMdESession;
     
+    __ASSERT_DEBUG((iMdESession), User::Panic(_L("CThumbAGProcessor::SetMdESession() !iMdESession "), KErrBadHandle));
+    
     TRAPD( err, iDefNamespace = &iMdESession->GetDefaultNamespaceDefL() );
     if (err != KErrNone)
         {
-        TN_DEBUG1( "CThumbAGProcessor::SetMdESession - Error: GetDefaultNamespaceDefL leave" );
+        TN_DEBUG2( "CThumbAGProcessor::SetMdESession() GetDefaultNamespaceDefL() err = %d", err );
         }
     
-    TRAP_IGNORE(QueryPlaceholdersL());
-    TRAP_IGNORE(QueryAllItemsL());
+    __ASSERT_DEBUG((iDefNamespace), User::Panic(_L("CThumbAGProcessor::SetMdESession() !iDefNamespace "), KErrBadHandle));
+       
+    //do async init
+    iInit = ETrue;
     
 	ActivateAO();
     }
@@ -379,7 +412,9 @@
 // ---------------------------------------------------------------------------
 //
 void CThumbAGProcessor::AddToQueueL( TObserverNotificationType aType, 
-                                    const RArray<TItemId>& aIDArray, TBool /*aPresent*/ )
+                                    const RArray<TItemId>& aIDArray, 
+                                    const RPointerArray<HBufC>& aObjectUriArray,
+                                    TBool /*aPresent*/ )
     {
     TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() - begin" );
 
@@ -390,10 +425,10 @@
         
         for (int i=0; i<aIDArray.Count(); i++)
             {
-            // only add to Add queue if not already in Add queue        
-            if (iAddQueue.Find( aIDArray[i] ) == KErrNotFound)
+            // do not to append to Add queue if exist already in Add or 2nd Add queue (just processed)     
+            if (iAddQueue.Find( aIDArray[i] ) == KErrNotFound && i2ndRoundGenerateQueue.Find( aIDArray[i] ) == KErrNotFound)
                 {
-                iAddQueue.AppendL(aIDArray[i]); 
+                iAddQueue.AppendL(aIDArray[i]);
                 }
             }
         }
@@ -403,15 +438,10 @@
         
         if(iPHHarvesting)
             {
+        
             TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() - PH  harvesting active, treat like add" );
             for (int i=0; i<aIDArray.Count(); i++)
                 {
-                // only add to Add queue if not already in Add queue        
-                if (iAddQueue.Find( aIDArray[i] ) == KErrNotFound)
-                    {
-                    iAddQueue.AppendL(aIDArray[i]); 
-                    }
-                
                 TInt itemIndex = iPlaceholderQueue.Find( aIDArray[i] );
                                 
                 if (itemIndex >= 0)
@@ -419,6 +449,12 @@
                     TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() - remove from placeholder queue");
                     iPlaceholderQueue.Remove( itemIndex );
                     }
+                
+                if(iAddQueue.Find( aIDArray[i]) == KErrNotFound && i2ndRoundGenerateQueue.Find( aIDArray[i]))
+                    {
+                    TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() - append to add queue");
+                    iAddQueue.Append( aIDArray[i]);
+                    }
                 }
             }
         else
@@ -435,7 +471,6 @@
                     {
                     TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() - placeholder modify, remove from placeholder queue");
                     iPlaceholderQueue.Remove( itemIndex );
-                    iAddQueue.Append( aIDArray[i] );
                     }
                 else
                     {
@@ -447,12 +482,20 @@
                         TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() - remove from add queue");
                         iAddQueue.Remove( itemIndex );
                         }
+					else
+						{
+						
+						itemIndex = i2ndRoundGenerateQueue.Find( aIDArray[i] );
+                                    
+	                    if (itemIndex >= 0)
+	                        {
+	                        TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() - remove from 2nd round add queue");
+	                        i2ndRoundGenerateQueue.Remove( itemIndex );
+	                        }
+					}
                     
-                    if( iPlaceholderQueue.Find( aIDArray[i] ) == KErrNotFound )
-                        {
-                        TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() - append to modify queue");
-                        iModifyQueue.AppendL(aIDArray[i]);
-                        }
+                    TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() - append to modify queue");
+                    iModifyQueue.AppendL(aIDArray[i]);
                     
                     SetForceRun( ETrue );
                     } 
@@ -461,7 +504,7 @@
         }
         else if (aType == ENotifyRemove)
             {
-            TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() - ENotifyRemove, remove IDs from all queues, append to Delete" );
+            TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() - ENotifyRemove, remove IDs from all queues");
             
             for (int i=0; i<aIDArray.Count(); i++)
                 {
@@ -478,20 +521,21 @@
                     {
                     iModifyQueue.Remove(itemIndex);
                     }
-                
-                //add to remove queue
-                if (iRemoveQueue.Find( aIDArray[i] ) == KErrNotFound)
-                    {
-                    iRemoveQueue.AppendL(aIDArray[i]);
-                    }
+                }
+            
+            TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() - ENotifyRemove append URIs to remove queue");
+            for (int i=0; i<aObjectUriArray.Count(); i++)
+                {
+                HBufC* temp = aObjectUriArray[i]->AllocL();
+                iRemoveQueue.Append( temp );
+                TN_DEBUG2( "CThumbAGProcessor::AddToQueueL() - %S", temp); 
                 }
             }
 #ifdef _DEBUG
         else
             {
 	        TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() -  should not come here" );
-            __ASSERT_DEBUG((EFalse), User::Panic(_L("CThumbAGProcessor::AddToQueueL()"), -2));
-			return;
+	        User::Leave( KErrArgument );
             }
 #endif
     
@@ -508,12 +552,20 @@
     {
     TN_DEBUG1( "CThumbAGProcessor::CreateThumbnailsL() - begin" );
     
+    __ASSERT_DEBUG((iTMSession), User::Panic(_L("CThumbAGProcessor::CreateThumbnailsL() !iTMSession "), KErrBadHandle));
+    __ASSERT_DEBUG((iDefNamespace), User::Panic(_L("CThumbAGProcessor::CreateThumbnailsL() !iDefNamespace "), KErrBadHandle));
+    
+    if(!iTMSession || !iDefNamespace)
+        {
+        return;
+        }
+    
     TInt orientationVal = 0;
     TInt64 modifiedVal = 0;
     
     CMdEProperty* orientation = NULL;
-    CMdEObjectDef& objDef = iDefNamespace->GetObjectDefL( MdeConstants::Image::KImageObject );       
-    TInt orientErr = aObject->Property( objDef.GetPropertyDefL( MdeConstants::Image::KOrientationProperty ), orientation, 0 );
+    CMdEObjectDef& imageObjectDef = iDefNamespace->GetObjectDefL( MdeConstants::Image::KImageObject );       
+    TInt orientErr = aObject->Property( imageObjectDef.GetPropertyDefL( MdeConstants::Image::KOrientationProperty ), orientation, 0 );
     
     if (orientErr == KErrNone)
         {
@@ -521,23 +573,57 @@
         }
         
     CMdEProperty* modified = NULL;
-    CMdEObjectDef& objDef2 = iDefNamespace->GetObjectDefL( MdeConstants::Object::KBaseObject );       
-    TInt modifyErr = aObject->Property( objDef2.GetPropertyDefL( MdeConstants::Object::KLastModifiedDateProperty ), modified, 0 );
-    
+    CMdEObjectDef& baseObjDef = iDefNamespace->GetObjectDefL( MdeConstants::Object::KBaseObject );       
+    TInt modifyErr = aObject->Property( baseObjDef.GetPropertyDefL( MdeConstants::Object::KLastModifiedDateProperty ), modified, 0 );
+
     if (modifyErr >= 0)
         {
         modifiedVal = modified->TimeValueL().Int64();
         }
     
-    // modify existing thumbs
+    // update thumbs
     if (iTMSession)
         {
+		// 2nd round and modify updates both sizes if needed
+        if( i2ndRound )
+            {
+            //generate both if needed
+            TN_DEBUG1( "CThumbAGProcessor::CreateThumbnailsL() EOptimizeForQuality ");
+            iTMSession->SetQualityPreferenceL( CThumbnailManager::EOptimizeForQuality );
+            }
+		// 1st roung generation
+        else
+            {
+            //1st round
+            TN_DEBUG1( "CThumbAGProcessor::CreateThumbnailsL() EOptimizeForQualityWithPreview");
+            iTMSession->SetQualityPreferenceL( CThumbnailManager::EOptimizeForQualityWithPreview );
+            
+            CMdEObjectDef& videoObjectDef = iDefNamespace->GetObjectDefL( MdeConstants::Video::KVideoObject );
+            
+            // add item to 2nd round queue 
+            if(iLastQueue == &iAddQueue || iLastQueue == &iModifyQueue)
+                {
+                TN_DEBUG2( "CThumbAGProcessor::CreateThumbnailsL() - 1st round add/modify, append to 2nd round queue", aObject->Id() );
+                if(i2ndRoundGenerateQueue.Find(aObject->Id()) == KErrNotFound)
+                    {
+                    i2ndRoundGenerateQueue.Append( aObject->Id() );
+                    }
+                }
+            
+           if( !(imageObjectDef.Id() == aObject->Def().Id() || videoObjectDef.Id() == aObject->Def().Id()) )
+                {
+                TN_DEBUG1( "CThumbAGProcessor::CreateThumbnailsL() 1st round and not image or video, skip");
+                ActivateAO();
+                return;
+                }
+            }
+
         // run as lower priority than getting but higher that creating thumbnails
-        TRAPD(err, iTMSession->UpdateThumbnailsL(aObject->Id(), aObject->Uri(), orientationVal, modifiedVal, CActive::EPriorityIdle ));
-        
+        TRAPD(err, iTMSession->UpdateThumbnailsL(KNoId, aObject->Uri(), orientationVal, modifiedVal, CActive::EPriorityIdle ));
+      
         if ( err != KErrNone )
             {
-            TN_DEBUG2( "CThumbAGProcessor::UpdateThumbnailsL, iTMSession error == %d", err );
+            TN_DEBUG2( "CThumbAGProcessor::CreateThumbnailsL, iTMSession error == %d", err );
             
             iSessionDied = ETrue;
             iActive = EFalse;
@@ -545,6 +631,7 @@
             } 
         else
             {
+            iActiveCount++;
             iActive = ETrue;
             }
         }
@@ -553,22 +640,6 @@
         ActivateAO();
         }
         
-#ifdef _DEBUG
-    if(iModify)
-        {
-        iModCounter++;
-        }
-    else
-        {
-        iAddCounter++;
-        }
-#endif     
-        
-#ifdef _DEBUG
-    TN_DEBUG3( "CThumbAGProcessor::OUT-COUNTERS----------, Add = %d Modify = %d", 
-               iAddCounter, iModCounter );
-#endif
-   
     TN_DEBUG1( "CThumbAGProcessor::CreateThumbnailsL() - end" );
     }
 
@@ -580,6 +651,19 @@
     {
     TN_DEBUG1( "CThumbAGProcessor::QueryL() - begin" );
     
+    __ASSERT_DEBUG((iMdESession), User::Panic(_L("CThumbAGProcessor::QueryL() !iMdeSession "), KErrBadHandle));
+    __ASSERT_DEBUG((iDefNamespace), User::Panic(_L("CThumbAGProcessor::QueryL() !iDefNamespace "), KErrBadHandle));
+    
+    if(!iMdESession  || !iDefNamespace)
+        {
+        return;
+        }
+    
+	//reset query queue
+    iQueryQueue.Reset();
+	//set reference to current pprocessing queue
+    iLastQueue = &aIDArray;
+    
     iQueryReady = EFalse;
 
     // delete old query
@@ -596,9 +680,8 @@
     
     for(TInt i=0;i < KMaxQueryItems && i < maxCount; i++)
         {
-        TN_DEBUG2( "CThumbAGProcessor::QueryL() - fill %d", aIDArray[0] );
-        iQueryQueue.Append( aIDArray[0] );
-        aIDArray.Remove( 0 );
+        TN_DEBUG2( "CThumbAGProcessor::QueryL() - fill %d", aIDArray[i] );
+        iQueryQueue.Append( aIDArray[i] );
         }
     
     TN_DEBUG3( "CThumbAGProcessor::QueryL() - fill end aIDArray == %d, iQueryQueue == %d", aIDArray.Count(), iQueryQueue.Count() );
@@ -639,8 +722,6 @@
     
     iQuery->FindL();
     
-    iQueryQueue.Reset();
-    
     TN_DEBUG1( "CThumbAGProcessor::QueryL() - end" );
     }
 
@@ -654,13 +735,17 @@
     {
     TN_DEBUG1( "CThumbAGProcessor::QueryPlaceholdersL" );
     
-    CMdEObjectQuery::TState state(CMdEObjectQuery::EStateFirst);
+    __ASSERT_DEBUG((iMdESession), User::Panic(_L("CThumbAGProcessor::QueryPlaceholdersL() !iMdeSession "), KErrBadHandle));
+    __ASSERT_DEBUG((iDefNamespace), User::Panic(_L("CThumbAGProcessor::QueryPlaceholdersL() !iDefNamespace "), KErrBadHandle));
+    
+    if(!iMdESession  || !iDefNamespace)
+         {
+         return;
+         }
     
     if( iQueryPlaceholders )
         {
-        state = iQueryPlaceholders->State();
-    
-        if(state == CMdEObjectQuery::EStateSearching )
+        if( !iQueryPlaceholders->IsComplete() )
             {
             TN_DEBUG1( "CThumbAGProcessor::QueryPlaceholdersL active- skip" );
             return;
@@ -714,30 +799,65 @@
     
     if (iSessionDied)
         {
+        TN_DEBUG1( "CThumbAGProcessor::RunL() - iSessionDied" );
         delete iTMSession;
         iTMSession = NULL;
         }
     
     if (iInit)
         {
-        TN_DEBUG1( "CThumbAGProcessor::RunL() - Do Initialisation" );
+        TN_DEBUG1( "CThumbAGProcessor::RunL() - Do Initialisation 1" );
+        
         iInit = EFalse;
-        TN_DEBUG1( "iHarvesterClient");
-        if( iHarvesterClient.Connect() == KErrNone )
+        iInit2 = ETrue;
+
+        iAddQueue.Reset();
+        iModifyQueue.Reset();
+        iRemoveQueue.ResetAndDestroy();
+        iQueryQueue.Reset();
+        iPlaceholderQueue.Reset();
+        
+        TRAP_IGNORE(QueryPlaceholdersL());
+        TN_DEBUG1( "CThumbAGProcessor::RunL() - Initialisation 1 done" );
+        ActivateAO();
+        return;
+        }
+    
+    if(iInit2)
+        {
+        TN_DEBUG1( "CThumbAGProcessor::RunL() - Do Initialisation 2" );
+		
+        iInit2 = EFalse;
+        TInt err(KErrNone);
+        /*
+        TN_DEBUG1( "CThumbAGProcessor::RunL() do iHarvesterClient connect");
+        TInt err = iHarvesterClient.Connect();
+        TN_DEBUG2( "CThumbAGProcessor::RunL() iHarvesterClient connect err = %d", err);
+        
+        __ASSERT_DEBUG((err==KErrNone), User::Panic(_L("CThumbAGProcessor::RunL(), !iHarvesterClient "), err));
+        
+        if(  err == KErrNone )
             {
-            TN_DEBUG1( "iHarvesterClient connected");
-            iHarvesterClient.AddHarvesterEventObserver( *this, EHEObserverTypeOverall, KMaxTInt );
-            iHarvesterClient.AddHarvesterEventObserver( *this, EHEObserverTypePlaceholder, KMaxTInt );
-            iHarvesterClient.AddHarvesterEventObserver( *this, EHEObserverTypeMMC, KMaxTInt );
-            TN_DEBUG1( "iHarvesterClient AddHarvesterEventObserver added");
+            TN_DEBUG1( "CThumbAGProcessor::RunL() add iHarvesterClient observer");
+            err = iHarvesterClient.AddHarvesterEventObserver( *this, EHEObserverTypeOverall | EHEObserverTypePlaceholder, KMaxTInt );
+            TN_DEBUG2( "CThumbAGProcessor::RunL() iHarvesterClient observer err = %d", err);
+            __ASSERT_DEBUG((err==KErrNone), User::Panic(_L("CThumbAGProcessor::RunL(), !iHarvesterClient "), err));
+            }*/
+ 
+        TN_DEBUG1( "CThumbAGProcessor::RunL() MMPXCollectionUtility");
+        TRAP( err, iCollectionUtility = MMPXCollectionUtility::NewL( this, KMcModeIsolated ));
+        TN_DEBUG2( "CThumbAGProcessor::RunL() create MMPXCollectionUtility err = %d", err);
+        __ASSERT_DEBUG((iCollectionUtility), User::Panic(_L("CThumbAGProcessor::RunL(), !iCollectionUtility "), err));
+        
+        __ASSERT_DEBUG((iActivityManager), User::Panic(_L("CThumbAGProcessor::RunL(), !iActivityManager "), KErrBadHandle));
+        if(iActivityManager)
+            {
+            iActivityManager->Start();
             }
         
-        TN_DEBUG1( "create MMPXCollectionUtility");
-        iCollectionUtility = MMPXCollectionUtility::NewL( this, KMcModeIsolated );
-        TN_DEBUG1( "CThumbAGProcessor::RunL() - Initialisation done" );
-        
-        iActivityManager->Start();
-        
+        TRAP_IGNORE(QueryAllItemsL());
+		
+        TN_DEBUG1( "CThumbAGProcessor::RunL() - Initialisation 2 done" );
         return;
         }
     
@@ -763,47 +883,45 @@
     // do not run if request is already issued to TNM server even if forced
     if( iActive)
         {
-        if(iActiveCount <= KMaxDaemonRequests)
+        if(iActiveCount >= KMaxDaemonRequests)
             {
-            iActiveCount++;
             TN_DEBUG1( "CThumbAGProcessor::RunL() - waiting for previous to complete, abort..." );
             return;
             }
-        else
-            {
-            TN_DEBUG1( "CThumbAGProcessor::RunL() - iActive jammed - resetted" );
-            iActive = EFalse;
-            iActiveCount = 0;
-            }     
         }
     else
         {
         iActiveCount = 0;   
         }
     
+    
     //force run can proceed from this point
-	if( iForceRun )
-	    {
-	    CancelTimeout();
-	    TN_DEBUG1( "void CThumbAGProcessor::RunL() forced run, continue!");
-	    }
-	else
+#ifdef _DEBUG
+	if( iForegroundRun )
+		{
+      	TN_DEBUG1( "void CThumbAGProcessor::RunL() KForceBackgroundGeneration enabled");
+	  	}
+	
+    if( iForceRun )
+        {
+        TN_DEBUG1( "CThumbAGProcessor::RunL() - *** FORCED RUN ***");
+        }
+#endif
+	
+  	if( /*iForceRun || */iForegroundRun )
+      	{
+        TN_DEBUG1( "void CThumbAGProcessor::RunL() skip idle detection!");
+      	CancelTimeout();
+     	 }
+  	else
 	    {
-	    if( !iLights)
-	        {
-            iIdle = ETrue;
+        if(iActivityManager)
+            {
+            iIdle = iActivityManager->IsInactive();
             }
-        else
-            {
-            iIdle = IsInactive();
-            }
-        
+	    
         if( !iIdle || iHarvesting || iMPXHarvesting || iPeriodicTimer->IsActive() )
             {
-            #ifdef _DEBUG
-            TN_DEBUG5( "iIdle = %d, iHarvesting = %d, iMPXHarvesting = %d, iPeriodicTimer->IsActive() = %d", 
-                    iIdle, iHarvesting, iMPXHarvesting, iPeriodicTimer->IsActive());
-            #endif
             TN_DEBUG1( "void CThumbAGProcessor::RunL() device not idle");
             return;
             }
@@ -832,32 +950,56 @@
         {
         TInt err(KErrNone);
         //if force or non forced
-        if((iForceRun && iModify) || (!iForceRun && !iModify))
+        if((iForceRun && iModify ) || (!iForceRun && !iModify ))
             {
             TN_DEBUG1( "CThumbAGProcessor::RunL() - iQueryReady START" );
             
             const CMdEObject* object = &iQuery->Result( iProcessingCount-1 );
             iProcessingCount--;
-        
+            
+            TInt itemIndex = iLastQueue->Find( object->Id());
+            if(itemIndex >= 0)
+                {
+                iLastQueue->Remove(itemIndex);
+                }
+				
             // process one item at once
             if ( object )
                 {
-                TRAP( err, CreateThumbnailsL(object) );
+                //remove item from queryQueue when request is issued 
+                itemIndex = iQueryQueue.Find( object->Id());
+                if(itemIndex >= 0)
+                    {
+                    iQueryQueue.Remove(itemIndex);
+                    }
             
-                if ( err != KErrNone )
-                    { 
-                    TN_DEBUG2( "CThumbAGProcessor::RunL(), CreateThumbnailsL error == %d", err );
-                    }
+                TRAP( err, CreateThumbnailsL(object) );
+                TN_DEBUG2( "CThumbAGProcessor::RunL(), CreateThumbnailsL error == %d", err );
+                __ASSERT_DEBUG((err==KErrNone), User::Panic(_L("CThumbAGProcessor::RunL(), CreateThumbnailsL() "), err));
                 }
             }
         //force is coming, but executing non-forced query complete-> cancel old
         else
             {
-            TN_DEBUG1( "CThumbAGProcessor::RunL() - deleting query" );
+            TN_DEBUG1( "CThumbAGProcessor::RunL() - deleting query 1" );
             delete iQuery;
             iQuery = NULL;
             iQueryReady = EFalse;
             iProcessingCount = 0;
+            
+            //move remainig IDs in query queue back to original queue
+            while(iQueryQueue.Count())
+                {
+                if(iLastQueue)
+                    {
+                    if(iLastQueue->Find( iQueryQueue[0]) == KErrNotFound)
+                        {
+                        iLastQueue->Append(iQueryQueue[0]);
+                        }
+                    }
+                iQueryQueue.Remove(0);
+                }
+            iLastQueue = NULL;
             ActivateAO();
             return;    
             }
@@ -873,11 +1015,11 @@
             //check if forced run needs to continue
             if (iModifyQueue.Count())
                 {
-                iForceRun = ETrue;
+                SetForceRun( ETrue );
                 }
             else
                 {
-                iForceRun = EFalse;
+                SetForceRun( EFalse );
                 }   
             }
         //keep going if processing Remove items or if Add item fails
@@ -891,12 +1033,31 @@
         {
         if(iForceRun && !iModify)
             {
-            iQuery->Cancel();
-            delete iQuery;
-            iQuery = NULL;
-            TN_DEBUG1( "CThumbAGProcessor::RunL() - canceling query..." );
+            if(iQuery)
+                {
+                TN_DEBUG1( "CThumbAGProcessor::RunL() - deleting query 2" );
+                iQuery->Cancel();
+                delete iQuery;
+                iQuery = NULL;
+                }
+
             iQueryReady = EFalse;
             iQueryActive = EFalse;
+            
+            //move remainig IDs in query queue back to original queue
+            while(iQueryQueue.Count())
+                {
+                if(iLastQueue)
+                    {
+                    if(iLastQueue->Find( iQueryQueue[0]) == KErrNotFound)
+                        {
+                        iLastQueue->Append(iQueryQueue[0]);
+                        }
+                    }
+                iQueryQueue.Remove(0);
+                }
+            iLastQueue = NULL;
+            
             ActivateAO();
             }
         else  
@@ -905,42 +1066,65 @@
             }    
         }
 
-    // select queue to process, priority by type. Process modify events before new images
+    // no items in query queue, start new
+    // select queue to process, priority by type
     else if ( iModifyQueue.Count() > 0 )
         {
         TN_DEBUG1( "void CThumbAGProcessor::RunL() update thumbnails");
         
+        i2ndRound = EFalse;
+        
         // query for object info
         iQueryActive = ETrue;
         iModify = ETrue;
         QueryL( iModifyQueue );
        }
-    else if ( iRemoveQueue.Count() > 0 )
-        {
-        TN_DEBUG1( "void CThumbAGProcessor::RunL() delete thumbnails");
-        
-        // delete thumbs by ID
-        if (iTMSession)
-            {
-            iTMSession->DeleteThumbnails( iRemoveQueue[0] );
-            }
-        iRemoveQueue.Remove( 0 );
-            
-#ifdef _DEBUG
-        iDelCounter++;
-        TN_DEBUG2( "CThumbAGProcessor::OUT-COUNTERS----------, Delete = %d", iDelCounter );
-#endif
-        ActivateAO();
-        }
     else if ( iAddQueue.Count() > 0 )
         {
-        TN_DEBUG1( "void CThumbAGProcessor::RunL() create thumbnails");
+        TN_DEBUG1( "void CThumbAGProcessor::RunL() update 1st round thumbnails");
+        
+        i2ndRound = EFalse;
         
         // query for object info
         iQueryActive = ETrue;
         
         QueryL( iAddQueue );     
         }
+    else if ( iRemoveQueue.Count() > 0 )
+        {
+        TN_DEBUG1( "void CThumbAGProcessor::RunL() delete thumbnails");
+
+        i2ndRound = EFalse;
+        
+        // delete thumbs by URI
+        __ASSERT_DEBUG((iTMSession), User::Panic(_L("CThumbAGProcessor::RunL() !iTMSession "), KErrBadHandle));
+        if(iTMSession)
+            {
+            HBufC* uri = iRemoveQueue[0];
+            TN_DEBUG2( "void CThumbAGProcessor::RunL() delete %S",  uri);
+            CThumbnailObjectSource* source = NULL;
+            TRAPD(err,  source = CThumbnailObjectSource::NewL( *uri, KNullDesC));
+               
+        	if(err == KErrNone)
+            	{
+                iTMSession->DeleteThumbnails( *source );
+                }
+            iRemoveQueue.Remove( 0 );
+            delete source;
+            delete uri;
+            }
+            
+        ActivateAO();
+        }
+    else if( i2ndRoundGenerateQueue.Count() > 0)
+        {
+        TN_DEBUG1( "void CThumbAGProcessor::RunL() update 2nd round thumbnails");
+            
+        // query for object info
+        iQueryActive = ETrue;
+        i2ndRound = ETrue;
+        QueryL( i2ndRoundGenerateQueue );     
+        }
         
     TN_DEBUG1( "CThumbAGProcessor::RunL() - end" );
     }
@@ -970,10 +1154,6 @@
         {
         TN_DEBUG1( "CThumbAGProcessor::HarvestingUpdated -- type EHEObserverTypeOverall");
         }
-    else
-        {
-        TN_DEBUG1( "CThumbAGProcessor::HarvestingUpdated -- type EHEObserverTypeMMC");
-        }
     #endif
     
     //placeholder harvesting
@@ -1050,22 +1230,7 @@
                 }
             }
         }
-    else if( aHEObserverType == EHEObserverTypeMMC)
-        {
-        switch(aHarvesterEventState)
-            {
-            case EHEStateStarted:
-            case EHEStateHarvesting:
-            case EHEStateResumed:
-                TN_DEBUG1( "CThumbAGProcessor::HarvestingUpdated -- MMC harvesting started ");
-                break;
-            case EHEStateFinished:
-                TN_DEBUG1( "CThumbAGProcessor::HarvestingUpdated -- MMC harvesting finished ");
-                TRAP_IGNORE(QueryAllItemsL());
-            break;
-            };
-        }
-
+   
     TN_DEBUG3( "CThumbAGProcessor::HarvestingUpdated -- end() iHarvesting == %d, iPHHarvesting == %d ", iHarvesting, iPHHarvesting);
     }
 
@@ -1101,16 +1266,26 @@
 // CThumbAGProcessor::RunError()
 // ---------------------------------------------------------------------------
 //
+#ifdef _DEBUG
 TInt CThumbAGProcessor::RunError(TInt aError)
+#else
+TInt CThumbAGProcessor::RunError(TInt /*aError*/)
+#endif
     {
-    TN_DEBUG1( "CThumbAGProcessor::RunError()");
-    if (aError != KErrNone)
+    TN_DEBUG2( "CThumbAGrocessor::RunError() %d", aError);
+    
+    UpdatePSValues();
+        
+    iActiveCount--;
+    
+    if(iActiveCount <= 0)
         {
-        TN_DEBUG2( "CThumbAGProcessor::RunError = %d", aError );
+        iActiveCount = 0;
+        iActive = EFalse;
         }
     
-    iActive = EFalse;
-    
+	ActivateAO();
+	
     // nothing to do
     return KErrNone;
     }
@@ -1122,7 +1297,12 @@
 void CThumbAGProcessor::ActivateAO()
     {
 #ifdef _DEBUG
-    TN_DEBUG6( "CThumbAGProcessor::Items in queue Add = %d, Mod = %d, Del = %d, Query = %d, iPlaceholder = %d", iAddQueue.Count(),  iModifyQueue.Count(), iRemoveQueue.Count(), iQueryQueue.Count(), iPlaceholderQueue.Count());
+    TN_DEBUG6( "CThumbAGProcessor::ActivateAO() items in queue Add = %d, Mod = %d, Del = %d, Query = %d, iPlaceholder = %d", iAddQueue.Count(),  iModifyQueue.Count(), iRemoveQueue.Count(), iQueryQueue.Count(), iPlaceholderQueue.Count());
+    TN_DEBUG2( "CThumbAGProcessor::ActivateAO() items in queue 2nd Add = %d", i2ndRoundGenerateQueue.Count());
+    TN_DEBUG3( "CThumbAGProcessor::ActivateAO() iActive = %d, iActiveCount = %d", iActive, iActiveCount);
+    TN_DEBUG3( "CThumbAGProcessor::ActivateAO() iHarvesting == %d, iMPXHarvesting == %d", iHarvesting, iMPXHarvesting);
+    TN_DEBUG4( "CThumbAGProcessor::ActivateAO() iIdle = %d, timer = %d, iForceRun = %d", iIdle, iPeriodicTimer->IsActive(), iForceRun);
+    TN_DEBUG4( "CThumbAGProcessor::ActivateAO() iModify = %d, iQueryReady = %d, iProcessingCount = %d", iModify, iQueryReady, iProcessingCount);
 #endif
     
     if(iFormatting)
@@ -1133,16 +1313,12 @@
         
     if( !IsActive() )
         {
-#ifdef _DEBUG
-        if( iForceRun )
-            {
-            TN_DEBUG1( "CThumbAGProcessor::ActivateAO() - *** FORCED RUN ***");
-            }
-#endif
         SetActive();
         TRequestStatus* statusPtr = &iStatus;
         User::RequestComplete( statusPtr, KErrNone );
         }
+
+    UpdatePSValues();
     }
 
 // ---------------------------------------------------------------------------
@@ -1223,7 +1399,11 @@
 // CThumbAGProcessor::RemoveFromQueues()
 // ---------------------------------------------------------------------------
 //
+#ifdef _DEBUG
 void CThumbAGProcessor::RemoveFromQueues( const RArray<TItemId>& aIDArray, const TBool aRemoveFromDelete )
+#else
+void CThumbAGProcessor::RemoveFromQueues( const RArray<TItemId>& aIDArray, const TBool /*aRemoveFromDelete*/ )
+#endif
     {
     TN_DEBUG2( "CThumbAGProcessor::RemoveFromQueues() aRemoveFromDelete == %d - begin", aRemoveFromDelete );
     
@@ -1232,7 +1412,7 @@
     for (int i=0; i< aIDArray.Count(); i++)
         {
         TN_DEBUG2( "CThumbAGProcessor::RemoveFromQueues() - %d", aIDArray[i]);
-        
+
         itemIndex = iPlaceholderQueue.Find( aIDArray[i] );
                          
         if(itemIndex >= 0)
@@ -1247,7 +1427,14 @@
             {
             iAddQueue.Remove(itemIndex);
             TN_DEBUG1( "CThumbAGProcessor::RemoveFromQueues() - iAddQueue" );
-            continue;
+            }
+
+        itemIndex = i2ndRoundGenerateQueue.Find( aIDArray[i] );
+                
+        if(itemIndex >= 0)
+            {
+            i2ndRoundGenerateQueue.Remove(itemIndex);
+            TN_DEBUG1( "CThumbAGProcessor::RemoveFromQueues() - i2ndRoundGenerateQueue" );
             }
         
         itemIndex = iModifyQueue.Find( aIDArray[i] );
@@ -1259,13 +1446,13 @@
 			 
             if( iModifyQueue.Count() == 0)
 			    {
-			    iForceRun = EFalse;
+			    SetForceRun( EFalse );
 		        }
 			 
             continue;
             }
     
-        if( aRemoveFromDelete )
+        /*if( aRemoveFromDelete )
             {
             itemIndex = iRemoveQueue.Find( aIDArray[i] );
              
@@ -1275,7 +1462,7 @@
                 TN_DEBUG1( "CThumbAGProcessor::RemoveFromQueues() - iRemoveQueue" );
                 continue;
                 }
-            }
+            }*/
         }
     
     TN_DEBUG1( "CThumbAGProcessor::RemoveFromQueues() - end" );
@@ -1304,13 +1491,16 @@
     {
     TN_DEBUG1( "CThumbAGProcessor::QueryAllItemsL" );
     
-    CMdEObjectQuery::TState state(CMdEObjectQuery::EStateFirst);
+    __ASSERT_DEBUG((iMdESession), User::Panic(_L("CThumbAGProcessor::QueryAllItemsL() !iMdeSession "), KErrBadHandle));
+    
+    if(!iMdESession)
+         {
+         return;
+         }
     
     if( iQueryAllItems )
         {
-        state = iQueryAllItems->State();
-    
-        if(state == CMdEObjectQuery::EStateSearching )
+        if( !iQueryAllItems->IsComplete() )
             {
             TN_DEBUG1( "CThumbAGProcessor::QueryAllItemsL active- skip" );
             return;
@@ -1392,6 +1582,17 @@
                 default:
                     break;
                 }
+            
+            //signal Server's stores about MPX harvesting state
+            if( iMPXHarvesting )
+                {
+                RProperty::Set(KTAGDPSNotification, KMPXHarvesting, ETrue);
+                }
+            else
+                {
+                RProperty::Set(KTAGDPSNotification, KMPXHarvesting, EFalse);
+                }
+                
             TN_DEBUG3( "CThumbAGProcessor::HandleCollectionMessage -- end() iHarvesting == %d, iMPXHarvesting == %d", iHarvesting, iMPXHarvesting);
             }
         }
@@ -1430,71 +1631,29 @@
     {
     // not needed here
     }
-	
+
 // -----------------------------------------------------------------------------
-// LightStatusChanged()
+// ActivityChanged()
 // -----------------------------------------------------------------------------
 //
-void CThumbAGProcessor::LightStatusChanged(TInt aTarget, CHWRMLight::TLightStatus aStatus)
+void CThumbAGProcessor::ActivityChanged(const TBool aActive)
     {
-    TN_DEBUG3( "void CThumbAGProcessor::LightStatusChanged() aTarget == %d, aStatus == %d", aTarget, aStatus);
-    
-     if( aStatus == CHWRMLight::ELightOff)
+    TN_DEBUG2( "void CThumbAGProcessor::ActivityChanged() aActive == %d", aActive);
+    if(aActive)
         {
-        TN_DEBUG1( "void CThumbAGProcessor::LightStatusChanged() -- OFF");
-        iLights = EFalse;
-		
-        if(iAddQueue.Count() + iModifyQueue.Count() + iRemoveQueue.Count() > 0 )
+        iIdle = EFalse;
+        }
+    else
+        {
+        iIdle = ETrue; 
+        
+        if(iAddQueue.Count() + iModifyQueue.Count() + iRemoveQueue.Count() + i2ndRoundGenerateQueue.Count() > 0 )
             {
             ActivateAO();
             }
         }
-    else
-        {
-        TN_DEBUG1( "void CThumbAGProcessor::LightStatusChanged() -- ON");
-        iLights = ETrue;
-        }
     }
 
-// -----------------------------------------------------------------------------
-// IsInactive()
-// -----------------------------------------------------------------------------
-//
-TBool CThumbAGProcessor::IsInactive()
-    {
-#ifdef _DEBUG
-TN_DEBUG2( "CThumbAGProcessor::IsInactive()= %d", User::InactivityTime().Int());
-#endif
-
-    if( User::InactivityTime() < TTimeIntervalSeconds(KBackgroundGenerationIdle) )
-      {
-      return EFalse;
-      }
-    return ETrue;
-    }
-
-// -----------------------------------------------------------------------------
-// ActivityDetected()
-// -----------------------------------------------------------------------------
-//
-void CThumbAGProcessor::ActivityDetected()
-    {
-    iIdle = EFalse;
-    }
-
-// -----------------------------------------------------------------------------
-// InactivityDetected()
-// -----------------------------------------------------------------------------
-//
-void CThumbAGProcessor::InactivityDetected()
-    {
-    iIdle = ETrue; 
-    
-    if(iAddQueue.Count() + iModifyQueue.Count() + iRemoveQueue.Count() > 0 )
-        {
-        ActivateAO();
-        }
-    }
 
 // ---------------------------------------------------------------------------
 // CThumbAGProcessor::FormatNotification
@@ -1512,5 +1671,68 @@
         }
     }
 
+// ---------------------------------------------------------------------------
+// CThumbAGProcessor::RPropertyNotification
+// Handles a RProperty changed operation
+// ---------------------------------------------------------------------------
+//
+void CThumbAGProcessor::RPropertyNotification(const TInt aError, const TUid aKeyCategory, const TUint aPropertyKey, const TInt aValue)
+    {
+    TN_DEBUG5( "CThumbAGProcessor::RPropertyNotification() aError = %d, aPropertyKey = %d, aKeyCategory = %d, aValue = %d", aError, aPropertyKey, aKeyCategory, aValue );
+    
+    if(aPropertyKey == KForceBackgroundGeneration && aKeyCategory == KTAGDPSNotification )
+        {
+        if( aValue == 1 && aError == KErrNone )
+            {
+            iForegroundRun = ETrue;
+            ActivateAO();
+            }
+        else
+            {
+            iForegroundRun = EFalse;
+            }
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// CThumbAGProcessor::UpdateItemsLeft
+// Update KItemsleft PS value if changed
+// ---------------------------------------------------------------------------
+//
+void CThumbAGProcessor::UpdatePSValues(const TBool aDefine)
+    {
+    TInt itemsLeft = iModifyQueue.Count() + iAddQueue.Count();
+    TBool daemonProcessing = EFalse;
+    
+    if(itemsLeft + i2ndRoundGenerateQueue.Count() + iRemoveQueue.Count() > 0 )
+        {
+        daemonProcessing = ETrue;
+        }
+    
+    if(aDefine)
+        {
+        TN_DEBUG1( "CThumbAGProcessor::UpdatePSValues() define");
+        RProperty::Define(KTAGDPSNotification, KDaemonProcessing, RProperty::EInt);
+        RProperty::Set(KTAGDPSNotification, KDaemonProcessing, 0);
+        daemonProcessing = EFalse;
+        RProperty::Define(KTAGDPSNotification, KItemsleft, RProperty::EInt);
+        RProperty::Set(KTAGDPSNotification, KItemsleft, 0);
+        iPreviousItemsLeft = 0;
+        }
+    
+    if( daemonProcessing != iPreviousDaemonProcessing)
+        {
+        TN_DEBUG2( "CThumbAGProcessor::UpdatePSValues() update KDaemonProcessing == %d", daemonProcessing);
+        iPreviousDaemonProcessing = daemonProcessing;
+        RProperty::Set(KTAGDPSNotification, KDaemonProcessing, daemonProcessing);
+        }
+    
+    if( itemsLeft != iPreviousItemsLeft)
+        {
+        TN_DEBUG2( "CThumbAGProcessor::UpdatePSValues() update KItemsleft == %d", itemsLeft);
+        iPreviousItemsLeft = itemsLeft;
+        RProperty::Set(KTAGDPSNotification, KItemsleft, itemsLeft );
+        }
+    }
 
 // End of file
--- a/imagehandlingutilities/thumbnailmanager/thumbnailclient/inc/thumbnailsession.h	Fri Feb 19 23:07:36 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailclient/inc/thumbnailsession.h	Fri Mar 12 15:43:57 2010 +0200
@@ -155,15 +155,6 @@
     TInt ChangePriority( TThumbnailRequestId aRequestId, TInt aNewPriority );
 
     /**
-     * Create thumbnails.
-     *
-     * @since S60 v5.0
-     * @param aPath Path to media object whose thumbnails should be created.
-     * @return Error code.
-     */
-    TInt CreateThumbnails( const RFile64& aFile, TDisplayMode aDisplayMode );
-
-    /**
      * Delete thumbnails.
      *
      * @since S60 v5.0
--- a/imagehandlingutilities/thumbnailmanager/thumbnailclient/src/thumbnailrequestactive.cpp	Fri Feb 19 23:07:36 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailclient/src/thumbnailrequestactive.cpp	Fri Mar 12 15:43:57 2010 +0200
@@ -205,7 +205,7 @@
 //
 void CThumbnailRequestActive::RunL()
     {
-    TN_DEBUG2( "CThumbnaiRequestActive::RunL() - request ID: %d", iParams.iRequestId );
+    TN_DEBUG2( "CThumbnailRequestActive::RunL() - request ID: %d", iParams.iRequestId );
     
     if ( iParams.iControlFlags == EThumbnailPreviewThumbnail )
         {
@@ -234,13 +234,17 @@
     else if ( iStatus.Int() == KThumbnailErrThumbnailNotFound && iParams.iFileName.Length() && 
          !( iParams.iFlags& CThumbnailManager::EDoNotCreate ))
         {
-        TN_DEBUG1( "CThumbnaiRequestActive::RunL() - no thumbnail found - lets try with file handle" );
+        TN_DEBUG2( "CThumbnaiRequestActive::RunL() - no thumbnail found - lets try with file handle %S", &iParams.iFileName );
         iRequestCompleted = EFalse;
         
         // We tried to get thumbnail using file path, but it was not found in
         // the database. We need to open the file now (on the client side) and
         // use file handle.
-        User::LeaveIfError( iFile.Open( iFs, iParams.iFileName, EFileShareReadersOrWriters ));
+        
+        TInt err = iFile.Open( iFs, iParams.iFileName, EFileShareReadersOrWriters );
+        TN_DEBUG2( "CThumbnaiRequestActive::RunL() - file handle open err = %d", err );
+        User::LeaveIfError( err );
+        
         CleanupClosePushL( iFile );
         
         TN_DEBUG2( "CThumbnaiRequestActive::RunL() - file handle opened for %S", &iParams.iFileName );
@@ -254,14 +258,15 @@
         }
     else if ( iStatus.Int())
         {
-        TN_DEBUG2( "CThumbnaiRequestActive::RunL() - error (%d) occured", iStatus.Int() );
+        TN_DEBUG2( "CThumbnailRequestActive::RunL() - error (%d) occured", iStatus.Int() );
         // An error occurred
         iError = iStatus.Int();
         HandleError();
         }
-    else if (iParams.iControlFlags == EThumbnailGeneratePersistentSizesOnly)
+    //1st round thumb ready from exif (stored)
+    else if (iParams.iOriginalControlFlags == EThumbnailGeneratePersistentSizesOnly && !iProcessingPreview)
 	    {
-	    TN_DEBUG1( "CThumbnaiRequestActive::RunL()- generate persistent sizes" );
+	    TN_DEBUG1( "CThumbnaiRequestActive::RunL()- generate persistent sizes thumbnailready" );
 	    iBitmapHandle = iParams.iBitmapHandle;
 	    
 	    TN_DEBUG2( "CThumbnaiRequestActive::RunL() - iObserver.ThumbnailReady %d", iParams.iRequestId );
@@ -270,43 +275,84 @@
 	    ReleaseServerBitmap();
 	    iRequestQueue->RequestComplete(this);
 	    
-#ifdef _DEBUG
-    TTime stop;
-    stop.UniversalTime();
-    TN_DEBUG3( "CThumbnailRequestActive::RunL() total execution time %d, %d ms",
-               iParams.iRequestId, (TInt)stop.MicroSecondsFrom(iStartExecTime).Int64()/1000 );
-#endif
+        #ifdef _DEBUG
+            TTime stop;
+            stop.UniversalTime();
+            TN_DEBUG3( "CThumbnailRequestActive::RunL() total execution time %d, %d ms",
+                       iParams.iRequestId, (TInt)stop.MicroSecondsFrom(iStartExecTime).Int64()/1000 );
+        #endif
 	    }
+    //1st round preview ready from too low quality exif/exif not found (not-stored)
+    //relauch using normal decoding
+    else if (iParams.iOriginalControlFlags == EThumbnailGeneratePersistentSizesOnly && iProcessingPreview)
+        {
+        TN_DEBUG1( "CThumbnaiRequestActive::RunL()- generate persistent sizes thumbnailpreviewready" );
+        iBitmapHandle = iParams.iBitmapHandle;
+        
+        TN_DEBUG2( "CThumbnaiRequestActive::RunL() - iObserver.ThumbnailPreviewReady %d", iParams.iRequestId );
+        iObserver.ThumbnailPreviewReady( *iCallbackThumbnail, iParams.iRequestId );
+        
+        iProcessingPreview = EFalse;
+      
+        ReleaseServerBitmap();
+        
+        //set flags so that EThumbnailGeneratePersistentSizesOnly is done aka check all missing sizes 
+        iParams.iQualityPreference = CThumbnailManager::EOptimizeForQuality;
+        iParams.iControlFlags = EThumbnailGeneratePersistentSizesOnly;
+        iRequestType = EReqUpdateThumbnails;
+        
+        //increase priority
+        this->SetPriority(this->Priority() + 1);
+        iParams.iPriority++;
+        
+        iSession.UpdateThumbnails( iPath, iOrientation, iModified, iParamsPckg, iStatus );
+        
+        SetActive();
+           
+    	#ifdef _DEBUG
+        TTime stop;
+        stop.UniversalTime();
+        TN_DEBUG3( "CThumbnailRequestActive::RunL() total execution time %d, %d ms",
+                   iParams.iRequestId, (TInt)stop.MicroSecondsFrom(iStartExecTime).Int64()/1000 );
+    	#endif
+        }
     else
         {
-        TN_DEBUG1( "CThumbnaiRequestActive::RunL() - succesful" );
+        TN_DEBUG1( "CThumbnailRequestActive::RunL() - succesful" );
         
         // Success
         iBitmapHandle = iParams.iBitmapHandle;
-        CFbsBitmap* bitmap = new( ELeave )CFbsBitmap();
-        CleanupStack::PushL( bitmap );
-        User::LeaveIfError( bitmap->Duplicate( iBitmapHandle ));
-        CleanupStack::Pop( bitmap );
-		
-		// reduce bpp value (displaymode to match reqested bits per pixel)
-		#ifdef _DEBUG
-        TN_DEBUG2( "CThumbnaiRequestActive::RunL() - displaymode is %d", bitmap->DisplayMode());
-		#endif
         
-        if( bitmap->DisplayMode() > iParams.iDisplayMode )
+        if( iBitmapHandle )
             {
-            bitmap->SetDisplayMode( iParams.iDisplayMode );
-			#ifdef _DEBUG
-            TN_DEBUG2( "CThumbnaiRequestActive::RunL() - displaymode is now %d", bitmap->DisplayMode());
-			#endif
+            CFbsBitmap* bitmap = new( ELeave )CFbsBitmap();
+            CleanupStack::PushL( bitmap );
+            User::LeaveIfError( bitmap->Duplicate( iBitmapHandle ));
+            CleanupStack::Pop( bitmap );
+            
+            // reduce bpp value (displaymode to match reqested bits per pixel)
+            #ifdef _DEBUG
+            TN_DEBUG2( "CThumbnailRequestActive::RunL() - displaymode is %d", bitmap->DisplayMode());
+            #endif
+            
+            if( bitmap->DisplayMode() > iParams.iDisplayMode )
+                {
+                bitmap->SetDisplayMode( iParams.iDisplayMode );
+                #ifdef _DEBUG
+                TN_DEBUG2( "CThumbnailRequestActive::RunL() - displaymode is now %d", bitmap->DisplayMode());
+                #endif
+                }
+            
+            iCallbackThumbnail->Set( bitmap, iClientData );
+            bitmap = NULL; // Owned by iCallbackThumbnail or client now
             }
-        
-        iCallbackThumbnail->Set( bitmap, iClientData );
-        bitmap = NULL; // Owned by iCallbackThumbnail or client now
 
         if ( iProcessingPreview )
             {
-            TN_DEBUG2( "CThumbnaiRequestActive::RunL() - iObserver.ThumbnailPreviewReady %d", iParams.iRequestId );
+            TN_DEBUG2( "CThumbnailRequestActive::RunL() - iObserver.ThumbnailPreviewReady %d", iParams.iRequestId );
+			//increase priority of 2nd round (both, AO and request itself)
+            this->SetPriority(this->Priority() + 1);
+            iParams.iPriority++;
             iObserver.ThumbnailPreviewReady( *iCallbackThumbnail, iParams.iRequestId );
             iProcessingPreview = EFalse;
             ReleaseServerBitmap();
@@ -314,7 +360,7 @@
             }
         else
             {
-            TN_DEBUG2( "CThumbnaiRequestActive::RunL() - iObserver.ThumbnailReady %d", iParams.iRequestId );
+            TN_DEBUG2( "CThumbnailRequestActive::RunL() - iObserver.ThumbnailReady %d", iParams.iRequestId );
             
             iObserver.ThumbnailReady( iStatus.Int(), * iCallbackThumbnail, iParams.iRequestId );
             ReleaseServerBitmap();    
@@ -465,6 +511,7 @@
     iParams.iControlFlags = (aGeneratePersistentSizesOnly ?
     						EThumbnailGeneratePersistentSizesOnly :
     						EThumbnailNoControlFlags);    
+    iParams.iOriginalControlFlags = iParams.iControlFlags;
     iParams.iBitmapHandle = 0;
     iParams.iSize = aSize;
     iParams.iDisplayMode = aDisplayMode;
@@ -498,7 +545,8 @@
     iClientData = aClientData;
     iParams.iControlFlags = (aGeneratePersistentSizesOnly ?
                             EThumbnailGeneratePersistentSizesOnly :
-                            EThumbnailNoControlFlags);    
+                            EThumbnailNoControlFlags);
+    iParams.iOriginalControlFlags = iParams.iControlFlags;
     iParams.iBitmapHandle = 0;
     iParams.iSize = aSize;
     iParams.iDisplayMode = aDisplayMode;
@@ -531,7 +579,7 @@
     iParams.iControlFlags = (aGeneratePersistentSizesOnly ?
     						EThumbnailGeneratePersistentSizesOnly :
     						EThumbnailNoControlFlags);
-    						
+    iParams.iOriginalControlFlags = iParams.iControlFlags;
     iParams.iBitmapHandle = 0;
     iParams.iSize = aSize;
     iParams.iDisplayMode = aDisplayMode;
@@ -563,7 +611,7 @@
     iParams.iControlFlags = (aGeneratePersistentSizesOnly ?
                             EThumbnailGeneratePersistentSizesOnly :
                             EThumbnailNoControlFlags);
-                           
+    iParams.iOriginalControlFlags = iParams.iControlFlags;  
     iParams.iMimeType = TDataType( aMimeType );
     iParams.iBitmapHandle = 0;
     iParams.iSize = aSize;
@@ -594,7 +642,7 @@
     iParams.iControlFlags = (aGeneratePersistentSizesOnly ?
                             EThumbnailGeneratePersistentSizesOnly :
                             EThumbnailNoControlFlags);
-                           
+    iParams.iOriginalControlFlags = iParams.iControlFlags;  
     iParams.iBitmapHandle = 0;
     iParams.iSize = aSize;
     iParams.iThumbnailSize = aThumbnailSize;
@@ -645,6 +693,7 @@
     iRequestType = EReqUpdateThumbnails;
     
     iParams.iControlFlags = EThumbnailGeneratePersistentSizesOnly;   
+    iParams.iOriginalControlFlags = iParams.iControlFlags;
     iParams.iBitmapHandle = 0;
     iParams.iDisplayMode = aDisplayMode;
     iParams.iRequestId = iRequestId;
@@ -731,8 +780,11 @@
     iStartError = aErr;
     iRequestActive = ETrue;
     
-    iTimer->Start( KClientRequestStartErrorTimeout, KClientRequestStartErrorTimeout, 
-                   TCallBack(TimerCallBack, this));
+    if (!iTimer->IsActive())
+        {
+        iTimer->Start( KClientRequestStartErrorTimeout, KClientRequestStartErrorTimeout, 
+                       TCallBack(TimerCallBack, this));
+        }
     }
 
 // ---------------------------------------------------------------------------
--- a/imagehandlingutilities/thumbnailmanager/thumbnailclient/src/thumbnailsession.cpp	Fri Feb 19 23:07:36 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailclient/src/thumbnailsession.cpp	Fri Mar 12 15:43:57 2010 +0200
@@ -277,23 +277,6 @@
 // Delete thumbnails for given object file
 // ---------------------------------------------------------------------------
 //
-TInt RThumbnailSession::CreateThumbnails( const RFile64& aFile, TDisplayMode aDisplayMode )
-    {
-    TIpcArgs args( aDisplayMode ); // 1st argument
-    TInt err = aFile.TransferToServer( args, 1, 2 ); // 2.&3. argument
-    err = Send( ECreateThumbnails, args );
-    while ( err == KErrServerBusy )
-        {
-        err = Send( ECreateThumbnails, args );
-        }
-    return err;
-    }
-
-
-// ---------------------------------------------------------------------------
-// Delete thumbnails for given object file
-// ---------------------------------------------------------------------------
-//
 void RThumbnailSession::DeleteThumbnails( const TDesC& aPath,
         TThumbnailRequestParamsPckg& aParams, TRequestStatus& aStatus )
     {
--- a/imagehandlingutilities/thumbnailmanager/thumbnailserver/group/thumbnailserver.mmp	Fri Feb 19 23:07:36 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/group/thumbnailserver.mmp	Fri Mar 12 15:43:57 2010 +0200
@@ -49,15 +49,17 @@
 SOURCE                  thumbnaildiskunmountobserver.cpp
 SOURCE                  thumbnailcenrep.cpp 
 SOURCE                  thumbnailmemorycardobserver.cpp 
-SOURCE 			        thumbnaildecodetask.cpp
+SOURCE		        thumbnaildecodetask.cpp
 #ifdef RD_MDS_2_5
-SOURCE					thumbnailmdsquerytask.cpp
+SOURCE			thumbnailmdsquerytask.cpp
 #endif // RD_MDS_2_5
-SOURCE					tmgetimei.cpp 
+SOURCE			tmgetimei.cpp 
 
-SOURCEPATH 				../../tmcommon/src
-SOURCE					tmshutdownobserver.cpp
-SOURCE					tmformatobserver.cpp
+SOURCEPATH		../../tmcommon/src
+SOURCE			tmshutdownobserver.cpp
+SOURCE			tmformatobserver.cpp
+SOURCE			tmactivitymanager.cpp
+
 
 // Default system include paths for middleware layer modules.
 MW_LAYER_SYSTEMINCLUDE
@@ -77,16 +79,17 @@
 LIBRARY                 ihl.lib
 LIBRARY                 centralrepository.lib
 LIBRARY                 platformenv.lib
-LIBRARY					imageconversion.lib 
-LIBRARY         		caf.lib
-LIBRARY         		cafutils.lib
-LIBRARY         		mdeclient.lib
-LIBRARY					etel3rdparty.lib
-LIBRARY					bafl.lib
-LIBRARY					bitgdi.lib
+LIBRARY			imageconversion.lib 
+LIBRARY       		caf.lib
+LIBRARY         	cafutils.lib
+LIBRARY         	mdeclient.lib
+LIBRARY			etel3rdparty.lib
+LIBRARY			bafl.lib
+LIBRARY			bitgdi.lib
+LIBRARY 		hwrmlightclient.lib
 
 DEBUGLIBRARY            flogger.lib
 
 PAGED
 BYTEPAIRCOMPRESSTARGET
-EPOCPROCESSPRIORITY foreground
+EPOCPROCESSPRIORITY background
--- a/imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/thumbnailcenrep.h	Fri Feb 19 23:07:36 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/thumbnailcenrep.h	Fri Mar 12 15:43:57 2010 +0200
@@ -142,8 +142,8 @@
     };
     
 public:
-    enum { EUnknownSourceType, EImage, EVideo, EAudio };
-    enum { EUnknownSizeType, EGrid, EList, EFullscreen }; 
+    enum TThumbnailSourceType { EUnknownSourceType, EImage, EVideo, EAudio };
+    enum TThumbnailSizeType { EUnknownSizeType, EGrid, EList, EFullscreen }; 
     
 public:
     
@@ -160,21 +160,19 @@
                               aMode, TInt aFormat );
     
     TThumbnailPersistentSize( TThumbnailSize aType, const TSize& aSize, TBool aCrop, TDisplayMode
-                              aMode, TInt aFormat, TBool aAutoCreate );
+                              aMode, TInt aFormat, TBool aAutoCreate, TThumbnailSizeType aSizeType  );
     
 public:
     
     // data
     TThumbnailSize iType;
-    TInt iSourceType;
-    TInt iSizeType;
-    
+    TThumbnailSourceType iSourceType;
     TSize iSize;
     TBool iCrop;
     TDisplayMode iMode;
     TInt iFormat;
-    
     TBool iAutoCreate;
+    TThumbnailSizeType iSizeType;
 };
 
 /**
--- a/imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/thumbnailgeneratetask.h	Fri Feb 19 23:07:36 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/thumbnailgeneratetask.h	Fri Mar 12 15:43:57 2010 +0200
@@ -55,7 +55,7 @@
             CThumbnailManager::TThumbnailFlags aFlags, const TSize& aSize,
             TDisplayMode aDisplayMode, TInt aPriority,
             RArray < TThumbnailPersistentSize >* aMissingSizes, const TDesC& aTargetUri,
-            TThumbnailSize aThumbnailSize, const TThumbnailId aThumbnailId,
+            TThumbnailSize aThumbnailSize, const TInt64 aModified,
             const CThumbnailManager::TThumbnailQualityPreference aQualityPreference );
 
     /**
@@ -135,6 +135,13 @@
      */
     void CreateBlackListedL( const TSize& aOriginalSize );
     
+    
+    /**
+     * Check is blacklisting needed
+     *
+     * @param aErrorCode verdict is based on this error code
+     * @param aOriginalSize Original size of bitmap.
+     */
     void DoBlacklisting( const TInt aError, const TSize& aOriginalSize );
 
 private:
@@ -194,6 +201,10 @@
      */
     TThumbnailSize iThumbnailSize;    
     
+	 /**
+     * timestamp
+     */
+    TInt64 iModified;
 
     /**
      * Size of the original image.
@@ -214,8 +225,6 @@
      */
     CThumbnailProvider* iProvider;
     
-    TThumbnailId iThumbnailId;
-    
     TBool iScaledBitmapToPool;
     
 #ifdef _DEBUG
--- a/imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/thumbnailmdsquerytask.h	Fri Feb 19 23:07:36 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/thumbnailmdsquerytask.h	Fri Mar 12 15:43:57 2010 +0200
@@ -82,15 +82,7 @@
      * @since S60 v5.0
      * @param aId ID
      */
-    void QueryPathByIdL(TThumbnailId aId);
-    
-    /**
-     * Query Id by path
-     *
-     * @since S60 v5.0
-     * @param aUri the Path
-     */
-    void QueryIdByPathL(const TDesC& aUri);
+    void QueryPathByIdL(TThumbnailId aId, TBool aDelete);
     
     /**
      * Sets are values updated to db automatically
@@ -136,6 +128,8 @@
      TBool iUpdateToDb;
      
      TFileName iUri;
+     
+     TBool iDelete;
 };
 
 #endif // THUMBNAILMDSQUERYTASK_H
--- a/imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/thumbnailscaletask.h	Fri Feb 19 23:07:36 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/thumbnailscaletask.h	Fri Mar 12 15:43:57 2010 +0200
@@ -56,7 +56,7 @@
         CThumbnailServer& aServer, const TDesC& aFilename, CFbsBitmap* aBitmap,
         const TSize& aOriginalSize, const TSize& aTargetSize, TBool aCrop,
         TDisplayMode aDisplayMode, TInt aPriority, const TDesC& aTargetUri,
-        const TThumbnailSize aThumbnailSize, const TThumbnailId aThumbnailId,
+        const TThumbnailSize aThumbnailSize, const TInt64 aModified,
         const TBool aBitmapToPool, const TBool aEXIF);
 
     /**
@@ -126,7 +126,7 @@
         aServer, const TDesC& aFilename, CFbsBitmap* aBitmap, const TSize&
         aOriginalSize, const TSize& aTargetSize, TBool aCrop, TDisplayMode
         aDisplayMode, TInt aPriority, const TDesC& aTargetUri,
-        const TThumbnailSize aThumbnailSize, const TThumbnailId aThumbnailId,
+        const TThumbnailSize aThumbnailSize, const TInt64 aModified,
         const TBool aBitmapToPool, const TBool aEXIF);
 
     /**
@@ -195,9 +195,14 @@
     TSize iOriginalSize;
 
     /**
+     * Target size of scaled thubnail (not real of preview)
+     */
+    TSize iTargetSize;
+    
+    /**
      * Target size of the thumbnail.
      */
-    TSize iTargetSize;
+    TSize iTargetSizeTN;
 
     /**
      * Incidates if cropping is enabled.
@@ -252,9 +257,9 @@
     TThumbnailSize iThumbnailSize;
     
 	 /**
-     * MDS ID of requested Thumbnail
+     * timestamp
      */
-    TThumbnailId iThumbnailId;
+    TInt64 iModified;
     
 	/**
      * Add bitmap to server's pool.
--- a/imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/thumbnailserver.h	Fri Feb 19 23:07:36 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/thumbnailserver.h	Fri Mar 12 15:43:57 2010 +0200
@@ -167,7 +167,8 @@
      */
     void StoreThumbnailL( const TDesC& aPath, CFbsBitmap* aBitmap, const TSize&
         aOriginalSize, const TBool aCropped, const TThumbnailSize aThumbnailSize,
-        const TThumbnailId aThumbnailId, const TBool aThumbFromPath = ETrue,
+        const TInt64 aModified,
+        const TBool aThumbFromPath = ETrue,
         const TBool aCheckExist = ETrue);
 
     /**
@@ -189,18 +190,6 @@
              TDesC8* & aData, const TThumbnailSize aThumbnailSize, TSize &aOriginalSize );
     
     /**
-     * Fetch thumbnail image.
-     *
-     * @since S60 v5.0
-     * @param aThumbnailId ID of the media object whose thumbnail is to be
-     *              retrieved.
-     * @param aThumbnail Pointer to get the fetched thumbnail bitmap.
-     *                   Caller assumes ownership.
-     */    
-    void FetchThumbnailL( TThumbnailId aThumbnailId, CFbsBitmap* &
-        aThumbnail, TDesC8* & aData, TThumbnailSize aThumbnailSize, TSize &aOriginalSize );
-
-    /**
      * Delete thumbnails.
      *
      * @since S60 v5.0
@@ -325,9 +314,10 @@
      * @since S60 v5.0
      * @param aPath Path associated to missing thumbnails
      * @param aMissingSizes Returns a list of thumbnail sizes not yet create related to the path
+	 * @param aCheckGridSizeOnly check only is Grid size missing
      */
-    void GetMissingSizesAndIDsL( const TDesC& aPath, TInt aSourceType, RArray <
-        TThumbnailPersistentSize > & aMissingSizes, TBool& aMissingIDs);
+    void GetMissingSizesL( const TDesC& aPath, TInt aSourceType, RArray <
+        TThumbnailPersistentSize > & aMissingSizes, TBool aCheckGridSizeOnly);
 
     /**
      * Fileserver
@@ -375,13 +365,12 @@
      * Update thumbnails in database
      *
      * @since S60 v5.0
-     * @param aItemId       TThumbnailId
      * @param aPath         (New) path for the Thumbnail
      * @param aOrientation  Thumbnail orientation
      * @param aModified     Last modified
      * @param TBool         EFalse, if new thumbs need to be created
      */  
-    TBool UpdateThumbnailsL( const TThumbnailId aItemId, const TDesC& aPath,
+    TBool UpdateThumbnailsL( const TDesC& aPath,
                              const TInt aOrientation, const TInt64 aModified );
     
     /** 
@@ -439,15 +428,6 @@
     CThumbnailStore* StoreForPathL( const TDesC& aPath );  
     
     /**
-     * Update ID in database
-     *
-     * @since S60 v5.0
-     * @param aItemId Id of item whose thumbnails are to be updated.
-     * @param aNewPath Path property of the object to be updated.
-     */  
-    void UpdateIDL( const TDesC& aPath, const TThumbnailId aNewId );
-    
-    /**
      * Close Removable Stores
      *
      * @since S60 v5.0
@@ -531,7 +511,12 @@
      */
     void OpenStoresL();
     
- 
+    /**
+     * Callback for reconnect timer
+     *
+     * @since S60 v5.0
+     */
+    static TInt ReconnectCallBack(TAny* aAny);
 
 private:
 
@@ -683,6 +668,9 @@
     
     TBool iFormatting;
     
+    // reconnect timer
+    CPeriodic* iReconnect;
+    
 #ifdef _DEBUG
     TUint32 iPlaceholderCounter;
 #endif
--- a/imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/thumbnailserversession.h	Fri Feb 19 23:07:36 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/thumbnailserversession.h	Fri Mar 12 15:43:57 2010 +0200
@@ -212,14 +212,6 @@
     TInt ChangePriority( const RMessage2& aMessage );
 
     /**
-     * Create thumbnails.
-     *
-     * @since S60 v5.0
-     * @param aMessage Message.
-     */
-    void CreateThumbnailsL( const RMessage2& aMessage );
-
-    /**
      * Delete thumbnails.
      *
      * @since S60 v5.0
--- a/imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/thumbnailsql.h	Fri Feb 19 23:07:36 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/thumbnailsql.h	Fri Mar 12 15:43:57 2010 +0200
@@ -53,10 +53,6 @@
 _LIT8( KThumbnailCreateInfoDataTable, "CREATE TABLE ThumbnailInfoData ("
         // If Thumbnail is stored in SQL then Data is NOT NULL
         "Data BLOB);");
-		
-//Create index for speedup DB searches 
-_LIT8( KThumbnailCreateInfoTableIndex1, "CREATE INDEX idx1 ON ThumbnailInfo(Path, Size);");
-_LIT8( KThumbnailCreateInfoTableIndex2, "CREATE INDEX idx2 ON ThumbnailInfo(TNId, Size);");
 
 //temp table is identical to actual main table except it's not persistent
 _LIT8( KThumbnailCreateTempInfoTable, "CREATE TEMP TABLE TempThumbnailInfo ("
@@ -85,6 +81,15 @@
         "Minor INTEGER,"
         "IMEI TEXT COLLATE NOCASE);");
 
+// deleted thumbs table
+_LIT8( KThumbnailDeletedTable, "CREATE TABLE ThumbnailDeleted ("
+        // Assosiacted object in file system
+        "Path TEXT UNIQUE COLLATE NOCASE);");
+
+//Create index for speedup DB searches 
+_LIT8( KThumbnailCreateInfoTableIndex1, "CREATE INDEX idx1 ON ThumbnailInfo(Path, Size);");
+_LIT8( KThumbnailCreateDeletedTableIndex, "CREATE INDEX idx4 ON ThumbnailDeleted(Path);");
+
 _LIT8( KThumbnailMoveFromTempInfoToMainTable, "INSERT INTO ThumbnailInfo SELECT * FROM TempThumbnailInfo;");
 _LIT8( KThumbnailMoveFromTempDataToMainTable, "INSERT INTO ThumbnailInfoData SELECT * FROM TempThumbnailInfoData;");
 
@@ -104,33 +109,26 @@
 _LIT8( KThumbnailRollbackTransaction, "ROLLBACK;" );
 
 _LIT8( KThumbnailInsertThumbnailInfoByPathAndId, "INSERT INTO TempThumbnailInfo "
-    "(Path,TNId,Size,Format,Width,Height,OrigWidth,OrigHeight,Flags,Orientation,ThumbFromPath,Modified) ""VALUES "
-    "(:Path,:TNId,:Size,:Format,:Width,:Height,:OrigWidth,:OrigHeight,:Flags,:Orient,:ThumbFromPath,:Modified);" );
+    "(Path,Size,Format,Width,Height,OrigWidth,OrigHeight,Flags,Orientation,ThumbFromPath,Modified) ""VALUES "
+    "(:Path,:Size,:Format,:Width,:Height,:OrigWidth,:OrigHeight,:Flags,:Orient,:ThumbFromPath,:Modified);" );
 
 _LIT8( KThumbnailInsertTempThumbnailInfoData, "INSERT INTO TempThumbnailInfoData (Data) VALUES (:Data);" );
 
-_LIT8( KThumbnailSelectSizeByPath, "SELECT Size, TNId FROM ThumbnailInfo WHERE Path = :Path ORDER BY Size DESC;" );
-
-_LIT8( KThumbnailSelectTempSizeByPath, "SELECT Size, TNId FROM TempThumbnailInfo WHERE Path = :Path ORDER BY Size DESC;" );
+_LIT8( KThumbnailSelectSizeByPath, "SELECT Size FROM ThumbnailInfo "
+        "WHERE NOT EXISTS (SELECT Path FROM ThumbnailDeleted "
+        "WHERE ThumbnailInfo.Path = ThumbnailDeleted.Path) "
+        "AND Path = :Path ORDER BY Size DESC;" );
 
-_LIT8( KThumbnailSelectById, "SELECT * "
-        "FROM ThumbnailInfo "
-        "JOIN ThumbnailInfoData "
-        "ON ThumbnailInfo.RowID = ThumbnailInfoData.RowID "
-        "WHERE TNId = :TNId" );
-
-_LIT8( KThumbnailSelectTempById, "SELECT * "
-        "FROM TempThumbnailInfo "
-        "JOIN TempThumbnailInfoData "
-        "ON TempThumbnailInfo.RowID = TempThumbnailInfoData.RowID "
-        "WHERE TNId = :TNId" );
+_LIT8( KThumbnailSelectTempSizeByPath, "SELECT Size FROM TempThumbnailInfo WHERE Path = :Path ORDER BY Size DESC;" );
 
 //query by Path
 _LIT8( KThumbnailSelectInfoByPath, "SELECT ThumbnailInfo.Format, ThumbnailInfoData.Data, ThumbnailInfo.Width, ThumbnailInfo.Height, ThumbnailInfo.Flags "
         "FROM ThumbnailInfo "
         "JOIN ThumbnailInfoData "
         "ON ThumbnailInfo.RowID = ThumbnailInfoData.RowID "
-        "WHERE ThumbnailInfo.Path = :Path AND ThumbnailInfo.Size = :Size;");
+        "WHERE NOT EXISTS (SELECT Path FROM ThumbnailDeleted "
+        "WHERE ThumbnailInfo.Path = ThumbnailDeleted.Path) " 
+        "AND ThumbnailInfo.Path = :Path AND ThumbnailInfo.Size = :Size;");
 
 _LIT8( KThumbnailSelectTempInfoByPath, "SELECT TempThumbnailInfo.Format, TempThumbnailInfoData.Data, TempThumbnailInfo.Width, TempThumbnailInfo.Height, TempThumbnailInfo.Flags "
         "FROM TempThumbnailInfo "
@@ -138,41 +136,9 @@
         "ON TempThumbnailInfo.RowID = TempThumbnailInfoData.RowID "
         "WHERE TempThumbnailInfo.Path = :Path AND TempThumbnailInfo.Size = :Size;");
 
-//query by Id
-_LIT8( KThumbnailSelectInfoById, "SELECT ThumbnailInfo.Format, ThumbnailInfoData.Data, ThumbnailInfo.Width, ThumbnailInfo.Height, ThumbnailInfo.Flags "
-        "FROM ThumbnailInfo "
-        "JOIN ThumbnailInfoData "
-        "ON ThumbnailInfo.RowID = ThumbnailInfoData.RowID "
-        "WHERE TNId = :TNId AND Size = :Size;" );
-
-_LIT8( KThumbnailSelectTempInfoById, "SELECT TempThumbnailInfo.Format, TempThumbnailInfoData.Data, TempThumbnailInfo.Width, TempThumbnailInfo.Height, TempThumbnailInfo.Flags "
-        "FROM TempThumbnailInfo "
-        "JOIN TempThumbnailInfoData "
-        "ON TempThumbnailInfo.RowID = TempThumbnailInfoData.RowID "
-        "WHERE TNId = :TNId AND Size = :Size;" );
-		
-//query by Idv2
-_LIT8( KThumbnailSelectInfoByIdv2, "SELECT ThumbnailInfo.Format, ThumbnailInfoData.Data, ThumbnailInfo.Width, ThumbnailInfo.Height, ThumbnailInfo.Flags "
-        "FROM ThumbnailInfo "
-        "JOIN ThumbnailInfoData "
-        "ON ThumbnailInfo.RowID = ThumbnailInfoData.RowID "
-        "WHERE TNId = :TNId AND (Size = :SizeImage OR Size = :SizeVideo OR Size = :SizeAudio);" );
-
-_LIT8( KThumbnailSelectTempInfoByIdv2, "SELECT TempThumbnailInfo.Format, TempThumbnailInfoData.Data, TempThumbnailInfo.Width, TempThumbnailInfo.Height, TempThumbnailInfo.Flags "
-        "FROM TempThumbnailInfo "
-        "JOIN TempThumbnailInfoData "
-        "ON TempThumbnailInfo.RowID = TempThumbnailInfoData.RowID "
-        "WHERE TNId = :TNId AND (Size = :SizeImage OR Size = :SizeVideo OR Size = :SizeAudio);" );		
 
 _LIT8( KThumbnailSelectSettings, "SELECT Version FROM ThumbnailSettings;" );
 
-//qyery Path by ID
-_LIT8( KThumbnailSelectPathByID, "SELECT Path FROM ThumbnailInfo WHERE TNId = :TNId;"  );
-_LIT8( KThumbnailSelectTempPathByID, "SELECT Path FROM TempThumbnailInfo WHERE TNId = :TNId;");
-
-//query Path and Modified by ID
-_LIT8( KThumbnailSelectPathModifiedByID, "SELECT Path, Modified FROM ThumbnailInfo WHERE TNId = :TNId;"  );
-_LIT8( KThumbnailSelectTempPathModifiedByID, "SELECT Path, Modified FROM TempThumbnailInfo WHERE TNId = :TNId;");
 
 _LIT( KThumbnailSqlParamData, ":Data" );
 _LIT( KThumbnailSqlParamFlags, ":Flags" );
@@ -182,7 +148,6 @@
 _LIT( KThumbnailSqlParamOriginalWidth, ":OrigWidth" );
 _LIT( KThumbnailSqlParamOriginalHeight, ":OrigHeight" );
 _LIT( KThumbnailSqlParamFormat, ":Format" );
-_LIT( KThumbnailSqlParamId, ":TNId" );
 _LIT( KThumbnailSqlParamSize, ":Size" );
 _LIT( KThumbnailSqlParamTNPath, ":TNPath" );
 _LIT( KThumbnailSqlParamMajor, ":Major" );
@@ -196,6 +161,7 @@
 _LIT( KThumbnailSqlParamThumbFromPath, ":ThumbFromPath" );
 _LIT( KThumbnailSqlParamModified, ":Modified" );
 _LIT( KThumbnailSqlParamFlag, ":Flag" );
+_LIT( KThumbnailSqlParamLimit, ":Limit" );
 
 //Delete by path
 _LIT8( KThumbnailSqlSelectRowIDInfoByPath, "SELECT ThumbnailInfo.RowID FROM ThumbnailInfo WHERE Path = :Path;" );
@@ -206,18 +172,20 @@
 _LIT8( KTempThumbnailSqlDeleteInfoDataByPath, "DELETE FROM TempThumbnailInfoData WHERE TempThumbnailInfoData.RowID = :RowID;" );
 
 
-//Delete by ID
-_LIT8( KThumbnailSqlSelectRowIDInfoByID, "SELECT ThumbnailInfo.RowID FROM ThumbnailInfo WHERE TNId = :TNId;" );
-_LIT8( KThumbnailSqlDeleteInfoByID, "DELETE FROM ThumbnailInfo WHERE ThumbnailInfo.RowID = :RowID;" );
-_LIT8( KThumbnailSqlDeleteInfoDataByID, "DELETE FROM ThumbnailInfoData WHERE ThumbnailInfoData.RowID = :RowID;" );
-_LIT8( KTempThumbnailSqlSelectRowIDInfoByID, "SELECT TempThumbnailInfo.RowID FROM TempThumbnailInfo WHERE TNId = :TNId LIMIT 1;" );
-_LIT8( KTempThumbnailSqlDeleteInfoByID, "DELETE FROM TempThumbnailInfo WHERE TempThumbnailInfo.RowID = :RowID;" );
-_LIT8( KTempThumbnailSqlDeleteInfoDataByID, "DELETE FROM TempThumbnailInfoData WHERE TempThumbnailInfoData.RowID = :RowID;" );
+// insert to deleted
+_LIT8( KThumbnailSqlInsertDeleted, "INSERT INTO ThumbnailDeleted (Path) VALUES (:Path);" );
+_LIT8 ( KThumbnailSqlFindDeleted, "SELECT * FROM ThumbnailDeleted WHERE Path = :Path;" );
 
+// delete marked
+_LIT8( KThumbnailSqlSelectMarked, "SELECT ThumbnailInfo.RowID FROM ThumbnailInfo "
+        "WHERE EXISTS (SELECT Path FROM ThumbnailDeleted "
+        "WHERE ThumbnailInfo.Path = ThumbnailDeleted.Path) LIMIT :Limit;" );
+_LIT8( KThumbnailSqlDeleteInfoByRowID, "DELETE FROM ThumbnailInfo WHERE ThumbnailInfo.RowID = :RowID;" );
+_LIT8( KThumbnailSqlDeleteInfoDataByRowID, "DELETE FROM ThumbnailInfoData WHERE ThumbnailInfoData.RowID = :RowID;" );
+_LIT8( KThumbnailSqlDeleteFromDeleted, "DELETE FROM ThumbnailDeleted "
+        "WHERE NOT EXISTS (SELECT Path FROM ThumbnailInfo "
+        "WHERE ThumbnailDeleted.Path = ThumbnailInfo.Path);" );
 
-//Update path by Id
-_LIT8( KTempThumbnailSqlUpdateById, "UPDATE TempThumbnailInfo SET Path = :Path WHERE TNId = :TNId" );
-_LIT8( KThumbnailSqlUpdateById, "UPDATE ThumbnailInfo SET Path = :Path WHERE TNId = :TNId" );
 
 //version commands
 _LIT8( KThumbnailInsertToVersion, "INSERT INTO ThumbnailVersion (IMEI, Minor, Major) VALUES (:IMEI, :Minor,:Major);" );
@@ -230,21 +198,13 @@
 //update IMEI
 _LIT8( KThumbnailUpdateIMEI, "UPDATE ThumbnailVersion SET IMEI = :IMEI" );
 
-//update ID by Path
-_LIT8( KTempThumbnailUpdateIdByPath, "UPDATE TempThumbnailInfo SET TNId = :TNId WHERE Path = :Path" );
-_LIT8( KThumbnailUpdateIdByPath, "UPDATE ThumbnailInfo SET TNId = :TNId WHERE Path = :Path" );
-
-//qyery Modification timestamp by ID
-_LIT8( KThumbnailSelectModifiedByID, "SELECT Modified FROM ThumbnailInfo WHERE TNId = :TNId AND ThumbFromPath = 1"  );
-_LIT8( KThumbnailSelectTempModifiedByID, "SELECT Modified FROM TempThumbnailInfo WHERE TNId = :TNId AND ThumbFromPath = 1");
-
 //query Modification timestamp by path
 _LIT8( KThumbnailSelectModifiedByPath, "SELECT Modified FROM ThumbnailInfo WHERE Path = :Path"  );
 _LIT8( KThumbnailSelectTempModifiedByPath, "SELECT Modified FROM TempThumbnailInfo WHERE Path = :Path");
 
 // query possible duplicates
-_LIT8 ( KTempFindDuplicate, "SELECT Path FROM TempThumbnailInfo WHERE Size = :Size AND (TNId = :TNId OR Path = :Path);" );
-_LIT8 ( KFindDuplicate, "SELECT Path FROM ThumbnailInfo WHERE Size = :Size AND (TNId = :TNId OR Path = :Path);" );
+_LIT8 ( KTempFindDuplicate, "SELECT Path FROM TempThumbnailInfo WHERE Path = :Path AND Size = :Size;" );
+_LIT8 ( KFindDuplicate, "SELECT Path FROM ThumbnailInfo WHERE Path = :Path AND Size = :Size;" );
 
 // check rowIDs
 _LIT8 ( KGetInfoRowID, "SELECT MAX (ThumbnailInfo.rowID) FROM ThumbnailInfo" );
@@ -253,4 +213,10 @@
 //remove KThumbnailDbFlagBlacklisted flag
 _LIT8( KThumbnailTouchBlacklistedRows, "UPDATE ThumbnailInfo SET Modified = 0 WHERE Flags & :Flag" );
 
+// existence check
+_LIT8( KThumbnailSelectAllPaths, "SELECT ThumbnailInfo.RowID,Path FROM ThumbnailInfo "
+        "WHERE NOT EXISTS (SELECT Path FROM ThumbnailDeleted "
+        "WHERE ThumbnailInfo.Path = ThumbnailDeleted.Path) "
+        "AND ThumbnailInfo.RowID > :RowID ORDER BY ThumbnailInfo.RowID ASC LIMIT :Limit;" );
+
 #endif // THUMBNAILSQL_H
--- a/imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/thumbnailstore.h	Fri Feb 19 23:07:36 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/thumbnailstore.h	Fri Mar 12 15:43:57 2010 +0200
@@ -25,6 +25,7 @@
 #include "thumbnailcenrep.h"
 #include "thumbnailmanagerconstants.h"
 #include "thumbnaillog.h"
+#include "tmactivitymanager.h"
 
 class RFs;
 class CFbsBitmap;
@@ -56,7 +57,7 @@
 
 
 /**
-* MMdSDiskSpaceNotifierObserver
+* MThumbnailStoreDiskSpaceNotifierObserver
 * Observer interface for a disk space notifier.
 */
 class MThumbnailStoreDiskSpaceNotifierObserver
@@ -79,7 +80,7 @@
     };
 
 /**
-* CMSDiskSpaceNotifierAO.
+* CThumbnailStoreDiskSpaceNotifierAO.
 * A disk space notifier class
 */
 class CThumbnailStoreDiskSpaceNotifierAO : public CActive
@@ -186,7 +187,9 @@
  *
  *  @since S60 v5.0
  */
-class CThumbnailStore: public CBase, public MThumbnailStoreDiskSpaceNotifierObserver
+class CThumbnailStore: public CBase, 
+                       public MThumbnailStoreDiskSpaceNotifierObserver,
+                       public MTMActivityManagerObserver
     {
     // Bitmasked Flags
     typedef enum 
@@ -228,8 +231,9 @@
      * @param aThumbFromPath Thumbnail created from associated path.
      */
     void StoreThumbnailL( const TDesC& aPath, CFbsBitmap* aThumbnail, const
-        TSize& aOriginalSize, TBool aCropped, const TThumbnailSize aThumbnailSize,
-        const TThumbnailId aThumbnailId = 0, const TBool aThumbFromPath = ETrue,
+        TSize& aOriginalSize, TBool aCropped, const TThumbnailSize aThumbnailSize, 
+        const TInt64 aModified,
+        const TBool aThumbFromPath = ETrue,
         TBool aBlackListed = EFalse );
 
     /**
@@ -257,48 +261,18 @@
             );
     
     /**
-     * Fetches thumbnail image.
-     *
-     * @since S60 v5.0
-     * @param aThumbnailId           Path of the media object whose thumbnail is
-     *                        to be retrieved.
-     * @param aThumbnail      Pointer to get the fetched thumbnail bitmap.
-     *                        Caller assumes ownership.
-     * @param aData           Pointer to get the fetched thumbnail JPEG.
-     *                        Caller assumes ownership.                      
-     * @param aThumbnailSize    Minimum size of the thumbnail
-     * .
-     * @param aThumbnailSize    Reference to real size of TN.
-     * 
-     * @return KErrNone, otherwise KErrNotFound if thumbnail not found from DB
-     */    
-    TInt FetchThumbnailL( TThumbnailId aThumbnailId, 
-            CFbsBitmap*& aThumbnail, 
-            TDesC8* & aData, 
-            TThumbnailSize aThumbnailSize, 
-            TSize &aThumbnailRealSize 
-            );
-    
-
-    /**
      * Delete thumbnails.
      *
      * @since S60 v5.0
      * @param aPath           Path of the media object whose thumbnail is
      *                        to be deleted.
+     * @param aForce          Force to delete instantly 
+     * @param aTransaction    Create a transaction 
      */
-    void DeleteThumbnailsL( const TDesC& aPath );
+    void DeleteThumbnailsL( const TDesC& aPath, TBool aForce = EFalse,
+                            TBool aTransaction = ETrue);
     
     /**
-      * Delete thumbnails.
-      *
-      * @since S60 TB9.1
-      * @param aTNId           Id of the media object whose thumbnail is
-      *                        to be deleted.
-      */
-     void DeleteThumbnailsL( const TThumbnailId& aTNId );
-
-    /**
      * Persistent sizes.
      *
      * @since S60 v5.0
@@ -313,128 +287,52 @@
      * @since S60 v5.0
      * @param aPath Path where missing sizes are associated
      * @param aMissingSizes List of missing thumbnail sizes
+     * @param aCheckGridSizeOnly check only is grid size missing
      */
-    void GetMissingSizesAndIDsL( const TDesC& aPath, TInt aSourceType, RArray <
-            TThumbnailPersistentSize > & aMissingSizes, TBool& aMissingIDs );
-    
-    /**
-       * Get persistent sizes not yet in database
-       *
-       * @since S60 TB9.1
-       * @param aId Id of TN where missing sizes are associated
-       * @param aMissingSizes List of missing thumbnail sizes
-       */
-      void GetMissingSizesL( const TThumbnailId aId, RArray <
-          TThumbnailPersistentSize > & aMissingSizes );
- 
+    void GetMissingSizesL( const TDesC& aPath, TInt aSourceType, RArray <
+            TThumbnailPersistentSize > & aMissingSizes, TBool aCheckGridSizeOnly  );
+        
     /**
-     * Find store for thumbnails.
-     *
-     * @since S60 TB9.1
-     * @param aThumbnailId Id of thumbnails to be updated.
-     */
-    void FindStoreL(TThumbnailId aThumbnailId);
-    
-    /**
-     * Updates path for thumbnails in current store.
-     *
-     * @since S60 v5.0
-     * @param aItemId Id for thumbnails to be updated.
-     * @param aNewPath New path for thumbnails.
-     * @return ETrue, if path was updated
-     */     
-    TBool UpdateStoreL( TThumbnailId aItemId, const TDesC& aNewPath );
-    
-    /**
-     * Updates path for thumbnails in current store.
+     * Check IMEI (owner) of db
      *
      * @since S60 v5.0
-     * @param aItemId Id for thumbnails to be updated.
-     * @param aNewPath New path for thumbnails.
-     */  
-    void UpdateStoreL( const TDesC& aPath, TThumbnailId aNewId );
-    
-    /**
-     * Check modification timestamp
-     *
-     * @since S60 v5.0
-     * @param aItemId Id for thumbnails to be updated.
-     * @param aModified new MDS timestamp
-     * @return ETrue, if given timestamp was newer than in DB
-     */     
-    TBool CheckModifiedL( const TThumbnailId aItemId, const TInt64 aModified );    
-    
-    /**
-     * Fetches thumbnails from store to be moved.
-     *
-     * @since S60 v5.0
-     * @param aItemId Id for thumbnails to be updated.
-     * @param aThumbnails Array for thumbnails to be moved.
-     */  
-    void FetchThumbnailsL(TThumbnailId aItemId, RArray < TThumbnailDatabaseData* >& aThumbnails);
-    
-    /**
-     * Stores thumbnails in to new store.
-     *
-     * @since S60 v5.0
-     * @param aNewPath New path for thumbnails.
-     * @param aThumbnails Array for thumbnails to be moved.
-     */  
-    void StoreThumbnailsL(const TDesC& aNewPath, RArray < TThumbnailDatabaseData* >& aThumbnails);
-    
-    /**
-     * Stores thumbnails in to new store.
-     *
-     * @since S60 v5.0
-     * @param aNewPath New path for thumbnails.
-     * @param aThumbnails Array for thumbnails to be moved.
      */  
     TInt CheckImeiL();
     
     /**
-     * Stores thumbnails in to new store.
+     * Check version of db
      *
      * @since S60 v5.0
-     * @param aNewPath New path for thumbnails.
-     * @param aThumbnails Array for thumbnails to be moved.
      */  
     TInt CheckVersionL();
     
     /**
-     * Stores thumbnails in to new store.
+     * Check mediaid of store
      *
      * @since S60 v5.0
-     * @param aNewPath New path for thumbnails.
-     * @param aThumbnails Array for thumbnails to be moved.
      */  
     TInt CheckMediaIDL();
     
     /**
-     * Stores thumbnails in to new store.
+     * Add version and IMEI to db
      *
      * @since S60 v5.0
-     * @param aNewPath New path for thumbnails.
-     * @param aThumbnails Array for thumbnails to be moved.
      */  
     void AddVersionAndImeiL();
     
     /**
-     * Stores thumbnails in to new store.
+     * Reset TNID column
      *
      * @since S60 v5.0
-     * @param aNewPath New path for thumbnails.
-     * @param aThumbnails Array for thumbnails to be moved.
      */  
-    void ResetThumbnailIDs();
+    TInt ResetThumbnailIDs();
     
     /**
-     * Stores thumbnails in to new store.
+     * Update IMEI to db
      *
      * @since S60 v5.0
-     * @param aNewPath New path for thumbnails.
-     * @param aThumbnails Array for thumbnails to be moved.
      */
-    void UpdateImeiL();
+    TInt UpdateImeiL();
     
     /**
      * Checks that database rowids match.
@@ -444,7 +342,22 @@
     
     TInt CheckRowIDsL();
     
+    /**
+     * Check is disk full
+     *
+     * @since S60 v5.0
+     */
     TBool IsDiskFull();
+    
+    /**
+     * Checks timestamp of blacklisted entry to timestamp of file, from
+     * which thumbnail entry was created, in filesystem
+     *
+     * @param aPath Path from which thumbnail created
+     * @param aModified current timestampt
+     * @contains indication whether file modified
+     */
+    TBool CheckModifiedByPathL( const TDesC& aPath, const TInt64 aModified, TBool& modifiedChanged);
 
 private:
     /**
@@ -463,13 +376,41 @@
      * @since S60 v5.0
      */
     void ConstructL();
+    
+    /**
+     * Starts constructing database
+     *
+     * @since S60 v5.0
+     */
+    void PrepareDbL();
+    
+    /**
+     * Open database
+     *
+     * @since S60 v5.0
+     */
+    TInt OpenDatabaseL();
+    
+    /**
+     * Open database
+     *
+     * @since S60 v5.0
+     */
+    TInt OpenDatabaseFileL();
 
     /**
-     * Create database tables.
+     * Construct database tables
      *
      * @since S60 v5.0
      */
     void CreateTablesL();
+    
+    /**
+     * Delete and create database
+     *
+     * @since S60 v5.0
+     */
+    void RecreateDatabaseL( const TBool aDelete);
 
     /**
      * Stores thumbnail image.
@@ -486,7 +427,7 @@
      */
     void StoreThumbnailL( const TDesC& aPath, const TDes8& aData, const TSize&
         aSize, const TSize& aOriginalSize, const TThumbnailFormat& aFormat, TInt aFlags, 
-        const TThumbnailSize& aThumbnailSize, const TThumbnailId aThumbnailId = 0,
+        const TThumbnailSize& aThumbnailSize, const TInt64 aModified,
         const TBool aThumbFromPath = ETrue);
 
     /**
@@ -497,8 +438,7 @@
      * @param aThumbnailId ID of the thumbnail
      * @param aThumbnailSize Associated size of the thumbnail to be deleted
      */
-    TBool FindDuplicateL( const TDesC& aPath, const TThumbnailId aThumbnailId,
-                          const TThumbnailSize& aThumbnailSize );    
+    TBool FindDuplicateL( const TDesC& aPath, const TThumbnailSize& aThumbnailSize );    
     
     /**
      * Flush RAM cache containing generated TNs to persistent storage.
@@ -522,6 +462,8 @@
      */
     void StopAutoFlush();
     
+    void StartMaintenance();
+    
     /**
      * Callback for harvesting complete timer
      *
@@ -530,36 +472,48 @@
     static TInt AutoFlushTimerCallBack(TAny* aAny);
     
     /**
-     * Checks timestamp of blacklisted entry to timestamp of file, from
-     * which thumbnail entry was created, in filesystem
+     * Callback for maintenance timer
      *
-     * @param aPath Path from which thumbnail created
-     * @param aTempTable Indication whether data in temp table
-     * @param aModified On return contains indication whether file modified
+     * @since S60 v5.0
      */
-    void CheckModifiedByPathL( const TDesC& aPath, TBool aTempTable, TBool& aModified  );
-    
-    /**
-     * Checks timestamp of blacklisted entry to timestamp of file, from
-     * which thumbnail entry was created, in filesystem
-     *
-     * @param aId Thumbnail id
-     * @param aTempTable Indication whether data in temp table
-     * @param aModified On return contains indication whether file modified
-     */
-    void CheckModifiedByIdL( TUint32 aId, TBool aTempTable, TBool& aModified  );
+    static TInt MaintenanceTimerCallBack(TAny* aAny);
     
     /**
     * Touches blacklisted items
     *
     */
-    void PrepareBlacklistedItemsForRetry();
+    void PrepareBlacklistedItemsForRetryL();
+    
+    /**
+    * Deletes thumbs added to Deleted table
+    *
+    */
+    TInt DeleteMarkedL();
+    
+    /**
+    * Checks if thumbnail source files are still in the file system.
+    * If not, delete corresponding thumbs.
+    *
+    * @return ETrue, if finished.
+    */
+    TBool FileExistenceCheckL();
+    
+    /**
+     * Strips drive letter from URI.
+     *
+     * @since S60 v5.0
+     * @param aPath Path.
+     */
+    void StripDriveLetterL( TDes& aPath );
     
 public : // From MThumbnailStoreDiskSpaceNotifierObserver
     void HandleDiskSpaceNotificationL(TBool aDiskFull);
 
     void HandleDiskSpaceError(TInt aError);
     
+private: //From MTMActivityManagerObserver
+    void ActivityChanged(const TBool aActive);
+    
 private:
     // data
 
@@ -602,17 +556,35 @@
 #ifdef _DEBUG
     TUint32 iThumbCounter;
 #endif
+
     /**
      * Periodic timer handling automatic flushing of db cache
      */
     CPeriodic* iAutoFlushTimer;
-    
+
+    /**
+     * Periodic timer handling db maintenance
+     */
+    CPeriodic* iMaintenanceTimer; 
+	   
     /**
     * Notifier for situations where free disk space runs out.
     */
     CThumbnailStoreDiskSpaceNotifierAO* iDiskFullNotifier;
     
     TBool iDiskFull;
+    
+    CTMActivityManager* iActivityManager;
+    
+    // device idle
+    TBool iIdle;
+    
+    // delete thumbs
+    TBool iDeleteThumbs;
+    
+    // check if thumb source files still exist
+    TBool iCheckFilesExist;
+    TInt64 iLastCheckedRowID;
 };
 // End of File
 
--- a/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailcenrep.cpp	Fri Feb 19 23:07:36 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailcenrep.cpp	Fri Mar 12 15:43:57 2010 +0200
@@ -31,12 +31,13 @@
 // ---------------------------------------------------------------------------
 //
 TThumbnailPersistentSize::TThumbnailPersistentSize( const TSize& aSize, TBool
-    aCrop, TDisplayMode aMode, TInt aFormat ): iSize( aSize ), iCrop( aCrop ),
+    aCrop, TDisplayMode aMode, TInt aFormat ) : iSize( aSize ), iCrop( aCrop ),
     iMode( aMode ), iFormat( aFormat )
     {
     iType = EUnknownThumbnailSize;
     iSourceType = EUnknownSourceType;
     iAutoCreate = ETrue;
+    iSizeType = EUnknownSizeType;
     }
 
 // ---------------------------------------------------------------------------
@@ -45,9 +46,9 @@
 //
 TThumbnailPersistentSize::TThumbnailPersistentSize( TThumbnailSize aType,
     const TSize& aSize, TBool aCrop, TDisplayMode aMode, TInt aFormat,
-    TBool aAutoCreate )
+    TBool aAutoCreate, TThumbnailSizeType aSizeType )
     : iType( aType ), iSize( aSize ), iCrop( aCrop ), iMode( aMode ),
-      iFormat( aFormat ), iAutoCreate( aAutoCreate )
+      iFormat( aFormat ), iAutoCreate( aAutoCreate ), iSizeType( aSizeType ) 
     {
     switch ( aType )
         {        
@@ -145,63 +146,63 @@
     User::LeaveIfError( iRepository->Get( KAutoCreateImageGrid, autoCreate ));
 
     iPersistentSizes.AppendL( TThumbnailPersistentSize( EImageGridThumbnailSize, TSize( xSize, ySize ),
-            KGridAndListThumbnailCropped, static_cast <TDisplayMode> (raw_mode), format, autoCreate ));
+            KGridAndListThumbnailCropped, static_cast <TDisplayMode> (raw_mode), format, autoCreate, TThumbnailPersistentSize::EGrid ));
 
     User::LeaveIfError( iRepository->Get( KSizeImageListWidth, xSize ));
     User::LeaveIfError( iRepository->Get( KSizeImageListHeight, ySize ));
     User::LeaveIfError( iRepository->Get( KAutoCreateImageList, autoCreate ));
 
     iPersistentSizes.AppendL( TThumbnailPersistentSize( EImageListThumbnailSize, TSize( xSize, ySize ),
-            KGridAndListThumbnailCropped, static_cast <TDisplayMode> (raw_mode), format, autoCreate ));
+            KGridAndListThumbnailCropped, static_cast <TDisplayMode> (raw_mode), format, autoCreate, TThumbnailPersistentSize::EList ));
     
     User::LeaveIfError( iRepository->Get( KSizeImageFullscreenWidth, xSize ));
     User::LeaveIfError( iRepository->Get( KSizeImageFullscreenHeight, ySize ));
     User::LeaveIfError( iRepository->Get( KAutoCreateImageFullscreen, autoCreate ));
     
     iPersistentSizes.AppendL( TThumbnailPersistentSize( EImageFullScreenThumbnailSize, TSize( xSize, ySize ),
-                              flags, static_cast <TDisplayMode> (raw_mode), format, autoCreate ));
+                              flags, static_cast <TDisplayMode> (raw_mode), format, autoCreate, TThumbnailPersistentSize::EFullscreen ));
     
     User::LeaveIfError( iRepository->Get( KSizeVideoGridWidth, xSize ));
     User::LeaveIfError( iRepository->Get( KSizeVideoGridHeight, ySize ));
     User::LeaveIfError( iRepository->Get( KAutoCreateVideoGrid, autoCreate ));
 
     iPersistentSizes.AppendL( TThumbnailPersistentSize( EVideoGridThumbnailSize, TSize( xSize, ySize ),
-            KGridAndListThumbnailCropped, static_cast <TDisplayMode> (raw_mode), format, autoCreate ));
+            KGridAndListThumbnailCropped, static_cast <TDisplayMode> (raw_mode), format, autoCreate, TThumbnailPersistentSize::EGrid ));
 
     User::LeaveIfError( iRepository->Get( KSizeVideoListWidth, xSize ));
     User::LeaveIfError( iRepository->Get( KSizeVideoListHeight, ySize ));
     User::LeaveIfError( iRepository->Get( KAutoCreateVideoList, autoCreate ));
 
     iPersistentSizes.AppendL( TThumbnailPersistentSize( EVideoListThumbnailSize, TSize( xSize, ySize ),
-            KGridAndListThumbnailCropped, static_cast <TDisplayMode> (raw_mode), format, autoCreate ));
+            KGridAndListThumbnailCropped, static_cast <TDisplayMode> (raw_mode), format, autoCreate, TThumbnailPersistentSize::EList ));
     
     User::LeaveIfError( iRepository->Get( KSizeVideoFullscreenWidth, xSize ));
     User::LeaveIfError( iRepository->Get( KSizeVideoFullscreenHeight, ySize ));
     User::LeaveIfError( iRepository->Get( KAutoCreateVideoFullscreen, autoCreate ));
     
     iPersistentSizes.AppendL( TThumbnailPersistentSize( EVideoFullScreenThumbnailSize, TSize( xSize, ySize ),
-                              flags, static_cast <TDisplayMode> (raw_mode), format, autoCreate ));  
+                              flags, static_cast <TDisplayMode> (raw_mode), format, autoCreate, TThumbnailPersistentSize::EFullscreen ));  
     
     User::LeaveIfError( iRepository->Get( KSizeAudioGridWidth, xSize ));
     User::LeaveIfError( iRepository->Get( KSizeAudioGridHeight, ySize ));
     User::LeaveIfError( iRepository->Get( KAutoCreateAudioGrid, autoCreate ));
 
     iPersistentSizes.AppendL( TThumbnailPersistentSize( EAudioGridThumbnailSize, TSize( xSize, ySize ),
-            KGridAndListThumbnailCropped, static_cast <TDisplayMode> (raw_mode), format, autoCreate ));
+            KGridAndListThumbnailCropped, static_cast <TDisplayMode> (raw_mode), format, autoCreate, TThumbnailPersistentSize::EGrid ));
 
     User::LeaveIfError( iRepository->Get( KSizeAudioListWidth, xSize ));
     User::LeaveIfError( iRepository->Get( KSizeAudioListHeight, ySize ));
     User::LeaveIfError( iRepository->Get( KAutoCreateAudioList, autoCreate ));
 
     iPersistentSizes.AppendL( TThumbnailPersistentSize( EAudioListThumbnailSize, TSize( xSize, ySize ),
-            KGridAndListThumbnailCropped, static_cast <TDisplayMode> (raw_mode), format, autoCreate ));
+            KGridAndListThumbnailCropped, static_cast <TDisplayMode> (raw_mode), format, autoCreate, TThumbnailPersistentSize::EList ));
     
     User::LeaveIfError( iRepository->Get( KSizeAudioFullscreenWidth, xSize ));
     User::LeaveIfError( iRepository->Get( KSizeAudioFullscreenHeight, ySize ));
     User::LeaveIfError( iRepository->Get( KAutoCreateAudioFullscreen, autoCreate ));
     
     iPersistentSizes.AppendL( TThumbnailPersistentSize( EAudioFullScreenThumbnailSize, TSize( xSize, ySize ),
-                              flags, static_cast <TDisplayMode> (raw_mode), format, autoCreate ));     
+                              flags, static_cast <TDisplayMode> (raw_mode), format, autoCreate, TThumbnailPersistentSize::EFullscreen ));     
     
     iAutoCreate = new (ELeave) TThumbnailAutoCreate();
     
--- a/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailgeneratetask.cpp	Fri Feb 19 23:07:36 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailgeneratetask.cpp	Fri Mar 12 15:43:57 2010 +0200
@@ -41,12 +41,12 @@
     const TDataType* aMimeType, CThumbnailManager::TThumbnailFlags aFlags,
     const TSize& aSize, TDisplayMode aDisplayMode, TInt aPriority,
     RArray < TThumbnailPersistentSize >* aMissingSizes, const TDesC& aTargetUri,
-    TThumbnailSize aThumbnailSize, const TThumbnailId aThumbnailId, 
+    TThumbnailSize aThumbnailSize, const TInt64 aModified, 
     const CThumbnailManager::TThumbnailQualityPreference aQualityPreference ): 
     CThumbnailTask( aProcessor, aPriority ), iServer( aServer ), 
     iFlags( aFlags ), iSize( aSize ), iDisplayMode( aDisplayMode ),
     iMissingSizes( aMissingSizes ), iTargetUri( aTargetUri ),
-    iThumbnailSize( aThumbnailSize ), iThumbnailId(aThumbnailId),
+    iThumbnailSize( aThumbnailSize ), iModified(aModified),
     iQualityPreference( aQualityPreference )
     {
     TN_DEBUG2( "CThumbnailGenerateTask(0x%08x)::CThumbnailGenerateTask()", this);
@@ -354,7 +354,7 @@
             
             CThumbnailScaleTask* scaleTask = CThumbnailScaleTask::NewL( iProcessor, iServer, iFilename,
                 iBitmap, iOriginalSize, (*iMissingSizes)[ i ].iSize, (*iMissingSizes)[ i ].iCrop, iDisplayMode,
-                KMaxPriority, iTargetUri, (*iMissingSizes)[ i ].iType, iThumbnailId, iScaledBitmapToPool, iEXIF );
+                KMaxPriority, iTargetUri, (*iMissingSizes)[ i ].iType, iModified, iScaledBitmapToPool, iEXIF );
             CleanupStack::PushL( scaleTask );
             
             TInt err1 = KErrNone;
@@ -411,7 +411,7 @@
         complTask = CThumbnailScaleTask::NewL( iProcessor, iServer, iFilename,
             iBitmap, iOriginalSize, iSize, iFlags& CThumbnailManager
             ::ECropToAspectRatio, iDisplayMode, KMaxPriority, iTargetUri,
-            iThumbnailSize, iThumbnailId, iScaledBitmapToPool, iEXIF );
+            iThumbnailSize, iModified, iScaledBitmapToPool, iEXIF );
         CleanupStack::PushL( complTask );
         
         TInt err1 = KErrNone;
@@ -482,12 +482,12 @@
     if(iFilename != KNullDesC)
         {
         iServer.StoreForPathL( iFilename )->StoreThumbnailL( 
-            iFilename, tempBitmap, aOriginalSize, EFalse, iThumbnailSize, iThumbnailId, EFalse, ETrue );
+            iFilename, tempBitmap, aOriginalSize, EFalse, iThumbnailSize, iModified, EFalse, ETrue );
         }
     else if(iTargetUri != KNullDesC)
         {
         iServer.StoreForPathL( iTargetUri )->StoreThumbnailL( 
-            iTargetUri, tempBitmap, aOriginalSize, EFalse, iThumbnailSize, iThumbnailId, EFalse, ETrue );
+            iTargetUri, tempBitmap, aOriginalSize, EFalse, iThumbnailSize, iModified, EFalse, ETrue );
         }
 
     CleanupStack::PopAndDestroy( tempBitmap );
@@ -506,10 +506,12 @@
     // error code just results in applications showing their default bitmap. 
     if( aError != KErrNone && (iFilename != KNullDesC || iTargetUri != KNullDesC ))
         {
-        if ( aError == KErrNotSupported ||
+        if (aError == KErrNotFound ||
+            aError == KErrNotSupported ||
             aError == KErrCorrupt ||
             aError == KErrCompletion ||
-            aError == KErrUnderflow)
+            aError == KErrUnderflow ||
+            aError == KErrNotReady)
             {
         
         if(iMissingSizes)
--- a/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailmdsquerytask.cpp	Fri Feb 19 23:07:36 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailmdsquerytask.cpp	Fri Mar 12 15:43:57 2010 +0200
@@ -87,88 +87,32 @@
             
             TN_DEBUG2( "CThumbnailMDSQueryTask::HandleQueryCompleted() - URI = %S", &object->Uri() );
                             
-            if( iUpdateToDb)
-                {
-                //update IDs to database by Path
-                if (ClientThreadAlive(EFalse))
-                    {               
-                    TInt err = iMessage.Read( 0, iRequestParams );
-                    if( err == KErrNone)
-                        {
-                        TThumbnailRequestParams& params = iRequestParams();
-                        TRAP_IGNORE(iServer.UpdateIDL(object->Uri(), params.iThumbnailId));
-                        }                   
-                    }
-                }
-    
-            // return path to client side            
-            ReturnPath(object->Uri());
-            }
-        else if (iQueryType == EId )
-            {
-            const CMdEObject* object = &iQuery->Result(0);
-            
-            TN_DEBUG2( "CThumbnailMDSQueryTask::HandleQueryCompleted() - Id = %d",  object->Id());
-            
-            if( object->Id() != KNoId)
+            // return path to client side       
+            if( iDelete )
                 {
-                if( iUpdateToDb)
-                    {
-                    TRAP_IGNORE(iServer.UpdateIDL(object->Uri(), object->Id() ));
-                    }
-                else
-                    {
-                    // add Id to message
-                    if (ClientThreadAlive(EFalse))
-                        {
-                        TInt ret = iMessage.Read( 0, iRequestParams );
-                        if( ret == KErrNone)
-                            {
-                            TThumbnailRequestParams& params = iRequestParams();
-                            params.iThumbnailId = object->Id();
-                            ret = iMessage.Write( 0, iRequestParams );
-                            }
-                        }
-                    }
+                TN_DEBUG2( "CThumbnailMDSQueryTask::HandleQueryCompleted() delete %S", &iUri );
+                TRAP_IGNORE( iServer.DeleteThumbnailsL( iUri ) );
                 }
-            
-            // complete the message with a code from which client side
-            // knows to make a new request using the path
-            if (ClientThreadAlive(EFalse))
-                {  
-                Complete( KThumbnailErrThumbnailNotFound );
-                ResetMessageData();
+            else
+                {
+                ReturnPath(object->Uri());
                 }
             }
         else
             {
-            TN_DEBUG1( "CThumbnailMDSQueryTask::HandleQueryCompleted() - Don't ever come here" );
+            TN_DEBUG1( "CThumbnailMDSQueryTask::HandleQueryCompleted() - Don't ever come here!" );
             if (ClientThreadAlive(EFalse))
                 {  
                 Complete( KErrNotFound );
                 ResetMessageData();
                 }
+            __ASSERT_DEBUG((EFalse), User::Panic(_L("CThumbnailMDSQueryTask::HandleQueryCompleted()"), KErrNotSupported));
             }
         }
     else
         {
         TN_DEBUG1( "CThumbnailMDSQueryTask::HandleQueryCompleted() - No results." );
-        
-        if( iQueryType == EId )
-            {
-            if( iUpdateToDb)
-                {
-                TN_DEBUG2( "CThumbnailMDSQueryTask::HandleQueryCompleted() delete %S", &iUri );
-                TRAP_IGNORE( iServer.DeleteThumbnailsL( iUri ) );
-                }
-               
-            if (ClientThreadAlive(EFalse))
-                {     
-                Complete( KThumbnailErrThumbnailNotFound );
-                ResetMessageData();
-                }
-            }
-        else 
+        if(!iDelete)
             {
             if (ClientThreadAlive(EFalse))
                 {  
@@ -230,10 +174,11 @@
 // CThumbnailMDSQueryTask::QueryPathByIdL()
 // ---------------------------------------------------------------------------
 //
-void CThumbnailMDSQueryTask::QueryPathByIdL(TThumbnailId aId)
+void CThumbnailMDSQueryTask::QueryPathByIdL(TThumbnailId aId, TBool aDelete)
     {
     TN_DEBUG1( "CThumbnailMDSQueryTask()::QueryPathByIdL()");
     iQueryType = EURI;
+    iDelete = aDelete;
     CMdENamespaceDef* defNamespace = &iMdESession->GetDefaultNamespaceDefL();
     CMdEObjectDef& objDef = defNamespace->GetObjectDefL( MdeConstants::Object::KBaseObject );
     
@@ -272,27 +217,6 @@
     }
 
 // ---------------------------------------------------------------------------
-// CThumbnailMDSQueryTask::QueryIdByPathL()
-// ---------------------------------------------------------------------------
-//
-void CThumbnailMDSQueryTask::QueryIdByPathL(const TDesC& aUri)
-    {
-    TN_DEBUG1( "CThumbnailMDSQueryTask()::QueryIdByPathL()");
-    iQueryType = EId;
-    iUri = aUri;
-    CMdENamespaceDef* defNamespace = &iMdESession->GetDefaultNamespaceDefL();
-    CMdEObjectDef& objDef = defNamespace->GetObjectDefL( MdeConstants::Object::KBaseObject );
-    
-    iQuery = iMdESession->NewObjectQueryL( *defNamespace, objDef, this );
-    iQuery->SetResultMode( EQueryResultModeItem );
-
-    CMdELogicCondition& rootCondition = iQuery->Conditions();
-    rootCondition.SetOperator( ELogicConditionOperatorOr );
-    
-    rootCondition.AddObjectConditionL(EObjectConditionCompareUri, aUri);
-    }
-
-// ---------------------------------------------------------------------------
 // CThumbnailMDSQueryTask::SetUpdateToDb()
 // ---------------------------------------------------------------------------
 //
--- a/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailscaletask.cpp	Fri Feb 19 23:07:36 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailscaletask.cpp	Fri Mar 12 15:43:57 2010 +0200
@@ -41,14 +41,14 @@
     aProcessor, CThumbnailServer& aServer, const TDesC& aFilename, CFbsBitmap*
     aBitmap, const TSize& aOriginalSize, const TSize& aTargetSize, TBool aCrop,
     TDisplayMode aDisplayMode, TInt aPriority, const TDesC& aTargetUri,
-    const TThumbnailSize aThumbnailSize, const TThumbnailId aThumbnailId,
+    const TThumbnailSize aThumbnailSize, const TInt64 aModified,
     TBool aBitmapToPool, const TBool aEXIF)
     {
     // We take ownership of aBitmap
     CleanupStack::PushL( aBitmap );
     CThumbnailScaleTask* self = new( ELeave )CThumbnailScaleTask( aProcessor,
         aServer, aFilename, aBitmap, aOriginalSize, aTargetSize, aCrop,
-        aDisplayMode, aPriority, aTargetUri, aThumbnailSize, aThumbnailId,
+        aDisplayMode, aPriority, aTargetUri, aThumbnailSize, aModified,
         aBitmapToPool, aEXIF);
     CleanupStack::Pop( aBitmap );
     CleanupStack::PushL( self );
@@ -67,12 +67,12 @@
     CThumbnailServer& aServer, const TDesC& aFilename, CFbsBitmap* aBitmap,
     const TSize& aOriginalSize, const TSize& aTargetSize, TBool aCrop,
     TDisplayMode aDisplayMode, TInt aPriority, const TDesC& aTargetUri,
-    const TThumbnailSize aThumbnailSize, const TThumbnailId aThumbnailId,
+    const TThumbnailSize aThumbnailSize, const TInt64 aModified,
     TBool aBitmapToPool, const TBool aEXIF):
     CThumbnailTask( aProcessor, aPriority ), iServer( aServer ), iOwnBitmap( aBitmap ),
-    iOriginalSize( aOriginalSize ), iTargetSize( aTargetSize ), iCrop( aCrop ),
+    iOriginalSize( aOriginalSize ), iTargetSize(aTargetSize), iTargetSizeTN( aTargetSize ), iCrop( aCrop ),
     iDisplayMode( aDisplayMode ), iFilename( aFilename ), iTargetUri( aTargetUri ),
-    iThumbnailSize(aThumbnailSize), iThumbnailId(aThumbnailId),
+    iThumbnailSize(aThumbnailSize), iModified(aModified),
     iBitmapToPool(aBitmapToPool), iEXIF(aEXIF)
     {
     TN_DEBUG2( "CThumbnailScaleTask(0x%08x)::CThumbnailScaleTask()", this );
@@ -326,16 +326,14 @@
 //
 void CThumbnailScaleTask::StoreAndCompleteL()
     {
-    TN_DEBUG5( "CThumbnailScaleTask(0x%08x)::StoreAndCompleteL() iFilename=%S, iBitmap=0x%08x, iScaledBitmap=0x%08x)", 
-               this, &iFilename, iBitmap, iScaledBitmap );
+    TN_DEBUG6( "CThumbnailScaleTask(0x%08x)::StoreAndCompleteL() iFilename=%S, iThumbnailSize=%d, iBitmap=0x%08x, iScaledBitmap=0x%08x)", 
+               this, &iFilename, iThumbnailSize, iBitmap, iScaledBitmap );
 		 
     // do not store TN if quality is too low eg. orignal size of image is smaller than requested size
     // (do not store upscaled images)
-    if ( iTargetSize.iWidth >= iOriginalSize.iWidth && 
-         iTargetSize.iHeight >= iOriginalSize.iHeight && iEXIF)
+    if ( (iTargetSizeTN.iWidth > iOriginalSize.iWidth || iTargetSizeTN.iHeight > iOriginalSize.iHeight) && iEXIF)
         {
         TN_DEBUG1("CThumbnailScaleTask()::StoreAndCompleteL() too low quality");
-        //don't store preview image
         iDoStore = EFalse;
         }
     
@@ -348,17 +346,17 @@
             if (iFilename != KNullDesC && iFilename.CompareF(iTargetUri) == 0)
                 {
                 // filename and target URI match, so thumb created from associated path
-                iServer.StoreThumbnailL( iTargetUri, iScaledBitmap, iOriginalSize, iCrop, iThumbnailSize, iThumbnailId, ETrue );
+                iServer.StoreThumbnailL( iTargetUri, iScaledBitmap, iOriginalSize, iCrop, iThumbnailSize, iModified, ETrue );
                 }
             else
                 {
                 // thumb not created from associated path
-                iServer.StoreThumbnailL( iTargetUri, iScaledBitmap, iOriginalSize, iCrop, iThumbnailSize, iThumbnailId, EFalse, EFalse );
+                iServer.StoreThumbnailL( iTargetUri, iScaledBitmap, iOriginalSize, iCrop, iThumbnailSize, iModified, EFalse, EFalse );
                 }  
             }
         else if (iFilename != KNullDesC)
             {
-            iServer.StoreThumbnailL( iFilename, iScaledBitmap, iOriginalSize, iCrop, iThumbnailSize, iThumbnailId, ETrue );
+            iServer.StoreThumbnailL( iFilename, iScaledBitmap, iOriginalSize, iCrop, iThumbnailSize, iModified, ETrue );
             }
         }    
     
@@ -374,7 +372,6 @@
             {
             TN_DEBUG1("CThumbnailScaleTask()::StoreAndCompleteL() scaled bitmap to pool");
             
-            
             params.iBitmapHandle = iScaledBitmap->Handle();
             
             iServer.AddBitmapToPoolL( iRequestId.iSession, iScaledBitmap, iRequestId );
--- a/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailserver.cpp	Fri Feb 19 23:07:36 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailserver.cpp	Fri Mar 12 15:43:57 2010 +0200
@@ -17,10 +17,10 @@
 
 
 #include <e32svr.h>
-#include <mihlscaler.h>
+#include <MIHLScaler.h>
 #include <driveinfo.h>
 #include <caf/data.h>
-#include <oma2agent.h>
+#include <Oma2Agent.h>
 #include <bautils.h>  
 #include <mdesession.h>
 
@@ -54,7 +54,7 @@
 // ----------------------------------------------------------------------------------------
 // Total number of ranges
 // ----------------------------------------------------------------------------------------
-const TUint KThumbnailServerRangeCount = 17;
+const TUint KThumbnailServerRangeCount = 16;
  
 // ----------------------------------------------------------------------------------------
 // Definition of the ranges
@@ -66,7 +66,6 @@
     EReleaseBitmap,
     ECancelRequest,
     EChangePriority,
-    ECreateThumbnails,
     EDeleteThumbnails,
     EGetMimeTypeBufferSize,
     EGetMimeTypeList,
@@ -90,7 +89,6 @@
     CPolicyServer::ECustomCheck,    // EReleaseBitmap
     CPolicyServer::ECustomCheck,    // ECancelRequest
     CPolicyServer::ECustomCheck,    // EChangePriority
-    CPolicyServer::ECustomCheck,    // ECreateThumbnails
     CPolicyServer::ECustomCheck,    // EDeleteThumbnails
     CPolicyServer::ECustomCheck,    // EGetMimeTypeBufferSize
     CPolicyServer::ECustomCheck,    // EGetMimeTypeList
@@ -139,7 +137,6 @@
         case EReleaseBitmap:
         case ECancelRequest:
         case EChangePriority:
-        case ECreateThumbnails:
         case EDeleteThumbnails:
         case EGetMimeTypeBufferSize:
         case EGetMimeTypeList:
@@ -251,9 +248,11 @@
     
     iFormatting = EFalse;
     
-    OpenStoresL();
+    //OpenStoresL();
     
     AddUnmountObserversL();
+    
+    iReconnect = CPeriodic::NewL(CActive::EPriorityIdle);
     }
 
 
@@ -270,9 +269,17 @@
     delete iShutdownObserver;
     delete iProcessor;
     
+    if(iReconnect)
+        {
+        iReconnect->Cancel();
+        delete iReconnect;
+        iReconnect = NULL;
+        }
+    
     if (iMdESession)
         {
         delete iMdESession;
+        iMdESession = NULL;
         }
 
     ResetAndDestroyHashMap < TInt, CThumbnailStore > ( iStores );
@@ -318,10 +325,17 @@
 //
 void CThumbnailServer::HandleSessionError( CMdESession& /*aSession*/, TInt aError )
     {
-    if (aError != KErrNone)
+    TN_DEBUG2( "CThumbnailServer::HandleSessionError == %d", aError );
+    if (aError != KErrNone && !iShutdown)
         {
-        TN_DEBUG2( "CThumbnailServer::HandleSessionError == %d", aError );
-        }   
+        if (!iReconnect->IsActive())
+            {
+            iReconnect->Start( KMdEReconnect, KMdEReconnect, 
+                               TCallBack(ReconnectCallBack, this));
+            
+            TN_DEBUG1( "CThumbnailServer::HandleSessionError() - reconnect timer started" );
+            }
+        } 
     }
 
 // -----------------------------------------------------------------------------
@@ -499,7 +513,7 @@
 //
 void CThumbnailServer::StoreThumbnailL( const TDesC& aPath, CFbsBitmap* aBitmap,
     const TSize& aOriginalSize, const TBool aCropped, const TThumbnailSize aThumbnailSize,
-    const TThumbnailId aThumbnailId, const TBool aThumbFromPath, const TBool aCheckExist )
+    const TInt64 aModified, const TBool aThumbFromPath, const TBool aCheckExist )
     {
     TN_DEBUG6( 
         "CThumbnailServer::StoreBitmapL(aPath=%S, aBitmap=0x%08x, aOriginalSize=%dx%d, aCropped=%d)", &aPath, aBitmap, aOriginalSize.iWidth, aOriginalSize.iHeight, aCropped );
@@ -510,12 +524,12 @@
     if (!aCheckExist)
         {
         StoreForPathL( aPath )->StoreThumbnailL( aPath, aBitmap, aOriginalSize,
-                       aCropped, aThumbnailSize, aThumbnailId, aThumbFromPath );
+                       aCropped, aThumbnailSize, aModified, aThumbFromPath );
         }    
     else if(BaflUtils::FileExists( iFs, aPath))
         {
         StoreForPathL( aPath )->StoreThumbnailL( aPath, aBitmap, aOriginalSize,
-                       aCropped, aThumbnailSize, aThumbnailId, aThumbFromPath );
+                       aCropped, aThumbnailSize, aModified, aThumbFromPath );
         }
     else
         {
@@ -569,7 +583,7 @@
         }
     else
         {
-        __ASSERT_DEBUG(( EFalse ), ThumbnailPanic( EThumbnailBitmapNotReleased ));
+        //__ASSERT_DEBUG(( EFalse ), ThumbnailPanic( EThumbnailBitmapNotReleased ));
         TN_DEBUG2( "CThumbnailServer::DeleteBitmapFromPool(%d) -- not found!",
             aHandle );
         }
@@ -587,41 +601,6 @@
     StoreForPathL( aPath )->DeleteThumbnailsL( aPath );
     }
 
-
-// -----------------------------------------------------------------------------
-// Delete thumbnails by Id
-// -----------------------------------------------------------------------------
-//
-void CThumbnailServer::DeleteThumbnailsByIdL( const TThumbnailId aItemId )
-    {
-    TN_DEBUG2( "CThumbnailServer::DeleteThumbnailsByIdL(%d)", aItemId);
-    
-#ifdef _DEBUG
-    TTime aStart, aStop;
-    aStart.UniversalTime();
-#endif
-    
-    // no path available, can be any store    
-    THashMapIter<TInt, CThumbnailStore*> iter( iStores );
-    CThumbnailStore* const *store = iter.NextValue();
-
-    while ( store )
-        {
-        TInt err = KErrNone;   
-        TRAP(err, ((CThumbnailStore*)(*store))->DeleteThumbnailsL(aItemId) );
-        if (err == KErrNone)
-            {
-#ifdef _DEBUG
-    aStop.UniversalTime();
-    TN_DEBUG2( "CThumbnailStore::DeleteThumbnailsByIdL() took %d ms", (TInt)aStop.MicroSecondsFrom(aStart).Int64()/1000);
-#endif
-            return;
-            }
-        store = iter.NextValue();
-        }    
-    }
-
-
 // -----------------------------------------------------------------------------
 // CThumbnailServer::ResolveMimeTypeL()
 // -----------------------------------------------------------------------------
@@ -909,67 +888,6 @@
     return res;
     }
 
-
-// -----------------------------------------------------------------------------
-// CThumbnailServer::FetchThumbnailL()
-// -----------------------------------------------------------------------------
-//
-void CThumbnailServer::FetchThumbnailL( TThumbnailId aThumbnailId, CFbsBitmap* &
-    aThumbnail, TDesC8* & aData, TThumbnailSize aThumbnailSize, TSize &aOriginalSize )
-    {
-    TN_DEBUG3( "CThumbnailServer::FetchThumbnailL(aThumbnailId=%d aThumbnailSize=%d)", aThumbnailId, aThumbnailSize );
-
-#ifdef _DEBUG
-    TTime aStart, aStop;
-    aStart.UniversalTime();
-    TInt roundCount = 1;
-#endif
-    
-    THashMapIter<TInt, CThumbnailStore*> storeIter(iStores);
-    
-    TN_DEBUG1( "CThumbnailServer::FetchThumbnailL() store iteration - begin");
-    for (CThumbnailStore* const* pStore = storeIter.NextValue();
-        pStore && aThumbnail == NULL ;
-        pStore = storeIter.NextValue())
-        {
-        TN_DEBUG2( "CThumbnailServer::FetchThumbnailL() store iteration - round == %d ", roundCount++);
-        CThumbnailStore* const store = (CThumbnailStore*)(*pStore);
-        
-        TRAPD(err, store->FetchThumbnailL( aThumbnailId, aThumbnail, aData, aThumbnailSize, aOriginalSize ));
-        
-        if( err == KErrCompletion )
-            {
-            // If thumbnail of requested size is blacklisted, fetching is left with KErrCompletion
-            TN_DEBUG1( 
-                "CThumbnailServer::FetchThumbnailL() - thumbnail blacklisted" );
-            User::Leave( err );
-            }
-        else if ( aThumbnail || aData)
-            { // thumbnail found from DB
-            TN_DEBUG1( "CThumbnailServer::FetchThumbnailL() found" );
-            break;
-            }
-/*
-#ifdef _DEBUG
-    aStop.UniversalTime();
-    TN_DEBUG3( "CThumbnailServer::FetchThumbnailL() iteration round %d took %d ms", roundCount, (TInt)aStop.MicroSecondsFrom(aStart).Int64()/1000);
-#endif 
-*/
-        }
-
-#ifdef _DEBUG
-    aStop.UniversalTime();
-    TN_DEBUG2( "CThumbnailServer::FetchThumbnailL() took %d ms", (TInt)aStop.MicroSecondsFrom(aStart).Int64()/1000);
-#endif 
-    
-    if ( !aThumbnail && !aData)
-        { // thumbnail not found from DB
-        TN_DEBUG1( "CThumbnailServer::FetchThumbnailL() not found" );
-        User::Leave( KErrNotFound );
-        }  
-    }
-
-
 // -----------------------------------------------------------------------------
 // Get the thumbnail store instance, which is responsible for the drive
 // identified by given path
@@ -1030,9 +948,6 @@
                 // ignore errors
                 TRAP_IGNORE( StoreForDriveL( i ));
                 
-                // start also placeholder task
-                //AddPlaceholderTaskL(i);
-                
                 driveCountInt--;
                 }
             }            
@@ -1066,10 +981,10 @@
     return iPersistentSizes;
     }
 
-void CThumbnailServer::GetMissingSizesAndIDsL( const TDesC& aPath, TInt aSourceType, RArray <
-    TThumbnailPersistentSize > & aMissingSizes, TBool& aMissingIDs )
+void CThumbnailServer::GetMissingSizesL( const TDesC& aPath, TInt aSourceType, RArray <
+    TThumbnailPersistentSize > & aMissingSizes, TBool aCheckGridSizeOnly  )
     {
-    StoreForPathL( aPath )->GetMissingSizesAndIDsL( aPath, aSourceType, aMissingSizes, aMissingIDs );
+    StoreForPathL( aPath )->GetMissingSizesL( aPath, aSourceType, aMissingSizes, aCheckGridSizeOnly );
     }
 
 // ---------------------------------------------------------------------------
@@ -1148,8 +1063,7 @@
         if (!err && !err_drive && driveInfo.iDriveAtt& KDriveAttRemovable)
             {
             // ignore errors
-            TRAP_IGNORE( StoreForDriveL( drive ));
-                    
+            //TRAP_IGNORE( StoreForDriveL( drive ));
             }
         
         //dismount -- if removable drive, close store
@@ -1214,7 +1128,7 @@
 // Updates thumbnails by given Id.
 // -----------------------------------------------------------------------------
 //
-TBool CThumbnailServer::UpdateThumbnailsL( const TThumbnailId aItemId, const TDesC& aPath,
+TBool CThumbnailServer::UpdateThumbnailsL( const TDesC& aPath,
                                            const TInt /*aOrientation*/, const TInt64 aModified )
     {
     TN_DEBUG1( "CThumbnailServer::UpdateThumbnailsL()");
@@ -1222,94 +1136,55 @@
     // 1. check path change
     // 2. check orientation change
     // 3. check timestamp change
-    TBool pathChanged = EFalse;
+
     TBool orientationChanged = EFalse;
     TBool modifiedChanged = EFalse;
     
-    CThumbnailStore* newstore = StoreForPathL( aPath );
-    TInt err(KErrNone);
-
-    // no path available, can be any store    
-    THashMapIter<TInt, CThumbnailStore*> iter( iStores );
-    CThumbnailStore* const *store = iter.NextValue();
-
-    while ( store )
-         {     
-        err = KErrNone;   
+    CThumbnailStore* store = StoreForPathL( aPath );
+   
+    // placeholder for orientation check
+    orientationChanged = EFalse;
+    
+    if (orientationChanged)
+        {
+        TN_DEBUG1( "CThumbnailServer::UpdateThumbnailsL() - orientation updated");
         
-        TRAP(err, ((CThumbnailStore*)(*store))->FindStoreL( aItemId ) );
-         
-         // no need to move thumbs to different store
-         if (err == KErrNone && *store == newstore)
+        // orientation updated, no need to check further
+        return ETrue;
+        }
+    else
+        {
+        TN_DEBUG1( "CThumbnailServer::UpdateThumbnailsL() - exist");
+        
+        TBool exists = store->CheckModifiedByPathL(aPath, aModified, modifiedChanged);
+       
+        if(!exists)
             {
-            pathChanged = ((CThumbnailStore*)(*store))->UpdateStoreL(aItemId, aPath);
+            TN_DEBUG1( "CThumbnailServer::UpdateThumbnailsL() - exists NO");
+            //not found, needs to be generated
+            return EFalse;
+            }
+        
+        TN_DEBUG1( "CThumbnailServer::UpdateThumbnailsL() - modified ?");
+        
+        if (modifiedChanged)
+            {
+            TN_DEBUG1( "CThumbnailServer::UpdateThumbnailsL() - modified YES");
             
-            if (pathChanged)
-                {
-                TN_DEBUG1( "CThumbnailServer::UpdateThumbnailsL() - path updated");
-                
-                // path updated, no need to check further
-                return ETrue;
-                }
-            else
-                {
-                // placeholder for orientation check
-                orientationChanged = EFalse;
-                
-                if (orientationChanged)
-                    {
-                    TN_DEBUG1( "CThumbnailServer::UpdateThumbnailsL() - orientation updated");
-                    
-                    // orientation updated, no need to check further
-                    return ETrue;
-                    }
-                else
-                    {
-                    TN_DEBUG1( "CThumbnailServer::UpdateThumbnailsL() - modified ?");
-                    modifiedChanged = ((CThumbnailStore*)(*store))->CheckModifiedL(aItemId, aModified);
-                    
-                    if (modifiedChanged)
-                        {
-                        TN_DEBUG1( "CThumbnailServer::UpdateThumbnailsL() - modified YES");
-                        
-                        // delete old thumbs
-                        ((CThumbnailStore*)(*store))->DeleteThumbnailsL(aItemId);
-                        
-                        // need to create new thumbs
-                        return EFalse;
-                        }
-                    else
-                        {
-                        TN_DEBUG1( "CThumbnailServer::UpdateThumbnailsL() - modified NO");
-                        
-                        // not modified
-                        return ETrue;
-                        }
-                    }
-                }
+            // delete old thumbs
+            store->DeleteThumbnailsL(aPath, ETrue);
             
-            }                 
-         // move to new store
-         else if (err == KErrNone && *store != newstore)
+            // need to create new thumbs
+            }
+        else
             {
-            RArray < TThumbnailDatabaseData* >* thumbnails = NULL;
-            thumbnails = new (ELeave) RArray < TThumbnailDatabaseData* >;
-            CleanupClosePushL( *thumbnails );
-            ((CThumbnailStore*)(*store))->FetchThumbnailsL(aItemId, *thumbnails);
-            newstore->StoreThumbnailsL(aPath, *thumbnails);
-            ((CThumbnailStore*)(*store))->DeleteThumbnailsL(aItemId);
-            CleanupStack::PopAndDestroy( thumbnails);
-            delete thumbnails;
-            thumbnails = NULL;
+            TN_DEBUG1( "CThumbnailServer::UpdateThumbnailsL() - modified NO");
             
-            TN_DEBUG1( "CThumbnailServer::UpdateThumbnailsL() - moved to different store");
-            
-            // no need to check further
+            // not modified
             return ETrue;
             }
-         
-         store = iter.NextValue();
-         } 
+        }
+  
     
     TN_DEBUG1( "CThumbnailServer::UpdateThumbnailsL() - no thumbs found, create new");
     
@@ -1580,19 +1455,6 @@
     }
 
 // -----------------------------------------------------------------------------
-// Updates ID for thumbnails with given Path
-// -----------------------------------------------------------------------------
-//
-void CThumbnailServer::UpdateIDL( const TDesC& aPath, const TThumbnailId aNewId )
-    {
-    TN_DEBUG3( "CThumbnailServer::UpdateIDL() aPath = %S aId = %d", &aPath, aNewId);
-    
-    CThumbnailStore* store = StoreForPathL( aPath );
-    User::LeaveIfNull( store );
-    store->UpdateStoreL( aPath, aNewId );
-    }
-
-// -----------------------------------------------------------------------------
 // Closes stores for removable drives
 // -----------------------------------------------------------------------------
 //
@@ -1687,3 +1549,29 @@
         }
     }
 
+// ---------------------------------------------------------------------------
+// CThumbnailServer::ReconnectCallBack()
+// ---------------------------------------------------------------------------
+//
+TInt CThumbnailServer::ReconnectCallBack(TAny* aAny)
+    {
+    TN_DEBUG1( "CThumbnailServer::ReconnectCallBack() - reconnect");
+    
+    CThumbnailServer* self = static_cast<CThumbnailServer*>( aAny );
+    
+    self->iReconnect->Cancel();
+    
+    if (self->iMdESession)
+        {
+        delete self->iMdESession;
+        self->iMdESession = NULL;
+        }
+    
+    // reconnect to MDS
+    TRAP_IGNORE( self->iMdESession = CMdESession::NewL( *self ) );
+    
+    TN_DEBUG1( "CThumbAGDaemon::ReconnectCallBack() - done");
+    
+    return KErrNone;
+    }
+
--- a/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailserversession.cpp	Fri Feb 19 23:07:36 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailserversession.cpp	Fri Mar 12 15:43:57 2010 +0200
@@ -102,11 +102,6 @@
                 err = ChangePriority( aMessage );
                 break;
                 }
-        case ECreateThumbnails:
-                {
-                CreateThumbnailsL( aMessage );
-                break;
-                }
         case EDeleteThumbnails:
                 {
                 DeleteThumbnailsL( aMessage );
@@ -243,17 +238,24 @@
     aMessage.ReadL( 0, iRequestParams );
     const TThumbnailRequestParams& params = iRequestParams();
     
-    TBool finished = Server()->UpdateThumbnailsL( params.iThumbnailId, params.iFileName, params.iOrientation, params.iModified );
+    TBool finished = Server()->UpdateThumbnailsL( params.iFileName, params.iOrientation, params.iModified );
     
     RArray < TThumbnailPersistentSize >* missingSizes = NULL;
     
+    TBool gridSizeOnly(EFalse);
+            
+    if ( params.iQualityPreference == CThumbnailManager
+                    ::EOptimizeForQualityWithPreview )
+        {
+        gridSizeOnly = ETrue;
+        }
+    
     if (finished)
         {
         // source type
         TDataType mimeType;
         TInt sourceType = 0;
         TInt err = Server()->MimeTypeFromFileExt( params.iFileName, mimeType );
-        TBool missingIDs(EFalse);
         
         // get missing sizes
         if ( err == KErrNone && ( params.iControlFlags & EThumbnailGeneratePersistentSizesOnly ) != 0 )
@@ -263,7 +265,7 @@
             missingSizes = new (ELeave) RArray < TThumbnailPersistentSize >;
             CleanupClosePushL( *missingSizes );
         
-            Server()->GetMissingSizesAndIDsL( params.iFileName, sourceType, *missingSizes, missingIDs);
+            Server()->GetMissingSizesL( params.iFileName, sourceType, *missingSizes, gridSizeOnly );
                 
             if ( missingSizes->Count() == 0)
                 {
@@ -276,7 +278,7 @@
         
         if(!missingSizes)
             {
-            TN_DEBUG1( "CThumbnailServerSession::UpdateThumbnailsL() - finished" );
+            TN_DEBUG1( "CThumbnailServerSession::UpdateThumbnailsL() - finished part 1" );
             aMessage.Complete( KErrNone );
             }
         else
@@ -285,7 +287,7 @@
             }
         }
 
-    if(missingSizes || !finished)
+    if (missingSizes || !finished)
         {
         TN_DEBUG1( "CThumbnailServerSession::UpdateThumbnailsL() - need to create (some) thumbs" );
         
@@ -306,7 +308,7 @@
         }
     else
         {
-        TN_DEBUG1( "CThumbnailServerSession::UpdateThumbnailsL() - finished" );
+        TN_DEBUG1( "CThumbnailServerSession::UpdateThumbnailsL() - finished part 2" );
         }
     
     iMessage = RMessage2();
@@ -334,54 +336,14 @@
 
     aMessage.ReadL( 0, iRequestParams );
     const TThumbnailRequestParams& params = iRequestParams();
-    TRAPD( err, Server()->FetchThumbnailL( params.iThumbnailId, iBitmap, iBuffer,
-                                           params.iThumbnailSize, iOriginalSize ));
-    if ( !err && iBitmap )
-        {
-        TN_DEBUG1( 
-            "CThumbnailServerSession::RequestThumbByIdAsyncL() - found existing thumbnail- bitmap" );
-
-        ProcessBitmapL();
-        }
-    else if ( !err && iBuffer)
-        {
-        TN_DEBUG1( 
-             "CThumbnailServerSession::RequestThumbByIdAsyncL() - found existing thumbnail- jpeg" );
-        
-        CThumbnailDecodeTask* task = new( ELeave )CThumbnailDecodeTask( Server()
-                 ->Processor(), * Server(), iBuffer, params.iPriority, params.iDisplayMode );
-        
-        CleanupStack::PushL( task );
-        task->SetMessageData( TThumbnailServerRequestId( this, params.iRequestId ), iMessage );
-        Server()->QueueTaskL( task );
-        CleanupStack::Pop( task ); // owned by processor now
-        
-        // Decode task is now responsible for completing the message
-        iMessage = RMessage2();
-        
-        //CThumbnailDecodeTask is responsible freeing
-        iBuffer = NULL;
-        }
-    else if( err == KErrCompletion )                
-        {
-        // If thumbnail of requested size is blacklisted, fetching is left with KErrCompletion
-        TN_DEBUG1( 
-            "CThumbnailServerSession::RequestThumbByIdAsyncL() - thumbnail blacklisted" );
-        aMessage.Complete( err );
-        iMessage = RMessage2();
-        }
-    else                
-        {
-        TN_DEBUG2( 
-            "CThumbnailServerSession::RequestThumbByIdAsyncL() - thumbnail not found ( query path from MDS ), err=%d ", err );
-
+    
 #ifdef RD_MDS_2_5        
         // try to query path from MDS
         CThumbnailMDSQueryTask* task = new( ELeave )CThumbnailMDSQueryTask(
                 Server()->Processor(), params.iPriority + 1, Server()->GetMdESession(), *Server());
         
         CleanupStack::PushL( task );
-        task->QueryPathByIdL(params.iThumbnailId);
+        task->QueryPathByIdL(params.iThumbnailId, EFalse);
         task->SetMessageData( TThumbnailServerRequestId( this, params.iRequestId ), iMessage );
         Server()->QueueTaskL( task );
         CleanupStack::Pop( task ); // owned by processor now
@@ -389,14 +351,13 @@
         // query task is now responsible for completing the message
         iMessage = RMessage2();
 #else
-        User::Leave(KThumbnailErrThumbnailNotFound);
+        User::Leave(KErrNotSupported);
 #endif // RD_MDS_2_5
         
-        }   
     
 #ifdef _DEBUG
     aStop.UniversalTime();
-    TN_DEBUG2( "CThumbnailStore::RequestThumbByIdAsyncL() request took %d ms", (TInt)aStop.MicroSecondsFrom(aStart).Int64()/1000 );
+    TN_DEBUG2( "CThumbnailServerSession::RequestThumbByIdAsyncL() request took %d ms", (TInt)aStop.MicroSecondsFrom(aStart).Int64()/1000 );
 #endif 
     
     TN_DEBUG1("CThumbnailServerSession::RequestThumbByIdAsyncL() - end" );
@@ -437,6 +398,7 @@
     // CreateThumbnails
     if (params.iControlFlags == EThumbnailGeneratePersistentSizesOnly)
         {
+        TN_DEBUG1( "CThumbnailServerSession::RequestThumbByFileHandleAsyncL() - EThumbnailGeneratePersistentSizesOnly" );
         CleanupClosePushL( file );
         CreateGenerateTaskFromFileHandleL( &file );
         CleanupStack::Pop( &file );         
@@ -467,6 +429,7 @@
         else if ( (err == KErrNotFound || err == KErrAccessDenied) && 
                  !(params.iFlags& CThumbnailManager::EDoNotCreate) )
             {
+            TN_DEBUG1( "CThumbnailServerSession::RequestThumbByFileHandleAsyncL() - KErrNotFound & !EDoNotCreate" );
             CreateGenerateTaskFromFileHandleL( &file);
             }
         else if (!err && iBuffer)
@@ -569,7 +532,7 @@
 	        {
             // If thumbnail of requested size is blacklisted, fetching is left with KErrCompletion
             TN_DEBUG1( 
-                "CThumbnailServerSession::RequestThumbByIdAsyncL() - thumbnail blacklisted" );
+                "CThumbnailServerSession::RequestThumbByPathAsyncL() - thumbnail blacklisted" );
             aMessage.Complete( err );
             iMessage = RMessage2();
 	        }
@@ -595,24 +558,7 @@
 	            User::Leave( KErrDiskFull );
 	            }
 
-#ifdef RD_MDS_2_5	        
-            // try to query ID from MDS
-            CThumbnailMDSQueryTask* task = new( ELeave )CThumbnailMDSQueryTask(
-                    Server()->Processor(), params.iPriority + 1, Server()->GetMdESession(), *Server());
-            
-            CleanupStack::PushL( task );
-            task->SetUpdateToDb( EFalse );
-            task->QueryIdByPathL( params.iFileName );
-            task->SetMessageData( TThumbnailServerRequestId( this, params.iRequestId ), iMessage );
-            Server()->QueueTaskL( task );
-            CleanupStack::Pop( task ); // owned by processor now
-            
-            // query task is now responsible for completing the message
-            iMessage = RMessage2();	            
-#else
             User::Leave(err);
-#endif // RD_MDS_2_5
-	        
 	        }   
 	   }
     
@@ -690,7 +636,6 @@
     TDataType mimeType;
     TInt sourceType = 0;
     TInt err = Server()->MimeTypeFromFileExt( params.iTargetUri, mimeType );
-    TBool missingIDs(EFalse);
     
     // get missing sizes
     if ( err == KErrNone && ( params.iControlFlags & EThumbnailGeneratePersistentSizesOnly ) != 0 )
@@ -700,7 +645,7 @@
         missingSizes = new (ELeave) RArray < TThumbnailPersistentSize >;
         CleanupClosePushL( *missingSizes );
     
-        Server()->GetMissingSizesAndIDsL( params.iTargetUri, sourceType, *missingSizes, missingIDs);
+        Server()->GetMissingSizesL( params.iTargetUri, sourceType, *missingSizes, EFalse);
             
         if ( missingSizes->Count() == 0)
             {
@@ -731,11 +676,9 @@
             CThumbnailScaleTask* scaleTask = CThumbnailScaleTask::NewL( Server()->Processor(),
                 *Server(), params.iTargetUri, bitmap, bitmapSize,
                 (*missingSizes)[i].iSize, (*missingSizes)[i].iCrop, params.iDisplayMode,
-                KMaxPriority, KNullDesC, (*missingSizes)[i].iType, params.iThumbnailId, EFalse, EFalse );
+                KMaxPriority, KNullDesC, (*missingSizes)[i].iType, params.iModified, EFalse, EFalse );
             CleanupStack::PushL( scaleTask );
             scaleTask->SetDoStore( ETrue );
-            //increase priority, scale needs to run before ID update below
-            scaleTask->SetPriority( params.iPriority + 1 );
             Server()->Processor().AddTaskL( scaleTask );
             CleanupStack::Pop( scaleTask );
             
@@ -746,8 +689,6 @@
                 iMessage = RMessage2();
                 }
             }
-        
-        TN_DEBUG3("CThumbnailServerSession::RequestSetThumbnailByBitmapL() ID = %d, missingIDs = %d", params.iThumbnailId, missingIDs);
         }
     else
         {
@@ -767,23 +708,6 @@
     iBitmapHandle = 0;
     bitmap = NULL;
     }
-
-// -----------------------------------------------------------------------------
-// CThumbnailServerSession::CreateThumbnailsL()
-// Create thumbnails for given object file
-// -----------------------------------------------------------------------------
-//
-void CThumbnailServerSession::CreateThumbnailsL( const RMessage2& aMessage )
-    {
-    RFile64 file;
-    CleanupClosePushL( file );
-	User::LeaveIfError( file.AdoptFromClient( aMessage, 1, 2 ));
-
-	CreateGenerateTaskFromFileHandleL( &file);
-        
-	CleanupStack::Pop( &file );
-    }      
-
  
 // -----------------------------------------------------------------------------
 // CThumbnailServerSession::CreateGenerateTaskL()
@@ -801,8 +725,6 @@
         {
         User::Leave( KErrDiskFull );
         }
-      
-    TBool missingIDs = EFalse;
     
     RArray < TThumbnailPersistentSize >* missingSizes = NULL;
     
@@ -813,35 +735,17 @@
         sourceType = Server()->SourceTypeFromMimeType( params.iMimeType );
         missingSizes = new (ELeave) RArray < TThumbnailPersistentSize >;
         CleanupClosePushL( *missingSizes );
-        
-        Server()->GetMissingSizesAndIDsL( params.iFileName, sourceType, *missingSizes, missingIDs );
-#ifdef RD_MDS_2_5        
-        if( missingIDs )
-            {
-            TN_DEBUG1("CThumbnailServerSession::CreateGenerateTaskFromFileHandleL() some IDs missing");
+		
+		    
+	    TBool gridSizeOnly(EFalse);
             
-            if( params.iThumbnailId == KNoId)
-                {
-                TN_DEBUG1("CThumbnailServerSession::CreateGenerateTaskFromFileHandleL() query fro MDS");
-                // try to query ID from MDS
-                CThumbnailMDSQueryTask* task = new( ELeave )CThumbnailMDSQueryTask(
-                        Server()->Processor(), params.iPriority + 1, Server()->GetMdESession(), *Server());
-                
-                CleanupStack::PushL( task );
-                task->QueryIdByPathL( params.iFileName );
-                
-                task->SetMessageData( TThumbnailServerRequestId( this, params.iRequestId ) );
-                Server()->QueueTaskL( task );
-                CleanupStack::Pop( task ); // owned by processor now
-                TN_DEBUG1("CThumbnailServerSession::CreateGenerateTaskFromFileHandleL() query from MDS queued" );
-                }
-            else
-                {
-                TN_DEBUG2("CThumbnailServerSession::CreateGenerateTaskFromFileHandleL() got ID %d from params", params.iThumbnailId);
-                TRAP_IGNORE( Server()->UpdateIDL(params.iFileName, params.iThumbnailId ) );
-                }
-            }
-#endif // RD_MDS_2_5
+	    if ( params.iQualityPreference == CThumbnailManager
+	                    ::EOptimizeForQualityWithPreview )
+	        {
+	        gridSizeOnly = ETrue;
+	        }
+        
+        Server()->GetMissingSizesL( params.iFileName, sourceType, *missingSizes, gridSizeOnly);
         
         if ( missingSizes->Count() == 0)
             {
@@ -873,7 +777,7 @@
     CThumbnailGenerateTask* task = new( ELeave )CThumbnailGenerateTask( Server()
         ->Processor(), * Server(), aFile, NULL, &params.iMimeType, params.iFlags,
         params.iSize, params.iDisplayMode, priority, missingSizes, params.iTargetUri,
-        params.iThumbnailSize, params.iThumbnailId, params.iQualityPreference );
+        params.iThumbnailSize, params.iModified, params.iQualityPreference );
 
     // do not store bitmaps to server pool when generating only
     if( params.iControlFlags & EThumbnailGeneratePersistentSizesOnly )
@@ -950,8 +854,7 @@
         missingSizes = new (ELeave) RArray < TThumbnailPersistentSize >;
         CleanupClosePushL( *missingSizes );
         
-        TBool missingIDs;
-        Server()->GetMissingSizesAndIDsL( params.iTargetUri, sourceType, *missingSizes, missingIDs );
+        Server()->GetMissingSizesL( params.iTargetUri, sourceType, *missingSizes, EFalse );
             
         if ( missingSizes->Count() == 0)
             {
@@ -984,7 +887,7 @@
     CThumbnailGenerateTask* task = new( ELeave )CThumbnailGenerateTask( Server()
         ->Processor(), * Server(), NULL, aBuffer, &params.iMimeType, params.iFlags,
         params.iSize, params.iDisplayMode, priority, missingSizes, params.iTargetUri,
-        params.iThumbnailSize, params.iThumbnailId, params.iQualityPreference );
+        params.iThumbnailSize, params.iModified, params.iQualityPreference );
 
     // do not store bitmaps to server pool when generating only
     if( params.iControlFlags & EThumbnailGeneratePersistentSizesOnly )
@@ -1030,15 +933,13 @@
     
     if( params.iFileName != KNullDesC )
         {
-        TN_DEBUG4( "CThumbnailServerSession::FetchThumbnailL( TNId==%d ThumbnailSize=%d ( Path=%S ))", 
-                params.iThumbnailId, params.iThumbnailSize, &params.iFileName );
+        TN_DEBUG3( "CThumbnailServerSession::FetchThumbnailL( ThumbnailSize=%d ( Path=%S ))", 
+                 params.iThumbnailSize, &params.iFileName );
         Server()->FetchThumbnailL( params.iFileName, iBitmap, iBuffer, params.iThumbnailSize, iOriginalSize);
         }
     else
         {
-        TN_DEBUG3( "CThumbnailServerSession::FetchThumbnailL(Path=%S ThumbnailSize=%d)", 
-                        &params.iFileName, params.iThumbnailSize );
-        Server()->FetchThumbnailL( params.iThumbnailId, iBitmap, iBuffer,  params.iThumbnailSize, iOriginalSize );
+        User::Leave( KErrNotSupported );
         }
 #ifdef _DEBUG
     if( iBitmap)
@@ -1064,7 +965,7 @@
         {
         Server()->StoreThumbnailL( params.iTargetUri, iBitmap, iOriginalSize,
                                    params.iFlags& CThumbnailManager::ECropToAspectRatio,
-                                   params.iThumbnailSize, params.iThumbnailId,
+                                   params.iThumbnailSize, params.iModified,
                                    EFalse, EFalse);
         }
     
@@ -1191,9 +1092,17 @@
     aMessage.ReadL( 0, iRequestParams );
     const TThumbnailRequestParams& params = iRequestParams();
     
-    TThumbnailId id = params.iThumbnailId;
-    Server()->DeleteThumbnailsByIdL( id );
+    
+#ifdef RD_MDS_2_5        
+    // try to query path from MDS
+    CThumbnailMDSQueryTask* task = new( ELeave )CThumbnailMDSQueryTask(
+            Server()->Processor(), params.iPriority + 1, Server()->GetMdESession(), *Server());
     
+    CleanupStack::PushL( task );
+    task->QueryPathByIdL(params.iThumbnailId, ETrue);
+    Server()->QueueTaskL( task );
+    CleanupStack::Pop( task ); // owned by processor now
+#endif // RD_MDS_2_5
     aMessage.Complete( KErrNone );
     iMessage = RMessage2();
     }
@@ -1328,6 +1237,7 @@
 //
 TInt CThumbnailServerSession::ConvertSqlErrToE32Err( TInt aReason )
     {
+    TN_DEBUG2("CThumbnailServerSession::ConvertSqlErrToE32Err(%d)", aReason);
     TInt e32Err;
     if ( aReason >=  - 144 )
     // magic: [-1..-144] is E32 error range 
--- a/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailstore.cpp	Fri Feb 19 23:07:36 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailstore.cpp	Fri Mar 12 15:43:57 2010 +0200
@@ -22,8 +22,9 @@
 #include <imageconversion.h>
 #include <e32base.h>
 #include <exifread.h>
+#include <bautils.h>  
+#include <IclExtJpegApi.h>
 
-#include <iclextjpegapi.h>
 #include "thumbnailstore.h"
 #include "thumbnailsql.h"
 #include "thumbnaillog.h"
@@ -34,7 +35,6 @@
 #include "thumbnailserver.h"
 
 
-
 _LIT8( KThumbnailSqlConfig, "page_size=16384; cache_size=32;" );
 
 const TInt KStreamBufferSize = 1024 * 8;
@@ -42,7 +42,9 @@
 const TInt KMinor = 2;
 
 // Database path without drive letter
-_LIT( KThumbnailDatabaseName, ":[102830AB]thumbnail_v2.db" );
+_LIT( KThumbnailDatabaseName, ":[102830AB]thumbnail_v3.db" );
+
+_LIT( KDrv, ":");
 
 // Allow access to database only for the server process
 const TSecurityPolicy KThumbnailDatabaseSecurityPolicy( TSecureId(
@@ -74,6 +76,10 @@
     else
         {
         iState = EError;
+#ifdef _DEBUG
+    TPtrC errorMsg = iDatabase.LastErrorMessage();
+    TN_DEBUG3( "RThumbnailTransaction::BeginL() lastError %S, ret = %d" , &errorMsg, err);
+#endif
         User::Leave( err );
         }
     }
@@ -98,7 +104,14 @@
 //
 void RThumbnailTransaction::CommitL()
     {
-    User::LeaveIfError( iDatabase.Exec( KThumbnailCommitTransaction ));
+    TInt ret = iDatabase.Exec( KThumbnailCommitTransaction );
+    
+#ifdef _DEBUG
+    TPtrC errorMsg = iDatabase.LastErrorMessage();
+    TN_DEBUG3( "RThumbnailTransaction::CommitL() lastError %S, ret = %d" , &errorMsg, ret);
+#endif  
+    User::LeaveIfError( ret );
+    
     iState = EClosed;
     }
 
@@ -143,8 +156,17 @@
     {
     TN_DEBUG1( "CThumbnailStore::~CThumbnailStore()" );
     
-    delete iDiskFullNotifier;
-    iDiskFullNotifier = NULL; 
+    if(iActivityManager)
+        {
+        delete iActivityManager;
+        iActivityManager = NULL;
+        }
+    
+    if(iDiskFullNotifier)
+        {
+        delete iDiskFullNotifier;
+        iDiskFullNotifier = NULL;
+        }
 
     if(!iServer->IsFormatting())
         {
@@ -199,115 +221,253 @@
                                             KDiskFullThreshold,
                                             pathPtr );
 
+    CleanupStack::PopAndDestroy( databasePath );
+    
+    OpenDatabaseL();
+             
+    // to monitor device activity
+    iActivityManager = CTMActivityManager::NewL( this, KStoreMaintenanceIdle);
+    iActivityManager->Start();
+    
+    // once in every mount
+    iDeleteThumbs = ETrue;
+    iCheckFilesExist = ETrue;
+    iLastCheckedRowID = -1;
+    }
+
+// ---------------------------------------------------------------------------
+// OpenDatabaseL database file
+// ---------------------------------------------------------------------------
+TInt CThumbnailStore::OpenDatabaseFileL()
+    {
+    TN_DEBUG1( "CThumbnailStore::OpenDatabaseFile()" );
+    HBufC* databasePath = HBufC::NewLC( KMaxFileName );
+    TPtr pathPtr = databasePath->Des();
+    TChar driveChar = 0;
+    User::LeaveIfError( RFs::DriveToChar( iDrive, driveChar ));
+    pathPtr.Append( driveChar );
+    pathPtr.Append( KThumbnailDatabaseName );
+    
+    TInt ret = iDatabase.Open( pathPtr );
+    CleanupStack::PopAndDestroy( databasePath );
+    return ret;
+    }
+
+// ---------------------------------------------------------------------------
+// OpenDatabaseL database
+// ---------------------------------------------------------------------------
+TInt CThumbnailStore::OpenDatabaseL()
+    {
+    TN_DEBUG1( "CThumbnailStore::OpenDatabaseL()" );
+        
+    iDatabase.Close();
+    
+    TBool newDatabase(EFalse);
+    TInt error = KErrNone;
+    
+    TInt err = OpenDatabaseFileL();
+   
+   if ( err == KErrNotFound )
+       {
+       // db not found, create new
+       RecreateDatabaseL( EFalse);
+       newDatabase = ETrue;
+       err = KErrNone;
+       }
+   else if ( err == KErrNone)
+       {
+       // db found, check version and rowids
+       error = CheckVersionL();
+       if(error == KErrNone)
+           {
+           error = CheckRowIDsL();
+           }  
+       }
+   
+   TN_DEBUG3( "CThumbnailStore::ConstructL() -- error = %d, err = %d", error, err);
+   
+   // if wrong version, corrupted database or other error opening db
+   if ( error == KErrNotSupported || (err != KErrNone && err != KErrNotFound) )
+       {
+       RecreateDatabaseL( ETrue);
+       }
+   else if(!newDatabase)
+       {
+       if(ResetThumbnailIDs() == KSqlErrCorrupt)
+           {
+           RecreateDatabaseL( ETrue);
+           }
+       
+       //check ownership
+       error = CheckImeiL();
+       
+       if(error != KErrNone)
+           {
+           if(error == KSqlErrCorrupt)
+               {
+               RecreateDatabaseL( ETrue);
+               }
+           //take ownership
+           error = UpdateImeiL();
+           
+           if(error == KSqlErrCorrupt)
+               {
+               RecreateDatabaseL( ETrue);
+               }
+           
+           //Touch blacklisted items
+           TRAP(error, PrepareBlacklistedItemsForRetryL( ) );
+           
+           if(error == KSqlErrCorrupt)
+               {
+               RecreateDatabaseL( ETrue);
+               }
+           }
+       
+       //check is MMC known
+       if(CheckMediaIDL() != KErrNone )
+           {
+           //Touch blacklisted items
+           TRAP(error, PrepareBlacklistedItemsForRetryL() );
+           
+           if(error == KSqlErrCorrupt)
+               {
+               RecreateDatabaseL( ETrue);
+               }
+           }
+       }
+   
+   PrepareDbL();
+   return KErrNone;
+    }
+
+// ---------------------------------------------------------------------------
+// PrepareDbL database tables
+// ---------------------------------------------------------------------------
+//
+void CThumbnailStore::PrepareDbL()
+    {
+    TN_DEBUG1( "CThumbnailStore::PrepareDbL()" );
+    TInt err(KErrNone);
+    
+    // add tables
+    TRAPD(tableError, CreateTablesL() );
+      
+    if(!tableError)
+      {
+      TRAPD(err, AddVersionAndImeiL());
+      if (err == KSqlErrCorrupt)
+          {
+          RecreateDatabaseL( ETrue);
+          }
+      User::LeaveIfError(err);
+      }
+          
+      err = iDatabase.Exec( KThumbnailCreateTempInfoTable );
+#ifdef _DEBUG
+  if(err < 0)
+      {
+       TPtrC errorMsg = iDatabase.LastErrorMessage();
+       TN_DEBUG2( "CThumbnailStore::ConstructL() KThumbnailCreateTempInfoTable %S" , &errorMsg);
+      }
+#endif
+    User::LeaveIfError( err );
+
+  err = iDatabase.Exec( KThumbnailCreateTempInfoDataTable );
+#ifdef _DEBUG
+  if(err < 0)
+      {
+       TPtrC errorMsg = iDatabase.LastErrorMessage();
+       TN_DEBUG2( "CThumbnailStore::ConstructL() KThumbnailCreateTempInfoDataTable %S" , &errorMsg);
+      }
+#endif
+       User::LeaveIfError( err );
+}
+
+// ---------------------------------------------------------------------------
+// Create database tables
+// ---------------------------------------------------------------------------
+//
+void CThumbnailStore::CreateTablesL()
+    {
+    TN_DEBUG1( "CThumbnailStore::CreateTablesL()" );
+    
+    TInt err = 0;
+    err = iDatabase.Exec( KThumbnailCreateInfoTable );
+    TN_DEBUG2( "CThumbnailStore::CreateTablesL() KThumbnailCreateInfoTable err=%d", err );
+    err = iDatabase.Exec( KThumbnailCreateInfoDataTable );
+    TN_DEBUG2( "CThumbnailStore::CreateTablesL() KThumbnailCreateInfoDataTable err=%d", err );
+    
+    err = iDatabase.Exec(KThumbnailDeletedTable);
+    TN_DEBUG2( "CThumbnailStore::CreateTablesL() KThumbnailDeletedTable err=%d", err );
+    
+    err = iDatabase.Exec(KThumbnailVersionTable);
+    TN_DEBUG2( "CThumbnailStore::CreateTablesL() KThumbnailVersionTable err=%d", err );
+    
+    err = iDatabase.Exec( KThumbnailCreateInfoTableIndex1 );
+    TN_DEBUG2( "CThumbnailStore::CreateTablesL() KThumbnailCreateInfoTableIndex1 err=%d", err );
+
+    err = iDatabase.Exec( KThumbnailCreateDeletedTableIndex );
+    TN_DEBUG2( "CThumbnailStore::CreateTablesL() KThumbnailCreateDeletedTableIndex err=%d", err );
+    
+    User::LeaveIfError( err );
+    }
+
+void CThumbnailStore::RecreateDatabaseL(const TBool aDelete)
+    {
+    TN_DEBUG1( "CThumbnailStore::RecreateDatabaseL()" );
+    
     TVolumeInfo volumeinfo;
     iFs.Volume(volumeinfo, iDrive);
     TUint id = volumeinfo.iUniqueID;
     TBuf<50> mediaid;
     mediaid.Num(id);
-    TBool newDatabase(EFalse);
+    
+    // delete db and create new
+    iDatabase.Close();
     
-    TInt error = KErrNone;
+    HBufC* databasePath = HBufC::NewLC( KMaxFileName );
+    TPtr pathPtr = databasePath->Des();
+    TChar driveChar = 0;
+    User::LeaveIfError( RFs::DriveToChar( iDrive, driveChar ));
+    pathPtr.Append( driveChar );
+    pathPtr.Append( KThumbnailDatabaseName );
     
-    TInt err = iDatabase.Open( pathPtr );
-    if ( err == KErrNotFound )
+    TInt err(KErrNone);
+    
+    if(aDelete)
         {
-        // db not found, create new
-        TN_DEBUG1( "CThumbnailStore::ConstructL() -- 1 creating database" );
-        const TDesC8& config = KThumbnailSqlConfig;
-
-        RSqlSecurityPolicy securityPolicy;
-        CleanupClosePushL( securityPolicy );
-        securityPolicy.Create( KThumbnailDatabaseSecurityPolicy );
-
-        iDatabase.CreateL( pathPtr, securityPolicy, &config );
-        CleanupStack::PopAndDestroy( &securityPolicy );
-
-        TN_DEBUG1( "CThumbnailStore::ConstructL() -- 1 database created ok" );
-                
-        RFile64 file;
-        file.Create(iFs, mediaid, EFileShareReadersOrWriters );
-        file.Close();
-        newDatabase = ETrue;
-        }
-    else if ( err == KErrNone)
-        {
-        // db found, check version and rowids
-        error = CheckVersionL();
-        if(error == KErrNone)
-            {
-            error = CheckRowIDsL();
-            }  
-        }
-    
-    // if wrong version, corrupted database or other error opening db
-    if ( error == KErrNotSupported || (err != KErrNone && err != KErrNotFound) )
-        {
-        TN_DEBUG1( "CThumbnailStore::ConstructL() -- delete databases" );
-        
-        // delete db and create new
-        iDatabase.Close();
         iDatabase.Delete(pathPtr);
-        
-        TN_DEBUG1( "CThumbnailStore::ConstructL() -- 2 creating database" );
+        }
         
-        const TDesC8& config = KThumbnailSqlConfig;
-
-        RSqlSecurityPolicy securityPolicy;
-        CleanupClosePushL( securityPolicy );
-        securityPolicy.Create( KThumbnailDatabaseSecurityPolicy );
+    const TDesC8& config = KThumbnailSqlConfig;
 
-        iDatabase.CreateL( pathPtr, securityPolicy, &config );
-        CleanupStack::PopAndDestroy( &securityPolicy );
+    RSqlSecurityPolicy securityPolicy;
+    CleanupClosePushL( securityPolicy );
+    securityPolicy.Create( KThumbnailDatabaseSecurityPolicy );
 
-        TN_DEBUG1( "CThumbnailStore::ConstructL() -- 2 database created ok" );
+    TRAP(err, iDatabase.CreateL( pathPtr, securityPolicy, &config ));
+    CleanupStack::PopAndDestroy( &securityPolicy );
+    
         
-        RFile64 file;
-        file.Create(iFs, mediaid, EFileShareReadersOrWriters );
-        file.Close();
-        }
-    else if(!newDatabase)
+#ifdef _DEBUG
+    if(err < 0)
         {
-        //check ownership
-        if(CheckImeiL() != KErrNone)
-            {
-            ResetThumbnailIDs();
-            
-            //take ownership
-            UpdateImeiL();
-            
-            //Touch blacklisted items
-            TRAP_IGNORE( PrepareBlacklistedItemsForRetry( ) );
-            }
-        
-        //check is MMC known
-        if(CheckMediaIDL() != KErrNone )
-            {
-            ResetThumbnailIDs();
-            
-            //Touch blacklisted items
-            TRAP_IGNORE( PrepareBlacklistedItemsForRetry() );
-            }
+        TPtrC errorMsg = iDatabase.LastErrorMessage();
+        TN_DEBUG2( "CThumbnailStore::RecreateDatabaseL() KThumbnailInsertTempThumbnailInfoData %S" , &errorMsg);
         }
-              
+#endif
+    TN_DEBUG2( "CThumbnailStore::RecreateDatabaseL() -- database created err = %d", err );
+    User::LeaveIfError( err );
     CleanupStack::PopAndDestroy( databasePath );
     
-    // add tables
-    TRAPD(tableError, CreateTablesL() );
-    
-    if(!tableError)
-        {
-        AddVersionAndImeiL();
-        }
+    RFile64 file;
+    file.Create(iFs, mediaid, EFileShareReadersOrWriters );
+    file.Close();
     
-    err = iDatabase.Exec( KThumbnailCreateTempInfoTable );
-    TN_DEBUG2("CThumbnailStore::CreateTablesL() KThumbnailCreateTempInfoTable %d", err);
-    User::LeaveIfError( err );
-    err = iDatabase.Exec( KThumbnailCreateTempInfoDataTable );
-    TN_DEBUG2("CThumbnailStore::CreateTablesL() KThumbnailCreateTempInfoDataTable %d", err);
-    User::LeaveIfError( err );
+    OpenDatabaseFileL();
     }
 
-
 // ---------------------------------------------------------------------------
 // CThumbnailStore::StoreThumbnailL()
 // Stores thumbnail image.
@@ -315,7 +475,7 @@
 //
 void CThumbnailStore::StoreThumbnailL( const TDesC& aPath, const TDes8& aData,
     const TSize& aSize, const TSize& aOriginalSize, const TThumbnailFormat& aFormat, TInt aFlags, 
-	const TThumbnailSize& aThumbnailSize, TThumbnailId aThumbnailId, const TBool aThumbFromPath )
+	const TThumbnailSize& aThumbnailSize, const TInt64 aModified, const TBool aThumbFromPath )
     {
     TN_DEBUG1( "CThumbnailStore::StoreThumbnailL( const TDes8& ) in" );
 
@@ -366,17 +526,6 @@
     User::LeaveIfError( paramIndex );
     User::LeaveIfError( stmt.BindInt( paramIndex, aThumbnailSize ));
     
-    if( aThumbnailId > 0 )
-        {
-        paramIndex = stmt.ParameterIndex( KThumbnailSqlParamId );
-        User::LeaveIfError( paramIndex );
-        User::LeaveIfError( stmt.BindInt( paramIndex, aThumbnailId ));
-        }
-    else
-        {
-        TN_DEBUG1( "CThumbnailStore::StoreThumbnailL( ) aThumbnailId == 0" );
-        }
-    
     // orientation temporarily to 0
     paramIndex = stmt.ParameterIndex( KThumbnailSqlParamOrientation );
     User::LeaveIfError( paramIndex );
@@ -391,16 +540,30 @@
     // try getting modification time from file
     TTime timeStamp;
     
-    if (aPath.Length())
+    TN_DEBUG2( "CThumbnailStore::StoreThumbnailL() timeStamp aModified %Ld", aModified );
+        
+    if( aModified )
         {
-        iFs.Modified(aPath, timeStamp);
+        timeStamp = aModified;
         }
     else
         {
-        // otherwise current time
-        timeStamp.UniversalTime();
+
+        if (aPath.Length())
+            {
+            iFs.Modified(aPath, timeStamp);
+            TN_DEBUG2( "CThumbnailStore::StoreThumbnailL() timeStamp       iFs %Ld", timeStamp.Int64() );
+            }
+        else
+            {
+            // otherwise current time
+            timeStamp.UniversalTime();
+            TN_DEBUG2( "CThumbnailStore::StoreThumbnailL() timeStamp   current %Ld", timeStamp.Int64() );
+            }
         }
-    
+        
+   TN_DEBUG2( "CThumbnailStore::StoreThumbnailL() timeStamp       set %Ld", timeStamp.Int64());
+   
     paramIndex = stmt.ParameterIndex( KThumbnailSqlParamModified );
     User::LeaveIfError( paramIndex );
     User::LeaveIfError( stmt.BindInt64( paramIndex, timeStamp.Int64() ));
@@ -414,8 +577,11 @@
     TInt err = stmtData.Prepare( iDatabase, KThumbnailInsertTempThumbnailInfoData );
        
 #ifdef _DEBUG
-    TPtrC errorMsg = iDatabase.LastErrorMessage();
-    TN_DEBUG2( "CThumbnailStore::FetchThumbnailL() KThumbnailInsertTempThumbnailInfoData %S" , &errorMsg);
+    if(err < 0)
+        {
+        TPtrC errorMsg = iDatabase.LastErrorMessage();
+        TN_DEBUG2( "CThumbnailStore::StoreThumbnailL() KThumbnailInsertTempThumbnailInfoData %S" , &errorMsg);
+        }
 #endif    
     User::LeaveIfError( err );
     
@@ -452,10 +618,10 @@
 //
 void CThumbnailStore::StoreThumbnailL( const TDesC& aPath, CFbsBitmap*
     aThumbnail, const TSize& aOriginalSize, TBool /*aCropped*/, const TThumbnailSize aThumbnailSize, 
-    const TThumbnailId aThumbnailId, const TBool aThumbFromPath, TBool aBlackListed )
+    const TInt64 aModified, TBool aThumbFromPath, TBool aBlackListed )
     {
     TSize thumbSize = aThumbnail->SizeInPixels();
-    TN_DEBUG5( "CThumbnailStore::StoreThumbnailL( CFbsBitmap ) aThumbnailId = %d, aThumbnailSize = %d, aThumbnailSize(%d,%d) IN", aThumbnailId, aThumbnailSize, thumbSize.iWidth, thumbSize.iHeight );
+    TN_DEBUG4( "CThumbnailStore::StoreThumbnailL( CFbsBitmap ) aThumbnailSize = %d, aThumbnailSize(%d,%d) IN", aThumbnailSize, thumbSize.iWidth, thumbSize.iHeight );
 
     __ASSERT_DEBUG(( aThumbnail ), ThumbnailPanic( EThumbnailNullPointer ));
     
@@ -466,9 +632,13 @@
         TN_DEBUG1( "CThumbnailStore::StoreThumbnailL() not stored");
         return;
         }
+    
+    HBufC* path = aPath.AllocLC();
+    TPtr ptr(path->Des());
+    StripDriveLetterL( ptr );
 
     // check for duplicates
-    TBool exists = FindDuplicateL(aPath, aThumbnailId, aThumbnailSize);
+    TBool exists = FindDuplicateL(*path, aThumbnailSize);
     
     for ( TInt i = iPersistentSizes.Count(); --i >= 0; )
         {
@@ -518,8 +688,8 @@
                 if(request== KErrNone)
                   {
                   TPtr8 ptr  = data->Des(); 
-                  StoreThumbnailL( aPath, ptr, aThumbnail->SizeInPixels(), aOriginalSize,
-                          EThumbnailFormatJpeg, flags, aThumbnailSize, aThumbnailId, aThumbFromPath  );
+                  StoreThumbnailL( *path, ptr, aThumbnail->SizeInPixels(), aOriginalSize,
+                          EThumbnailFormatJpeg, flags, aThumbnailSize, aModified, aThumbFromPath  );
                   }
              
                 delete iFrameImageData;
@@ -538,8 +708,8 @@
                 stream.Open( *buf );
                 aThumbnail->ExternalizeL( stream );
             
-                StoreThumbnailL( aPath, buf->Ptr( 0 ), aThumbnail->SizeInPixels(),
-                    aOriginalSize, EThumbnailFormatFbsBitmap, flags, aThumbnailSize, aThumbnailId );
+                StoreThumbnailL( *path, buf->Ptr( 0 ), aThumbnail->SizeInPixels(),
+                    aOriginalSize, EThumbnailFormatFbsBitmap, flags, aThumbnailSize, aModified);
   
                 CleanupStack::PopAndDestroy( buf );
                 }
@@ -548,16 +718,16 @@
             }
         }
     
+    CleanupStack::PopAndDestroy( path );
+    
     TN_DEBUG1( "CThumbnailStore::StoreThumbnailL( CFbsBitmap* ) out" );
     }
 
-
 // ---------------------------------------------------------------------------
 // Finds possible existing duplicate thumbnail.
 // ---------------------------------------------------------------------------
 //
-TBool CThumbnailStore::FindDuplicateL( const TDesC& aPath, const TThumbnailId aThumbnailId,
-                                       const TThumbnailSize& aThumbnailSize )
+TBool CThumbnailStore::FindDuplicateL( const TDesC& aPath, const TThumbnailSize& aThumbnailSize )
     {
     TN_DEBUG1( "CThumbnailStore::FindDuplicateL()" );
     
@@ -572,10 +742,6 @@
     paramIndex = stmt.ParameterIndex( KThumbnailSqlParamPath );
     User::LeaveIfError( paramIndex );
     User::LeaveIfError( stmt.BindText( paramIndex, aPath ));
-        
-    paramIndex = stmt.ParameterIndex( KThumbnailSqlParamId );
-    User::LeaveIfError( paramIndex );
-    User::LeaveIfError( stmt.BindInt( paramIndex, aThumbnailId ));
     
     paramIndex = stmt.ParameterIndex( KThumbnailSqlParamSize );
     User::LeaveIfError( paramIndex );
@@ -595,10 +761,6 @@
         User::LeaveIfError( paramIndex );
         User::LeaveIfError( stmt.BindText( paramIndex, aPath ));
             
-        paramIndex = stmt.ParameterIndex( KThumbnailSqlParamId );
-        User::LeaveIfError( paramIndex );
-        User::LeaveIfError( stmt.BindInt( paramIndex, aThumbnailId ));
-        
         paramIndex = stmt.ParameterIndex( KThumbnailSqlParamSize );
         User::LeaveIfError( paramIndex );
         User::LeaveIfError( stmt.BindInt( paramIndex, aThumbnailSize ));
@@ -623,43 +785,51 @@
         found = ETrue;
         }
     
+    // check if duplicate in Deleted
+    if (found)
+        {
+        stmt.Close();
+        CleanupStack::PopAndDestroy( &stmt );
+        CleanupClosePushL( stmt );     
+            
+        User::LeaveIfError( stmt.Prepare( iDatabase, KThumbnailSqlFindDeleted ));
+        paramIndex = stmt.ParameterIndex( KThumbnailSqlParamPath );
+        User::LeaveIfError( paramIndex );
+        User::LeaveIfError( stmt.BindText( paramIndex, aPath ));
+        
+        rowStatus = stmt.Next();
+        
+        if(rowStatus == KSqlAtRow)
+            {
+            TN_DEBUG1( "CThumbnailStore::FindDuplicateL() - duplicate marked deleted" );
+            
+            DeleteThumbnailsL(aPath, ETrue);
+            
+            TN_DEBUG1( "CThumbnailStore::FindDuplicateL() - duplicate force-deleted" );
+            
+            found = EFalse;
+            }
+        }
+    
     stmt.Close();
     CleanupStack::PopAndDestroy( &stmt );
     
     return found;
     }
 
-
-// ---------------------------------------------------------------------------
-// Create database tables
-// ---------------------------------------------------------------------------
-//
-void CThumbnailStore::CreateTablesL()
-    {
-    TN_DEBUG1( "CThumbnailStore::CreateTablesL()" );
-    TInt err = 0;
-    err = iDatabase.Exec( KThumbnailCreateInfoTable );
-    TN_DEBUG2( "CThumbnailStore::CreateTablesL() KThumbnailCreateInfoTable err=%d", err );
-    err = iDatabase.Exec( KThumbnailCreateInfoDataTable );
-    TN_DEBUG2( "CThumbnailStore::CreateTablesL() KThumbnailCreateInfoDataTable err=%d", err );
-    err = iDatabase.Exec( KThumbnailCreateInfoTableIndex1 );
-    TN_DEBUG2( "CThumbnailStore::CreateTablesL() KThumbnailCreateInfoTableIndex1 err=%d", err );
-    err = iDatabase.Exec( KThumbnailCreateInfoTableIndex2 );
-    TN_DEBUG2( "CThumbnailStore::CreateTablesL() KThumbnailCreateInfoTableIndex2 err=%d", err );
-    err = iDatabase.Exec(KThumbnailVersionTable);
-    TN_DEBUG2( "CThumbnailStore::CreateTablesL() KThumbnailVersionTable err=%d", err );
-    User::LeaveIfError( err );
-    }
-
-
 // ---------------------------------------------------------------------------
 // Get missing sizes by Path
 // ---------------------------------------------------------------------------
 //     
-void CThumbnailStore::GetMissingSizesAndIDsL( const TDesC& aPath, TInt aSourceType, RArray <
-    TThumbnailPersistentSize > & aMissingSizes, TBool& aMissingIDs )
+void CThumbnailStore::GetMissingSizesL( const TDesC& aPath, TInt aSourceType, RArray <
+    TThumbnailPersistentSize > & aMissingSizes, TBool aCheckGridSizeOnly )
     {
-    TN_DEBUG2( "CThumbnailStore::GetMissingSizesAndIDsL() aSourceType == %d", aSourceType );
+    TN_DEBUG2( "CThumbnailStore::GetMissingSizesL() aSourceType == %d", aSourceType );
+    
+    HBufC* path = aPath.AllocLC();
+    TPtr ptr(path->Des());
+    StripDriveLetterL( ptr );
+    
     // define sizes to be checked
     const TInt count = iPersistentSizes.Count();
     
@@ -667,14 +837,30 @@
         {
         if ( iPersistentSizes[ i ].iSourceType == aSourceType && iPersistentSizes[ i ].iAutoCreate)
             {
-            aMissingSizes.Append( iPersistentSizes[ i ] );
+            //if generating only grid size for image or video, other sizes are not missing
+            if( aCheckGridSizeOnly )
+			{
+				if( (iPersistentSizes[i].iSourceType == TThumbnailPersistentSize::EImage || iPersistentSizes[i].iSourceType == TThumbnailPersistentSize::EVideo )&&
+                     iPersistentSizes[i].iSizeType != TThumbnailPersistentSize::EGrid )
+                    {
+                    TN_DEBUG4( "CThumbnailStore::GetMissingSizesL() skip, aCheckGridSizeOnly = %d and  iPersistentSizes[%d].iSizeType == %d", 
+                            aCheckGridSizeOnly, i, iPersistentSizes[i].iSizeType );
+                    }
+				else
+				    {
+                    aMissingSizes.Append( iPersistentSizes[ i ] );
+				    }
+			}
+            else
+                {
+                aMissingSizes.Append( iPersistentSizes[ i ] );
+                }
             }
         }
     
     TInt missingSizeCount = aMissingSizes.Count();
-    aMissingIDs = EFalse;
         
-    TN_DEBUG3( "CThumbnailStore::GetMissingSizesAndIDsL() missingSizeCount == %d, missingIDs == %d", missingSizeCount, aMissingIDs );
+    TN_DEBUG2( "CThumbnailStore::GetMissingSizesL() missingSizeCount == %d", missingSizeCount );
     
     // check temp table first
     RSqlStatement stmt;
@@ -682,30 +868,19 @@
     User::LeaveIfError( stmt.Prepare( iDatabase, KThumbnailSelectTempSizeByPath ));
     TInt paramIndex = stmt.ParameterIndex( KThumbnailSqlParamPath );
     User::LeaveIfError( paramIndex );
-    User::LeaveIfError( stmt.BindText( paramIndex, aPath ));
+    User::LeaveIfError( stmt.BindText( paramIndex, *path ));
        
     TInt rowStatus = stmt.Next();
 
     TInt round = 1;
     TInt size = 0;
-    TInt id = 0;
     
     while (round <= 2)
         {
         while ( rowStatus == KSqlAtRow && missingSizeCount > 0 )
             {
             size = stmt.ColumnInt( 0 );
-            id = stmt.ColumnInt( 1 );
 			
-			TN_DEBUG2( "CThumbnailStore::GetMissingSizesAndIDsL() id == %d", id );
-            
-			//if TNId is not valid mark that some are missing so that UpdateDb is run later
-            if ( id <= 0)
-                {
-                TN_DEBUG1( "CThumbnailStore::GetMissingSizesAndIDsL() missing ID");
-                aMissingIDs = ETrue;
-                }
-            
             missingSizeCount = aMissingSizes.Count();
             for ( TInt i = 0; i < missingSizeCount; i++ )
                 {
@@ -726,6 +901,7 @@
         // all found
         if (missingSizeCount == 0)
             {
+            CleanupStack::PopAndDestroy( path );
             return;
             }
         else if (round == 1)
@@ -735,213 +911,16 @@
             User::LeaveIfError( stmt.Prepare( iDatabase, KThumbnailSelectSizeByPath ));
             paramIndex = stmt.ParameterIndex( KThumbnailSqlParamPath );
             User::LeaveIfError( paramIndex );
-            User::LeaveIfError( stmt.BindText( paramIndex, aPath ));
+            User::LeaveIfError( stmt.BindText( paramIndex, *path ));
             rowStatus = stmt.Next();    
             }
         
         round++;
         }
+    
+    CleanupStack::PopAndDestroy( path );
     }
 
-
-// ---------------------------------------------------------------------------
-// CThumbnailStore::FetchThumbnailL()
-// Fetches thumbnail image.
-// ---------------------------------------------------------------------------
-//
-TInt CThumbnailStore::FetchThumbnailL( TThumbnailId aThumbnailId, 
-        CFbsBitmap*& aThumbnail, TDesC8* & aData, TThumbnailSize aThumbnailSize, TSize &aThumbnailRealSize )
-    {
-    TN_DEBUG3( "CThumbnailStore::FetchThumbnailL(%d) aThumbnailSize == %d", aThumbnailId, aThumbnailSize );
-     delete aThumbnail;
-     aThumbnail = NULL;
-
-     RSqlStatement stmt;
-     CleanupClosePushL( stmt );
-     
-     TInt paramIndex = 0;
-     TInt found = KErrNotFound;
-     TInt rowStatus = 0;
-     TInt column = 0;
-     TInt count = 0;
-     TThumbnailSize thumbnailImage = EUnknownThumbnailSize;
-     TThumbnailSize thumbnailVideo = EUnknownThumbnailSize;
-     TThumbnailSize thumbnailAudio = EUnknownThumbnailSize;
-     TBool inTempTable( ETrue );
-     
-     if(aThumbnailSize == EFullScreenThumbnailSize)
-         {
-         thumbnailImage = EImageFullScreenThumbnailSize;
-         thumbnailVideo = EVideoFullScreenThumbnailSize;
-         thumbnailAudio = EAudioFullScreenThumbnailSize;
-         }
-     else if(aThumbnailSize == EGridThumbnailSize)
-         {
-         thumbnailImage = EImageGridThumbnailSize;
-         thumbnailVideo = EVideoGridThumbnailSize;
-         thumbnailAudio = EAudioGridThumbnailSize;
-         }
-     else if(aThumbnailSize == EListThumbnailSize)
-         {
-         thumbnailImage = EImageListThumbnailSize;
-         thumbnailVideo = EVideoListThumbnailSize;
-         thumbnailAudio = EAudioListThumbnailSize;
-         }
-     
-     if(aThumbnailSize == EFullScreenThumbnailSize ||
-        aThumbnailSize == EGridThumbnailSize ||
-        aThumbnailSize == EListThumbnailSize )
-         {
-         TN_DEBUG1( "CThumbnailStore::FetchThumbnailL() -- No DataType -- TEMP TABLE lookup" );
-         User::LeaveIfError( stmt.Prepare( iDatabase, KThumbnailSelectTempInfoByIdv2 ));
-         paramIndex = stmt.ParameterIndex( KThumbnailSqlParamId );
-         User::LeaveIfError( paramIndex );
-         User::LeaveIfError( stmt.BindInt( paramIndex, aThumbnailId ));
-             
-         paramIndex = stmt.ParameterIndex( KThumbnailSqlParamSizeImage );
-         User::LeaveIfError( paramIndex );
-         User::LeaveIfError( stmt.BindInt( paramIndex, thumbnailImage ));
-         
-         paramIndex = stmt.ParameterIndex( KThumbnailSqlParamSizeVideo );
-         User::LeaveIfError( paramIndex );
-         User::LeaveIfError( stmt.BindInt( paramIndex, thumbnailVideo ));
-         
-         paramIndex = stmt.ParameterIndex( KThumbnailSqlParamSizeAudio );
-         User::LeaveIfError( paramIndex );
-         User::LeaveIfError( stmt.BindInt( paramIndex, thumbnailAudio ));
-             
-         rowStatus = stmt.Next();
-         //if not found from temp table, look from real table
-         if(rowStatus != KSqlAtRow)
-           {
-           TN_DEBUG1( "CThumbnailStore::FetchThumbnailL() -- No DataType -- MAIN TABLE lookup" );
-           inTempTable = EFalse;
-           stmt.Close();
-           CleanupStack::PopAndDestroy( &stmt );
-           CleanupClosePushL( stmt );
-                
-           User::LeaveIfError( stmt.Prepare( iDatabase, KThumbnailSelectInfoByIdv2 ));
-             
-           paramIndex = stmt.ParameterIndex( KThumbnailSqlParamId );
-           User::LeaveIfError( paramIndex );
-           User::LeaveIfError( stmt.BindInt( paramIndex, aThumbnailId ));
-                 
-           paramIndex = stmt.ParameterIndex( KThumbnailSqlParamSizeImage );
-           User::LeaveIfError( paramIndex );
-           User::LeaveIfError( stmt.BindInt( paramIndex, thumbnailImage ));
-                    
-           paramIndex = stmt.ParameterIndex( KThumbnailSqlParamSizeVideo );
-           User::LeaveIfError( paramIndex );
-           User::LeaveIfError( stmt.BindInt( paramIndex, thumbnailVideo ));
-                    
-           paramIndex = stmt.ParameterIndex( KThumbnailSqlParamSizeAudio );
-           User::LeaveIfError( paramIndex );
-           User::LeaveIfError( stmt.BindInt( paramIndex, thumbnailAudio ));
-             
-           rowStatus = stmt.Next();
-           }               
-         }
-     else
-         {
-         TN_DEBUG1( "CThumbnailStore::FetchThumbnailL() -- TEMP TABLE lookup" );
-         User::LeaveIfError( stmt.Prepare( iDatabase, KThumbnailSelectTempInfoById ));
-         paramIndex = stmt.ParameterIndex( KThumbnailSqlParamId );
-         User::LeaveIfError( paramIndex );
-         User::LeaveIfError( stmt.BindInt( paramIndex, aThumbnailId ));
-     
-         paramIndex = stmt.ParameterIndex( KThumbnailSqlParamSize );
-         User::LeaveIfError( paramIndex );
-         User::LeaveIfError( stmt.BindInt( paramIndex, aThumbnailSize ));
-     
-         rowStatus = stmt.Next();
-
-         //if not found from temp table, look from real table
-         if(rowStatus != KSqlAtRow)
-            {
-            TN_DEBUG1( "CThumbnailStore::FetchThumbnailL() -- MAIN TABLE lookup" );
-            inTempTable = EFalse;
-            stmt.Close();
-            CleanupStack::PopAndDestroy( &stmt );
-            CleanupClosePushL( stmt );
-        
-            User::LeaveIfError( stmt.Prepare( iDatabase, KThumbnailSelectInfoById ));
-     
-            paramIndex = stmt.ParameterIndex( KThumbnailSqlParamId );
-            User::LeaveIfError( paramIndex );
-            User::LeaveIfError( stmt.BindInt( paramIndex, aThumbnailId ));
-         
-            paramIndex = stmt.ParameterIndex( KThumbnailSqlParamSize );
-            User::LeaveIfError( paramIndex );
-            User::LeaveIfError( stmt.BindInt( paramIndex, aThumbnailSize ));
-     
-            rowStatus = stmt.Next();
-            }
-         }
-     if(rowStatus == KSqlAtRow)
-        {
-         TN_DEBUG1( "CThumbnailStore::FetchThumbnailL() -- thumbnail found" );
-         // Check whether blacklisted thumbnail entry modified. 
-         // If thumbnail is marked as blacklisted and timestamp has 
-         // changed, delete thumbnails from tables and leave with 
-         // KErrNotFound to get thumbnail regenerated.
-         column = 4;
-         TInt flags = stmt.ColumnInt( column );
-         if( flags & KThumbnailDbFlagBlacklisted )
-             {
-             TBool modified = EFalse;
-             CheckModifiedByIdL( aThumbnailId, inTempTable, modified );
-             if( modified )
-                 {
-                 // Close db to get deletion of thumbnails executed.
-                 stmt.Close();
-                 CleanupStack::PopAndDestroy( &stmt );
-                 DeleteThumbnailsL( aThumbnailId );
-                 User::Leave( KErrNotFound );
-                 }
-             else
-                 {
-                 User::Leave( KErrCompletion );
-                 }
-             }
-         
-         found = KErrNone;
-         count = 0;
-         count++;
-         column = 0;
-         TInt format = stmt.ColumnInt( column++ );  
-         if(format == 1 /*TThumbnailFormat::EThumbnailFormatJpeg */ )
-             {
-             TPtrC8 ptr = stmt.ColumnBinaryL( column++ );
-             HBufC8* data = ptr.AllocL() ;
-             aThumbnail = NULL;
-             aData = data;     
-             
-          } else {
-             TPtrC8 ptr = stmt.ColumnBinaryL( column );
-             RDesReadStream stream( ptr );
-             aThumbnail = new( ELeave )CFbsBitmap();
-             aThumbnail->InternalizeL( stream );
-             aData = NULL;
-          }
-         
-        //fetch real size of TN
-        column = 2;
-        aThumbnailRealSize.iWidth = stmt.ColumnInt( column++ );
-        aThumbnailRealSize.iHeight = stmt.ColumnInt( column );
-        }
-     else
-         {
-         TN_DEBUG1( "CThumbnailStore::FetchThumbnailL() -- thumbnail NOT found" );
-         }
-         
-     stmt.Close();
-     CleanupStack::PopAndDestroy( &stmt );
-
-     User::LeaveIfError( found );
-     return found;
-    }
-
-
 // ---------------------------------------------------------------------------
 // CThumbnailStore::FetchThumbnailL()
 // Fetches thumbnail image.
@@ -953,7 +932,11 @@
     TN_DEBUG3( "CThumbnailStore::FetchThumbnailL(%S) aThumbnailSize==%d", &aPath, aThumbnailSize );
     delete aThumbnail;
     aThumbnail = NULL;
-
+    
+    HBufC* path = aPath.AllocLC();
+    TPtr ptr(path->Des());
+    StripDriveLetterL( ptr );
+    
     RSqlStatement stmt;
     CleanupClosePushL( stmt );
     
@@ -968,13 +951,13 @@
 
 #ifdef _DEBUG
     TPtrC errorMsg = iDatabase.LastErrorMessage();
-    TN_DEBUG2( "CThumbnailStore::FetchThumbnailL() %S" , &errorMsg);
+    TN_DEBUG2( "CThumbnailStore::FetchThumbnailL() KThumbnailSelectTempInfoByPath %S" , &errorMsg);
 #endif
     User::LeaveIfError( err );
     
     paramIndex = stmt.ParameterIndex( KThumbnailSqlParamPath );
     User::LeaveIfError( paramIndex );
-    User::LeaveIfError( stmt.BindText( paramIndex, aPath ));
+    User::LeaveIfError( stmt.BindText( paramIndex, *path ));
     
     paramIndex = stmt.ParameterIndex( KThumbnailSqlParamSize );
     User::LeaveIfError( paramIndex );
@@ -995,7 +978,7 @@
     
         paramIndex = stmt.ParameterIndex( KThumbnailSqlParamPath );
         User::LeaveIfError( paramIndex );
-        User::LeaveIfError( stmt.BindText( paramIndex, aPath ));
+        User::LeaveIfError( stmt.BindText( paramIndex, *path ));
         
         paramIndex = stmt.ParameterIndex( KThumbnailSqlParamSize );
         User::LeaveIfError( paramIndex );
@@ -1013,7 +996,7 @@
         // KErrNotFound to get thumbnail regenerated.
         column = 4;
         TInt flags = stmt.ColumnInt( column );
-        if( flags & KThumbnailDbFlagBlacklisted && aPath.Length() )
+        if( flags & KThumbnailDbFlagBlacklisted && (*path).Length() )
             {
             TBool modified = EFalse;
             CheckModifiedByPathL( aPath, inTempTable, modified );
@@ -1022,7 +1005,7 @@
                 // Close db to get deletion of thumbnails executed.
                 stmt.Close();
                 CleanupStack::PopAndDestroy( &stmt );
-                DeleteThumbnailsL( aPath );
+                DeleteThumbnailsL( *path );
                 User::Leave( KErrNotFound );
                 }
             else
@@ -1064,7 +1047,8 @@
         
     stmt.Close();
     CleanupStack::PopAndDestroy( &stmt );
-
+    CleanupStack::PopAndDestroy( path );
+    
     User::LeaveIfError( found );
     }
 
@@ -1072,275 +1056,180 @@
 // Delete thumbnails for given object file by Path
 // -----------------------------------------------------------------------------
 //
-void CThumbnailStore::DeleteThumbnailsL( const TDesC& aPath )
+void CThumbnailStore::DeleteThumbnailsL( const TDesC& aPath, TBool aForce, 
+                                         TBool aTransaction )
     {
-    RThumbnailTransaction transaction( iDatabase );
-    CleanupClosePushL( transaction );
-    transaction.BeginL();
-    RSqlStatement stmt;
-    CleanupClosePushL( stmt );
-    
+    TN_DEBUG2( "CThumbnailStore::DeleteThumbnailsL(%S)", &aPath );
+#ifdef _DEBUG
+    TTime aStart, aStop;
+    aStart.UniversalTime();
+#endif
     TInt paramIndex = 0;
     TInt paramIndex1 = 0;
     TInt paramIndex2 = 0;
     TInt rowStatus = 0;
     TInt column = 0;
-    TInt rowid = 0;
-    TInt deleteCount = 0;
+    TInt64 rowid = 0;
+    TInt count = 0;
+
+    HBufC* path = aPath.AllocLC();
+    TPtr ptr(path->Des());
+    StripDriveLetterL( ptr );
     
+    RThumbnailTransaction transaction( iDatabase );
+    if (aTransaction)
+        {
+        CleanupClosePushL( transaction );    
+        transaction.BeginL();
+        }
+        
+    RSqlStatement stmt;
+    RSqlStatement stmt_info;
+    RSqlStatement stmt_infodata;
+    
+    CleanupClosePushL( stmt );
+    CleanupClosePushL( stmt_info );
+    CleanupClosePushL( stmt_infodata );
+        
     TN_DEBUG1( "CThumbnailStore::DeleteThumbnailsByPathL() -- TEMP TABLE lookup" );
-    TInt err = stmt.Prepare( iDatabase, KTempThumbnailSqlSelectRowIDInfoByPath);
-    User::LeaveIfError( err );
+    
+    User::LeaveIfError( stmt.Prepare( iDatabase, KTempThumbnailSqlSelectRowIDInfoByPath) );
+    User::LeaveIfError( stmt_info.Prepare( iDatabase, KTempThumbnailSqlDeleteInfoByPath) );
+    User::LeaveIfError( stmt_infodata.Prepare( iDatabase, KTempThumbnailSqlDeleteInfoDataByPath) );
     
     paramIndex = stmt.ParameterIndex( KThumbnailSqlParamPath );
     User::LeaveIfError( paramIndex );
-    User::LeaveIfError( stmt.BindText( paramIndex, aPath ));
+    User::LeaveIfError( stmt.BindText( paramIndex, *path ));
     
     rowStatus = stmt.Next();
-    RSqlStatement stmt_info;
-    CleanupClosePushL( stmt_info );
-    err = stmt_info.Prepare( iDatabase, KTempThumbnailSqlDeleteInfoByPath);
-    RSqlStatement stmt_infodata;
-    CleanupClosePushL( stmt_infodata );
-    err = stmt_infodata.Prepare( iDatabase, KTempThumbnailSqlDeleteInfoDataByPath);
-    
     
     while(rowStatus == KSqlAtRow)
-       {  
-       rowid = stmt.ColumnInt( column ); 
-       paramIndex1 = stmt_info.ParameterIndex( KThumbnailSqlParamRowID );
-       User::LeaveIfError( paramIndex1 );
-       User::LeaveIfError( stmt_info.BindInt( paramIndex1, rowid ));
-       
-       deleteCount = stmt_info.Exec();
-       stmt_info.Reset();
-       User::LeaveIfError( deleteCount );
-             
-       paramIndex2 = stmt_infodata.ParameterIndex( KThumbnailSqlParamRowID );
-       User::LeaveIfError( paramIndex2 );
-       User::LeaveIfError( stmt_infodata.BindInt( paramIndex2, rowid ));
-             
-       deleteCount = stmt_infodata.Exec();
-       stmt_infodata.Reset();
-       User::LeaveIfError( deleteCount );
-       
-       TN_DEBUG1( "CThumbnailStore::DeleteThumbnailsByPathL() -- TEMP TABLE lookup - thumbnail deleted" );
-       
-       // fetch another row (temp table rowIDs are updated immediately)
-       stmt.Reset();
-       
-       paramIndex = stmt.ParameterIndex( KThumbnailSqlParamPath );
-       User::LeaveIfError( paramIndex );
-       User::LeaveIfError( stmt.BindText( paramIndex, aPath ));
+        {  
+        rowid = stmt.ColumnInt64( column ); 
+        paramIndex1 = stmt_info.ParameterIndex( KThumbnailSqlParamRowID );
+        User::LeaveIfError( paramIndex1 );
+        User::LeaveIfError( stmt_info.BindInt64( paramIndex1, rowid ));
        
-       rowStatus = stmt.Next();   
-       }
-    stmt_infodata.Close();
-    stmt_info.Close();
-    CleanupStack::PopAndDestroy( &stmt_infodata );
-    CleanupStack::PopAndDestroy( &stmt_info );
-    
-
-    //look from real table 
-    TN_DEBUG1( "CThumbnailStore::DeleteThumbnailByPathL() -- MAIN TABLE lookup" );
-    stmt.Close();
-    CleanupStack::PopAndDestroy( &stmt );
-    CleanupClosePushL( stmt );   
-    User::LeaveIfError( stmt.Prepare( iDatabase, KThumbnailSqlSelectRowIDInfoByPath ));
-    
-    User::LeaveIfError( err );
-    
-    paramIndex = stmt.ParameterIndex( KThumbnailSqlParamPath );
-    User::LeaveIfError( paramIndex );
-    User::LeaveIfError( stmt.BindText( paramIndex, aPath ));
-         
-    rowStatus = stmt.Next();   
-    CleanupClosePushL( stmt_info );
-    err = stmt_info.Prepare( iDatabase, KThumbnailSqlDeleteInfoByPath);
-    CleanupClosePushL( stmt_infodata );
-    err = stmt_infodata.Prepare( iDatabase, KThumbnailSqlDeleteInfoDataByPath);
+        TInt err = stmt_info.Exec();
+        stmt_info.Reset();
+        User::LeaveIfError( err );
+             
+        paramIndex2 = stmt_infodata.ParameterIndex( KThumbnailSqlParamRowID );
+        User::LeaveIfError( paramIndex2 );
+        User::LeaveIfError( stmt_infodata.BindInt64( paramIndex2, rowid ));
+             
+        err = stmt_infodata.Exec();
+        stmt_infodata.Reset();
+        User::LeaveIfError( err );
+        
+        TN_DEBUG1( "CThumbnailStore::DeleteThumbnailsByPathL() -- TEMP TABLE lookup - thumbnail deleted" );
        
+        // fetch another row (temp table rowIDs are updated immediately)
+        stmt.Reset();
        
-    while(rowStatus == KSqlAtRow)
-       { 
-       rowid = stmt.ColumnInt( column ); 
-       paramIndex1 = stmt_info.ParameterIndex( KThumbnailSqlParamRowID );
-       User::LeaveIfError( paramIndex1 );
-       User::LeaveIfError( stmt_info.BindInt( paramIndex1, rowid ));
-          
-       deleteCount = stmt_info.Exec();
-       stmt_info.Reset();
-       User::LeaveIfError( deleteCount );
-                
-       paramIndex2 = stmt_infodata.ParameterIndex( KThumbnailSqlParamRowID );  
-       User::LeaveIfError( paramIndex2 );
-       User::LeaveIfError( stmt_infodata.BindInt( paramIndex2, rowid ));
-                
-       deleteCount = stmt_infodata.Exec();
-       stmt_infodata.Reset();
-       User::LeaveIfError( deleteCount );
+        paramIndex = stmt.ParameterIndex( KThumbnailSqlParamPath );
+        User::LeaveIfError( paramIndex );
+        User::LeaveIfError( stmt.BindText( paramIndex, *path ));
        
-       TN_DEBUG1( "CThumbnailStore::DeleteThumbnailByPathL() -- MAIN TABLE lookup - thumbnail deleted" );
-       
-       rowStatus = stmt.Next();
-       }
+        rowStatus = stmt.Next();   
+        }
     
     stmt_infodata.Close();
     stmt_info.Close();
     stmt.Close();
+    
     CleanupStack::PopAndDestroy( &stmt_infodata );
     CleanupStack::PopAndDestroy( &stmt_info );
-    CleanupStack::PopAndDestroy( &stmt );    
-    transaction.CommitL();
-    CleanupStack::PopAndDestroy( &transaction );
-    }
-
-// -----------------------------------------------------------------------------
-// Delete thumbnails for given object file by Id
-// -----------------------------------------------------------------------------
-//
-void CThumbnailStore::DeleteThumbnailsL( const TThumbnailId& aTNId )
-    {
-#ifdef _DEBUG
-    TTime aStart, aStop;
-    aStart.UniversalTime();
-#endif
+    CleanupStack::PopAndDestroy( &stmt );
+    
+    // if forcing instant delete
+    if (aForce)
+        {
+        //look from real table 
+        TN_DEBUG1( "CThumbnailStore::DeleteThumbnailByPathL() -- MAIN TABLE lookup" );
         
-    TInt paramIndex = 0;
-    TInt paramIndex1 = 0;
-    TInt paramIndex2 = 0;
-    TInt rowStatus = 0;
-    TInt column = 0;
-    TInt rowid = 0;
-    TInt deleteCount = 0;
-      
-    RThumbnailTransaction transaction( iDatabase );
-    CleanupClosePushL( transaction );
-    transaction.BeginL();
-    RSqlStatement stmt;
-    CleanupClosePushL( stmt );
-    
-    TN_DEBUG1( "CThumbnailStore::DeleteThumbnailsByIdL() -- TEMP TABLE lookup" );
-    TInt err = stmt.Prepare( iDatabase, KTempThumbnailSqlSelectRowIDInfoByID);
-    User::LeaveIfError( err );
+        CleanupClosePushL( stmt );
+        CleanupClosePushL( stmt_info );
+        CleanupClosePushL( stmt_infodata );
         
-    paramIndex = stmt.ParameterIndex( KThumbnailSqlParamId );
-    User::LeaveIfError( paramIndex );
-    User::LeaveIfError( stmt.BindInt( paramIndex, aTNId ));
-        
-    rowStatus = stmt.Next();
-    RSqlStatement stmt_info;
-    CleanupClosePushL( stmt_info );
-    err = stmt_info.Prepare( iDatabase, KTempThumbnailSqlDeleteInfoByID);
-    RSqlStatement stmt_infodata;
-    CleanupClosePushL( stmt_infodata );
-    err = stmt_infodata.Prepare( iDatabase, KTempThumbnailSqlDeleteInfoDataByID);
-        
-        
-    while(rowStatus == KSqlAtRow)
-       {  
-       rowid = stmt.ColumnInt( column ); 
-       paramIndex1 = stmt_info.ParameterIndex( KThumbnailSqlParamRowID );
-       User::LeaveIfError( paramIndex1 );
-       User::LeaveIfError( stmt_info.BindInt( paramIndex1, rowid ));
+        User::LeaveIfError( stmt.Prepare( iDatabase, KThumbnailSqlSelectRowIDInfoByPath ));
+        User::LeaveIfError( stmt_info.Prepare( iDatabase, KThumbnailSqlDeleteInfoByPath) );
+        User::LeaveIfError( stmt_infodata.Prepare( iDatabase, KThumbnailSqlDeleteInfoDataByPath) );
+
+        paramIndex = stmt.ParameterIndex( KThumbnailSqlParamPath );
+        User::LeaveIfError( paramIndex );
+        User::LeaveIfError( stmt.BindText( paramIndex, *path ));
+             
+        rowStatus = stmt.Next();   
            
-       err = stmt_info.Exec();
-       stmt_info.Reset();
-       User::LeaveIfError( err );
-                 
-       paramIndex2 = stmt_infodata.ParameterIndex( KThumbnailSqlParamRowID );
-       User::LeaveIfError( paramIndex2 );
-       User::LeaveIfError( stmt_infodata.BindInt( paramIndex2, rowid ));
-                 
-       err = stmt_infodata.Exec();
-       stmt_infodata.Reset();
-       User::LeaveIfError( err );
-       deleteCount++;
-       
-       TN_DEBUG1( "CThumbnailStore::DeleteThumbnailsByIdL() -- TEMP TABLE lookup - thumbnail deleted" );
-       
-       // fetch another row (temp table rowIDs are updated immediately)
-       stmt.Reset();
-       
-       paramIndex = stmt.ParameterIndex( KThumbnailSqlParamId );
-       User::LeaveIfError( paramIndex );
-       User::LeaveIfError( stmt.BindInt( paramIndex, aTNId ));
-       
-       rowStatus = stmt.Next();    
-       }
-    
-    stmt_infodata.Close();
-    stmt_info.Close();
-    CleanupStack::PopAndDestroy( &stmt_infodata );
-    CleanupStack::PopAndDestroy( &stmt_info );
-        
-    
-    //look from real table       
-    TN_DEBUG1( "CThumbnailStore::DeleteThumbnailByIdL() -- MAIN TABLE lookup" );
-    stmt.Close();
-    CleanupStack::PopAndDestroy( &stmt );
-    CleanupClosePushL( stmt );   
-    User::LeaveIfError( stmt.Prepare( iDatabase, KThumbnailSqlSelectRowIDInfoByID ));
-        
-    User::LeaveIfError( err );
+        while(rowStatus == KSqlAtRow)
+            { 
+            rowid = stmt.ColumnInt64( column ); 
+            paramIndex1 = stmt_info.ParameterIndex( KThumbnailSqlParamRowID );
+            User::LeaveIfError( paramIndex1 );
+            User::LeaveIfError( stmt_info.BindInt64( paramIndex1, rowid ));
+               
+            TInt err = stmt_info.Exec();
+            stmt_info.Reset();
+            User::LeaveIfError( err );
+                    
+            paramIndex2 = stmt_infodata.ParameterIndex( KThumbnailSqlParamRowID );  
+            User::LeaveIfError( paramIndex2 );
+            User::LeaveIfError( stmt_infodata.BindInt64( paramIndex2, rowid ));
+                    
+            err = stmt_infodata.Exec();
+            stmt_infodata.Reset();
+            User::LeaveIfError( err );
+           
+            TN_DEBUG1( "CThumbnailStore::DeleteThumbnailByPathL() -- MAIN TABLE lookup - thumbnail deleted" );
+            
+            rowStatus = stmt.Next();
+            }
         
-    paramIndex = stmt.ParameterIndex( KThumbnailSqlParamId );
-    User::LeaveIfError( paramIndex );
-    User::LeaveIfError( stmt.BindInt( paramIndex, aTNId ));
-             
-    rowStatus = stmt.Next();   
-    CleanupClosePushL( stmt_info );
-    err = stmt_info.Prepare( iDatabase, KThumbnailSqlDeleteInfoByID);
-    CleanupClosePushL( stmt_infodata );
-    err = stmt_infodata.Prepare( iDatabase, KThumbnailSqlDeleteInfoDataByID);
-           
-           
-    while(rowStatus == KSqlAtRow)
-       { 
-       rowid = stmt.ColumnInt( column ); 
-       paramIndex1 = stmt_info.ParameterIndex( KThumbnailSqlParamRowID );
-       User::LeaveIfError( paramIndex1 );
-       User::LeaveIfError( stmt_info.BindInt( paramIndex1, rowid ));
-              
-       err = stmt_info.Exec();
-       stmt_info.Reset();
-       User::LeaveIfError( err );
-                    
-       paramIndex2 = stmt_infodata.ParameterIndex( KThumbnailSqlParamRowID );  
-       User::LeaveIfError( paramIndex2 );
-       User::LeaveIfError( stmt_infodata.BindInt( paramIndex2, rowid ));
-                    
-       err = stmt_infodata.Exec();
-       stmt_infodata.Reset();
-       User::LeaveIfError( err );
-       deleteCount++;
-       
-       TN_DEBUG1( "CThumbnailStore::DeleteThumbnailByIdL() -- MAIN TABLE lookup - thumbnail deleted" );
-       
-       rowStatus = stmt.Next();
-       }
+        stmt_infodata.Close();
+        stmt_info.Close();
+        CleanupStack::PopAndDestroy( &stmt_infodata );
+        CleanupStack::PopAndDestroy( &stmt_info );
+        } 
+    else
+        {
+        // only add path to deleted table
+        CleanupClosePushL( stmt );  
+        User::LeaveIfError( stmt.Prepare( iDatabase, KThumbnailSqlInsertDeleted ) );
         
-    stmt_infodata.Close();
-    stmt_info.Close();
+        paramIndex = stmt.ParameterIndex( KThumbnailSqlParamPath );
+        User::LeaveIfError( paramIndex );
+        User::LeaveIfError( stmt.BindText( paramIndex, *path ));
+        
+        count = stmt.Exec();
+        }
+    
     stmt.Close();
-    CleanupStack::PopAndDestroy( &stmt_infodata );
-    CleanupStack::PopAndDestroy( &stmt_info );
     CleanupStack::PopAndDestroy( &stmt );    
-    transaction.CommitL();
-    CleanupStack::PopAndDestroy( &transaction );
+    
+    if (aTransaction)
+        {
+        transaction.CommitL();
+        CleanupStack::PopAndDestroy( &transaction );
+        }
     
 #ifdef _DEBUG
     aStop.UniversalTime();
-    TN_DEBUG2( "CThumbnailStore::DeleteThumbnailsByIdL() took %d ms", (TInt)aStop.MicroSecondsFrom(aStart).Int64()/1000);
+    TN_DEBUG2( "CThumbnailStore::DeleteThumbnailByPathL() took %d ms", (TInt)aStop.MicroSecondsFrom(aStart).Int64()/1000);
 #endif
     
-    if(!deleteCount)
+    // start maintenance if rows in main table were marked
+    if (!aForce && count > 0)
         {
-        User::Leave(KErrNotFound);
+        TN_DEBUG2( "CThumbnailStore::DeleteThumbnailByPathL() -- MAIN TABLE lookup - %d rows marked deleted", count);
+        
+        iDeleteThumbs = ETrue;
+        iActivityManager->Start();
         }
+    
+    CleanupStack::PopAndDestroy( path );
     }
 
-
 // ---------------------------------------------------------------------------
 // CThumbnailStore::PersistentSizes()
 // ---------------------------------------------------------------------------
@@ -1388,8 +1277,37 @@
     TInt err_tempinfo = iDatabase.Exec( KThumbnailMoveFromTempInfoToMainTable );
     TN_DEBUG2("CThumbnailStore::FlushCacheTable() KThumbnailMoveFromTempInfoToMainTable %d", err_tempinfo);
     
+#ifdef _DEBUG
+    if(err_tempinfo < 0)
+        {
+        TPtrC errorMsg = iDatabase.LastErrorMessage();
+        TN_DEBUG2( "CThumbnailStore::FlushCacheTable() lastError %S", &errorMsg);
+        }
+#endif
+    
+    if(err_tempinfo == KSqlErrCorrupt || err_tempinfo == KErrCorrupt )
+        {
+        TRAP_IGNORE(RecreateDatabaseL(ETrue));
+        TRAP_IGNORE(OpenDatabaseL());
+        return;
+        }
+    
     TInt err_tempdata = iDatabase.Exec( KThumbnailMoveFromTempDataToMainTable );
-    TN_DEBUG2("CThumbnailStore::FlushCacheTable() KThumbnailMoveFromTempDataToMainTable %d", err_tempdata);
+    
+#ifdef _DEBUG
+    if(err_tempdata < 0)
+        {
+        TPtrC errorMsg2 = iDatabase.LastErrorMessage();
+        TN_DEBUG2( "CThumbnailStore::FlushCacheTable() KThumbnailMoveFromTempDataToMainTable %S", &errorMsg2);
+        }
+#endif
+    if(err_tempdata == KSqlErrCorrupt || err_tempdata == KErrCorrupt )
+        {
+        TRAP_IGNORE(RecreateDatabaseL(ETrue));
+        TRAP_IGNORE(OpenDatabaseL());
+        return;
+        }
+    
     
     TInt err_delinfo = iDatabase.Exec( KThumbnailDeleteFromTempInfoTable );
     TN_DEBUG2("CThumbnailStore::FlushCacheTable() KThumbnailDeleteFromTempInfoTable %d", err_delinfo);
@@ -1417,572 +1335,6 @@
     TN_DEBUG1("CThumbnailStore::FlushCacheTable() out");
     }
 
-
-// -----------------------------------------------------------------------------
-// Find store for thumbnails by Id
-// -----------------------------------------------------------------------------
-//
-void CThumbnailStore::FindStoreL(TThumbnailId aThumbnailId)
-    {
-    TN_DEBUG2( "CThumbnailStore::FindStore( %d )", aThumbnailId );
-     RSqlStatement stmt;
-     CleanupClosePushL( stmt );
-         
-     TInt paramIndex = 0;
-     TInt found = KErrNotFound;
-     TInt rowStatus = 0;
-         
-     TN_DEBUG1( "CThumbnailStore::FindStore() -- TEMP TABLE lookup" );
-     User::LeaveIfError( stmt.Prepare( iDatabase, KTempThumbnailSqlSelectRowIDInfoByID ));
-     paramIndex = stmt.ParameterIndex( KThumbnailSqlParamId );
-     User::LeaveIfError( paramIndex );
-     User::LeaveIfError( stmt.BindInt( paramIndex, aThumbnailId ));
-         
-     rowStatus = stmt.Next();
-
-    //if not found from temp table, look from real table
-    if(rowStatus != KSqlAtRow)
-        {
-        TN_DEBUG1( "CThumbnailStore::FindStore() -- MAIN TABLE lookup" );
-        stmt.Close();
-        CleanupStack::PopAndDestroy( &stmt );
-        CleanupClosePushL( stmt );
-            
-        User::LeaveIfError( stmt.Prepare( iDatabase, KThumbnailSqlSelectRowIDInfoByID ));
-         
-        paramIndex = stmt.ParameterIndex( KThumbnailSqlParamId );
-        User::LeaveIfError( paramIndex );
-        User::LeaveIfError( stmt.BindInt( paramIndex, aThumbnailId ));
-            
-        rowStatus = stmt.Next();
-        }
-
-    if( rowStatus == KSqlAtRow )
-        {
-        TN_DEBUG1( "CThumbnailStore::FindStore() -- thumbnail found" );
-        found = KErrNone;
-        }
-    else
-        {
-        TN_DEBUG1( "CThumbnailStore::FindStore() -- thumbnail NOT found" );
-        }
-             
-    stmt.Close();
-    CleanupStack::PopAndDestroy( &stmt );
-
-    User::LeaveIfError( found );
-    }
-
-// -----------------------------------------------------------------------------
-// Updates path in current store by Id
-// -----------------------------------------------------------------------------
-//
-TBool CThumbnailStore::UpdateStoreL( TThumbnailId aItemId, const TDesC& aNewPath )
-    {
-    TN_DEBUG3( "CThumbnailStore::UpdateStore( %d, %S) by ID", aItemId, &aNewPath);
-
-    TBool doUpdate(EFalse);
-    TPath oldPath;
-    TInt column = 0;
-    
-    RSqlStatement stmt;
-    CleanupClosePushL( stmt );
-       
-    //check if path needs updating in temp table
-    User::LeaveIfError( stmt.Prepare( iDatabase, KThumbnailSelectTempPathByID ));
-    
-    TInt paramIndex = stmt.ParameterIndex( KThumbnailSqlParamId );
-    User::LeaveIfError( paramIndex );
-    User::LeaveIfError( stmt.BindInt( paramIndex, aItemId ));
-     
-    TInt rowStatus = stmt.Next();
-
-     //if not found from temp table, look from real table
-     if(rowStatus != KSqlAtRow)
-         {
-         stmt.Close();
-         CleanupStack::PopAndDestroy( &stmt );
-         CleanupClosePushL( stmt );
-         
-         //check if path needs updating in main table
-         User::LeaveIfError( stmt.Prepare( iDatabase, KThumbnailSelectPathByID ));
-         
-         paramIndex = stmt.ParameterIndex( KThumbnailSqlParamId );
-         User::LeaveIfError( paramIndex );
-         User::LeaveIfError( stmt.BindInt( paramIndex, aItemId ));
-          
-         rowStatus = stmt.Next();
-         }
-     
-     if(rowStatus == KSqlAtRow)
-         {
-           TN_DEBUG1( "CThumbnailStore::UpdateStore() -- matching TN ID found" );
-           oldPath = stmt.ColumnTextL(column);
-            
-            if(oldPath.CompareF(aNewPath) != 0)
-                {
-                TN_DEBUG1( "CThumbnailStore::UpdateStore() -- path no match" );
-                doUpdate = ETrue;
-                }
-            else
-                {
-                TN_DEBUG1( "CThumbnailStore::UpdateStore() -- path match, skip..." );
-                }
-         }
-     
-    stmt.Close();
-    CleanupStack::PopAndDestroy( &stmt );
-        
-    if(!doUpdate)
-        {
-        TN_DEBUG2( "CThumbnailStore::UpdateStore() -- no need to update old path=%S", &oldPath );
-        return EFalse;
-        }
-    
-    //Encapsulate update to Transaction
-    RThumbnailTransaction transaction( iDatabase );
-    CleanupClosePushL( transaction );
-    transaction.BeginL();
-	
-    CleanupClosePushL( stmt );
-     
-    TN_DEBUG1( "CThumbnailStore::UpdateStore() -- do temp path update" );
-
-    User::LeaveIfError( stmt.Prepare( iDatabase, KTempThumbnailSqlUpdateById ));
-    
-    paramIndex = stmt.ParameterIndex( KThumbnailSqlParamPath );
-    User::LeaveIfError( paramIndex );
-    User::LeaveIfError( stmt.BindText( paramIndex, aNewPath ));
-       
-    paramIndex = stmt.ParameterIndex( KThumbnailSqlParamId );
-    User::LeaveIfError( paramIndex );
-    User::LeaveIfError( stmt.BindInt( paramIndex, aItemId ));
-    User::LeaveIfError( stmt.Exec());
-    
-    stmt.Close();
-    CleanupStack::PopAndDestroy( &stmt );
-    CleanupClosePushL( stmt );
-    
-    TN_DEBUG1( "CThumbnailStore::UpdateStore() -- do main table path update" );
-             
-    User::LeaveIfError( stmt.Prepare( iDatabase, KThumbnailSqlUpdateById ));
-                
-    paramIndex = stmt.ParameterIndex( KThumbnailSqlParamPath );
-    User::LeaveIfError( paramIndex );
-    User::LeaveIfError( stmt.BindText( paramIndex, aNewPath ));
-
-    paramIndex = stmt.ParameterIndex( KThumbnailSqlParamId );
-    User::LeaveIfError( paramIndex );
-    User::LeaveIfError( stmt.BindInt( paramIndex, aItemId ));  
-            
-    User::LeaveIfError( stmt.Exec());   
-    CleanupStack::PopAndDestroy( &stmt );
-    
-    // Commit transaction
-    transaction.CommitL();
-    CleanupStack::PopAndDestroy( &transaction );
-    
-    return ETrue;
-    }
-
-// -----------------------------------------------------------------------------
-// Update IDs by Path
-// -----------------------------------------------------------------------------
-//
-void CThumbnailStore::UpdateStoreL( const TDesC& aPath, TThumbnailId aNewId )
-    {
-    TN_DEBUG3( "CThumbnailStore::UpdateStore( %S, %d ) by Path", &aPath, aNewId);
-    
-#ifdef _DEBUG
-    TTime aStart, aStop;
-    aStart.UniversalTime();
-#endif
-    
-    //Encapsulate update to Transaction
-    RThumbnailTransaction transaction( iDatabase );
-    CleanupClosePushL( transaction );
-    transaction.BeginL();
-    
-    RSqlStatement stmt;
-    CleanupClosePushL( stmt );
-       
-    TN_DEBUG1( "CThumbnailStore::UpdateStoreL() -- do temp ID update" );
-    
-    TInt err = stmt.Prepare( iDatabase, KTempThumbnailUpdateIdByPath );
-    
-#ifdef _DEBUG
-    TPtrC errorMsg = iDatabase.LastErrorMessage();
-    TN_DEBUG2( "CThumbnailStore::UpdateStoreL() KTempThumbnailUpdateIdByPath %S" , &errorMsg);
-#endif
-    
-    User::LeaveIfError( err );
-    
-    TInt paramIndex = stmt.ParameterIndex( KThumbnailSqlParamId );
-    User::LeaveIfError( paramIndex );
-    User::LeaveIfError( stmt.BindInt( paramIndex, aNewId ));
-    
-    paramIndex = stmt.ParameterIndex( KThumbnailSqlParamPath );
-    User::LeaveIfError( paramIndex );
-    User::LeaveIfError( stmt.BindText( paramIndex, aPath ));
-    
-    err =  stmt.Exec();
-    
-    TN_DEBUG2( "CThumbnailStore::UpdateStoreL() err==%d", err );
-    
-    stmt.Close();
-    CleanupStack::PopAndDestroy( &stmt );
-    CleanupClosePushL( stmt );
-    
-    TN_DEBUG1( "CThumbnailStore::UpdateStoreL() -- do main table ID update" );
-    
-    err = stmt.Prepare( iDatabase, KThumbnailUpdateIdByPath );
-    
-#ifdef _DEBUG
-    TPtrC errorMsg2 = iDatabase.LastErrorMessage();
-    TN_DEBUG2( "CThumbnailStore::UpdateStoreL() KThumbnailUpdateIdByPath %S" , &errorMsg2);
-#endif    
-    
-    User::LeaveIfError( err );
-    
-    paramIndex = stmt.ParameterIndex( KThumbnailSqlParamId );
-    User::LeaveIfError( paramIndex );
-    User::LeaveIfError( stmt.BindInt( paramIndex, aNewId ));
-    
-    paramIndex = stmt.ParameterIndex( KThumbnailSqlParamPath );
-    User::LeaveIfError( paramIndex );
-    User::LeaveIfError( stmt.BindText( paramIndex, aPath ));
-    
-    err =  stmt.Exec();
-    
-    TN_DEBUG2( "CThumbnailStore::UpdateStoreL() err==%d", err );
-    
-    stmt.Close();
-    CleanupStack::PopAndDestroy( &stmt ); 
-    
-    // Commit transaction
-    transaction.CommitL();
-    CleanupStack::PopAndDestroy( &transaction );
-    
-#ifdef _DEBUG
-    aStop.UniversalTime();
-    TN_DEBUG2( "CThumbnailStore::UpdateStoreL() took %d ms", (TInt)aStop.MicroSecondsFrom(aStart).Int64()/1000);
-#endif
-    }
-
-// -----------------------------------------------------------------------------
-// Checks if given modification timestamp is newer than in DB
-// -----------------------------------------------------------------------------
-//
-TBool CThumbnailStore::CheckModifiedL( const TThumbnailId aItemId, const TInt64 aModified )
-    {
-    TN_DEBUG2( "CThumbnailStore::CheckModifiedL( %d )", aItemId);
-
-    TInt column = 0;
-    
-    RSqlStatement stmt;
-    CleanupClosePushL( stmt );
-       
-    User::LeaveIfError( stmt.Prepare( iDatabase, KThumbnailSelectTempModifiedByID ));
-    
-    TInt paramIndex = stmt.ParameterIndex( KThumbnailSqlParamId );
-    User::LeaveIfError( paramIndex );
-    User::LeaveIfError( stmt.BindInt( paramIndex, aItemId ));
-     
-    TInt rowStatus = stmt.Next();
-    
-    TBool modified = EFalse;
-    TBool checkMain = EFalse;
-    
-    TN_DEBUG1( "CThumbnailStore::CheckModifiedL() -- temp" );
-    
-    while(rowStatus == KSqlAtRow || !checkMain)
-        {
-            if(rowStatus == KSqlAtRow)
-                {
-               TInt64 oldModified = stmt.ColumnInt64( column );
-               
-               if (oldModified < aModified)
-                   {
-                   TN_DEBUG1( "CThumbnailStore::CheckModifiedL() -- timestamp is newer than original" );
-                   modified = ETrue;
-                   break;
-                   }
-               else if (oldModified > aModified)
-                   {
-                   TN_DEBUG1( "CThumbnailStore::CheckModifiedL() -- timestamp is older than original" );
-                   break;
-                   }
-               else if (oldModified == aModified)
-                   {
-                   TN_DEBUG1( "CThumbnailStore::CheckModifiedL() -- timestamp is the same as original" );
-                   }
-                }
-            
-        rowStatus = stmt.Next();
-        
-        //switch to main table if modified not found from temp
-        if(rowStatus != KSqlAtRow && !checkMain && !modified)
-            {
-            TN_DEBUG1( "CThumbnailStore::CheckModifiedL() -- main" );
-            //come here only once
-            checkMain = ETrue;
-            
-            stmt.Close();
-            CleanupStack::PopAndDestroy( &stmt );
-            CleanupClosePushL( stmt );
-            
-            User::LeaveIfError( stmt.Prepare( iDatabase, KThumbnailSelectModifiedByID ));
-            
-            paramIndex = stmt.ParameterIndex( KThumbnailSqlParamId );
-            User::LeaveIfError( paramIndex );
-            User::LeaveIfError( stmt.BindInt( paramIndex, aItemId ));
-             
-            rowStatus = stmt.Next();
-            }
-        }
-     
-    stmt.Close();
-    CleanupStack::PopAndDestroy( &stmt ); 
-    
-    return modified;
-    }
-
-// -----------------------------------------------------------------------------
-// Fetches thumbnails from store by Id
-// -----------------------------------------------------------------------------
-//
-void CThumbnailStore::FetchThumbnailsL(TThumbnailId aItemId, RArray < TThumbnailDatabaseData* >& aThumbnails)
-    {
-    TN_DEBUG1( "CThumbnailStore::FetchThumbnails()" );
-    RSqlStatement stmt;
-    CleanupClosePushL( stmt );
-    
-    // first temp table
-    User::LeaveIfError( stmt.Prepare( iDatabase, KThumbnailSelectTempById ));
-
-    TInt paramIndex = stmt.ParameterIndex( KThumbnailSqlParamId );
-    User::LeaveIfError( paramIndex );
-    User::LeaveIfError( stmt.BindInt( paramIndex, aItemId ));
-
-    TInt rowStatus = stmt.Next();
-    
-    TPath path;
-    TPath tnPath;
-    while ( rowStatus == KSqlAtRow)
-        {
-        TN_DEBUG1( "CThumbnailStore::FetchThumbnails() -- thumbnail found from temp table" );
-        
-        TInt column = 0;
-            
-        TThumbnailDatabaseData* newRow = new(ELeave) TThumbnailDatabaseData;
-            
-        TInt err = stmt.ColumnText( column++, newRow->iPath );
-        newRow->iTnId = stmt.ColumnInt( column++ );
-        newRow->iSize = stmt.ColumnInt( column++ );
-        newRow->iFormat = stmt.ColumnInt( column++ );
-        err = stmt.ColumnText( column++, newRow->iTnPath);
-        newRow->iWidth = stmt.ColumnInt( column++ );
-        newRow->iHeight = stmt.ColumnInt( column++ );
-        newRow->iOrigWidth = stmt.ColumnInt( column++ );
-        newRow->iOrigHeight = stmt.ColumnInt( column++ );
-        newRow->iFlags = stmt.ColumnInt( column++ );
-        newRow->iVideoPosition = stmt.ColumnInt( column++ );
-        newRow->iOrientation = stmt.ColumnInt( column++ );
-        newRow->iThumbFromPath = stmt.ColumnInt( column++ );
-        newRow->iModified = stmt.ColumnInt64( column++ );
-        
-        if(newRow->iFormat == 0)
-            {
-            TPtrC8 ptr = stmt.ColumnBinaryL( column++ );
-            RDesReadStream stream( ptr );
-            newRow->iBlob = new( ELeave )CFbsBitmap();
-            newRow->iBlob->InternalizeL( stream );
-            }
-        else if(newRow->iFormat == 1)
-            {
-            TPtrC8 ptr = stmt.ColumnBinaryL( column++ );
-            HBufC8* data = ptr.AllocL() ;
-            newRow->iBlob = NULL;
-            newRow->iData = data;
-            }
-        
-        aThumbnails.Append( newRow );
-               
-        rowStatus = stmt.Next();
-        }
-    
-    // then real table
-    stmt.Close();
-    CleanupStack::PopAndDestroy(&stmt); 
-    CleanupClosePushL( stmt );
-    User::LeaveIfError( stmt.Prepare( iDatabase, KThumbnailSelectById ));
-
-    paramIndex = stmt.ParameterIndex( KThumbnailSqlParamId );
-    User::LeaveIfError( paramIndex );
-    User::LeaveIfError( stmt.BindInt( paramIndex, aItemId ));
-
-    rowStatus = stmt.Next();
-    while ( rowStatus == KSqlAtRow)
-        {
-        TN_DEBUG1( "CThumbnailStore::FetchThumbnails() -- thumbnail found from real table" );
-        
-        TInt column = 0;
-        
-        TThumbnailDatabaseData* newRow = new(ELeave) TThumbnailDatabaseData;
-        
-        TInt err = stmt.ColumnText( column++, newRow->iPath );
-        newRow->iTnId = stmt.ColumnInt( column++ );
-        newRow->iSize = stmt.ColumnInt( column++ );
-        newRow->iFormat = stmt.ColumnInt( column++ );
-        err = stmt.ColumnText( column++, newRow->iTnPath);
-        newRow->iWidth = stmt.ColumnInt( column++ );
-        newRow->iHeight = stmt.ColumnInt( column++ );
-        newRow->iOrigWidth = stmt.ColumnInt( column++ );
-        newRow->iOrigHeight = stmt.ColumnInt( column++ );
-        newRow->iFlags = stmt.ColumnInt( column++ );
-        newRow->iVideoPosition = stmt.ColumnInt( column++ );
-        newRow->iOrientation = stmt.ColumnInt( column++ );
-        newRow->iThumbFromPath = stmt.ColumnInt( column++ );
-        newRow->iModified = stmt.ColumnInt64( column++ );
-        
-        if(newRow->iFormat == 0)
-            {
-            TPtrC8 ptr = stmt.ColumnBinaryL( column++ );
-            RDesReadStream stream( ptr );
-            newRow->iBlob = new( ELeave )CFbsBitmap();
-            newRow->iBlob->InternalizeL( stream );
-            }
-        else if(newRow->iFormat == 1)
-            {
-            TPtrC8 ptr = stmt.ColumnBinaryL( column++ );
-            HBufC8* data = ptr.AllocL() ;
-            newRow->iBlob = NULL;
-            newRow->iData = data;
-            }
-        
-        aThumbnails.Append( newRow );
-              
-        rowStatus = stmt.Next();
-        }
-    
-    stmt.Close();
-    CleanupStack::PopAndDestroy( &stmt );
-    }
-
-// -----------------------------------------------------------------------------
-// Stores thumbnails to store
-// -----------------------------------------------------------------------------
-//
-
-void CThumbnailStore::StoreThumbnailsL(const TDesC& aNewPath, RArray < TThumbnailDatabaseData* >& aThumbnails)
-    {
-    TN_DEBUG1( "CThumbnailStore::StoreThumbnails()" );
-    
-    TInt ThumbnailCount = aThumbnails.Count();
-    RSqlStatement stmt;
-    for ( TInt i = 0; i < ThumbnailCount; i++ )
-        {
-        RThumbnailTransaction transaction( iDatabase );
-        CleanupClosePushL( transaction );
-        transaction.BeginL();
-        
-        CleanupClosePushL( stmt );
-          
-        User::LeaveIfError( stmt.Prepare( iDatabase, KThumbnailInsertThumbnailInfoByPathAndId ));
-        
-        TInt paramIndex = stmt.ParameterIndex( KThumbnailSqlParamPath );
-        User::LeaveIfError( paramIndex );
-        User::LeaveIfError( stmt.BindText( paramIndex, aNewPath ));
-        
-        paramIndex = stmt.ParameterIndex( KThumbnailSqlParamWidth );
-        User::LeaveIfError( paramIndex );
-        User::LeaveIfError( stmt.BindInt( paramIndex, aThumbnails[ i ]->iWidth ));
-        
-        paramIndex = stmt.ParameterIndex( KThumbnailSqlParamHeight );
-        User::LeaveIfError( paramIndex );
-        User::LeaveIfError( stmt.BindInt( paramIndex, aThumbnails[ i ]->iHeight ));
-        
-        paramIndex = stmt.ParameterIndex( KThumbnailSqlParamOriginalWidth );
-        User::LeaveIfError( paramIndex );
-        User::LeaveIfError( stmt.BindInt( paramIndex, aThumbnails[ i ]->iOrigWidth ));
-        
-        paramIndex = stmt.ParameterIndex( KThumbnailSqlParamOriginalHeight );
-        User::LeaveIfError( paramIndex );
-        User::LeaveIfError( stmt.BindInt( paramIndex, aThumbnails[ i ]->iOrigHeight ));
-        
-        paramIndex = stmt.ParameterIndex( KThumbnailSqlParamFormat );
-        User::LeaveIfError( paramIndex );
-        User::LeaveIfError( stmt.BindInt( paramIndex, aThumbnails[ i ]->iFormat ));
-        
-        paramIndex = stmt.ParameterIndex( KThumbnailSqlParamFlags );
-        User::LeaveIfError( paramIndex );
-        User::LeaveIfError( stmt.BindInt( paramIndex, aThumbnails[ i ]->iFlags ));
-        
-        paramIndex = stmt.ParameterIndex( KThumbnailSqlParamSize );
-        User::LeaveIfError( paramIndex );
-        User::LeaveIfError( stmt.BindInt( paramIndex, aThumbnails[ i ]->iSize ));
-        
-        paramIndex = stmt.ParameterIndex( KThumbnailSqlParamId );
-        User::LeaveIfError( paramIndex );
-        User::LeaveIfError( stmt.BindInt( paramIndex, aThumbnails[ i ]->iTnId ));
-        
-        paramIndex = stmt.ParameterIndex( KThumbnailSqlParamOrientation );
-        User::LeaveIfError( paramIndex );
-        User::LeaveIfError( stmt.BindInt( paramIndex, aThumbnails[ i ]->iOrientation ));
-        
-        paramIndex = stmt.ParameterIndex( KThumbnailSqlParamThumbFromPath );
-        User::LeaveIfError( paramIndex );
-        User::LeaveIfError( stmt.BindInt( paramIndex, aThumbnails[ i ]->iThumbFromPath ));
-        
-        paramIndex = stmt.ParameterIndex( KThumbnailSqlParamModified );
-        User::LeaveIfError( paramIndex );
-        User::LeaveIfError( stmt.BindInt64( paramIndex, aThumbnails[ i ]->iModified ));
-        
-        User::LeaveIfError( stmt.Exec());    
-        CleanupStack::PopAndDestroy( &stmt );
-        
-        RSqlStatement stmtData;
-        CleanupClosePushL( stmtData );
-        TInt err = stmtData.Prepare( iDatabase, KThumbnailInsertTempThumbnailInfoData );
-        
-        if(aThumbnails[ i ]->iFormat == 0)
-            {
-            CBufFlat* buf = CBufFlat::NewL( KStreamBufferSize );
-            CleanupStack::PushL( buf );
-            RBufWriteStream stream;
-            stream.Open( *buf );
-            aThumbnails[ i ]->iBlob->ExternalizeL( stream );
-            paramIndex = stmtData.ParameterIndex( KThumbnailSqlParamData );
-            User::LeaveIfError( paramIndex );
-            User::LeaveIfError( stmtData.BindBinary( paramIndex, buf->Ptr( 0 ) ));
-            CleanupStack::PopAndDestroy( buf );
-            delete aThumbnails[i]->iBlob;
-            aThumbnails[i]->iBlob = NULL;
-            }
-        else if(aThumbnails[ i ]->iFormat == 1)
-            {
-            paramIndex = stmtData.ParameterIndex( KThumbnailSqlParamData );
-            User::LeaveIfError( paramIndex );
-            User::LeaveIfError( stmtData.BindBinary( paramIndex, *aThumbnails[ i ]->iData ));
-            delete aThumbnails[i]->iData;
-            aThumbnails[i]->iData = NULL;
-            }
-        
-        User::LeaveIfError( stmtData.Exec());
-        CleanupStack::PopAndDestroy( &stmtData );
-        
-        // Commit transaction
-        transaction.CommitL();
-        CleanupStack::PopAndDestroy( &transaction );
-        
-        delete aThumbnails[i];
-        aThumbnails[i] = NULL;
-        iBatchItemCount++;                          
-        }
-    
-    FlushCacheTable();
-    }
-
 // -----------------------------------------------------------------------------
 // CheckVersionAndImeiL()
 // -----------------------------------------------------------------------------
@@ -2002,6 +1354,8 @@
        {  
        stmt.Close();
        CleanupStack::PopAndDestroy( &stmt ); 
+
+       TN_DEBUG1( "CThumbnailStore::CheckImeiL() failed" );
        return KErrNotSupported;
        }
               
@@ -2016,12 +1370,22 @@
     stmt.Close();
     CleanupStack::PopAndDestroy( &stmt ); 
     
+    if(ret < 0 )
+        {
+#ifdef _DEBUG
+   		 TPtrC errorMsg = iDatabase.LastErrorMessage();
+    	TN_DEBUG2( "RThumbnailTransaction::CheckImeiL() lastError %S, ret = %d" , &errorMsg);
+#endif
+        return ret;
+        }
+    
     if( imei == iImei )
       {
       return KErrNone;  
       }
     else
       {
+      TN_DEBUG1( "CThumbnailStore::CheckImeiL() mismatch" );
       return KErrNotSupported;  
       }
     }
@@ -2047,6 +1411,7 @@
        {  
        stmt.Close();
        CleanupStack::PopAndDestroy( &stmt ); 
+       TN_DEBUG1( "CThumbnailStore::CheckVersionL() unknown version" );
        return KErrNotSupported;
        }
               
@@ -2061,6 +1426,15 @@
     stmt.Close();
     CleanupStack::PopAndDestroy( &stmt ); 
     
+    if(ret < 0 )
+        {
+#ifdef _DEBUG
+   		 TPtrC errorMsg = iDatabase.LastErrorMessage();
+    	TN_DEBUG2( "RThumbnailTransaction::CheckVersionL() lastError %S, ret = %d" , &errorMsg);
+#endif
+        return ret;
+        }
+    
     if(major == KMajor && minor == KMinor )
       {
       return KErrNone;  
@@ -2137,15 +1511,34 @@
 // ResetThumbnailIDs()
 // -----------------------------------------------------------------------------
 //
-void CThumbnailStore::ResetThumbnailIDs()
+TInt CThumbnailStore::ResetThumbnailIDs()
     {
     TN_DEBUG1( "CThumbnailStore::ResetThumbnailIDs()" );
 
     TInt err = iDatabase.Exec( KTempThumbnailResetIDs );
     TN_DEBUG2( "CThumbnailStore::ResetThumbnailIDs() KThumbnailResetIDs - temp table, err=%d", err );
-    
+
+    if(err < 0)
+        {
+#ifdef _DEBUG
+        TPtrC errorMsg = iDatabase.LastErrorMessage();
+        TN_DEBUG2( "RThumbnailTransaction::ResetThumbnailIDs() lastError %S, ret = %d" , &errorMsg);
+#endif
+        return err;
+    }
+
     err = iDatabase.Exec( KThumbnailResetIDs );
     TN_DEBUG2( "CThumbnailStore::ResetThumbnailIDs() KThumbnailResetIDs - main table, err=%d", err );
+    
+	if(err < 0)
+        {
+#ifdef _DEBUG
+        TPtrC errorMsg2 = iDatabase.LastErrorMessage();
+        TN_DEBUG2( "RThumbnailTransaction::ResetThumbnailIDs() lastError %S, ret = %d" , &errorMsg2);
+#endif
+        return err;
+        }
+	return KErrNone;
     }
 
 
@@ -2153,7 +1546,7 @@
 // UpdateImeiL()
 // -----------------------------------------------------------------------------
 //
-void CThumbnailStore::UpdateImeiL()
+TInt CThumbnailStore::UpdateImeiL()
     {
     TN_DEBUG1( "CThumbnailStore::UpdateImeiL()" );
     RSqlStatement stmt;
@@ -2168,12 +1561,18 @@
     
     TInt err =  stmt.Exec();
     
-    TN_DEBUG2( "CThumbnailStore::UpdateImeiL() err==%d", err );
-    
-    User::LeaveIfError( err );
+    if(err < 0)
+        {
+#ifdef _DEBUG
+        TPtrC errorMsg2 = iDatabase.LastErrorMessage();
+        TN_DEBUG2( "RThumbnailTransaction::ResetThumbnailIDs() lastError %S, ret = %d" , &errorMsg2);
+#endif
+        return ret;
+        }
     
     stmt.Close();
-    CleanupStack::PopAndDestroy( &stmt ); 
+    CleanupStack::PopAndDestroy( &stmt );
+    return KErrNone;
     }
 
 // -----------------------------------------------------------------------------
@@ -2201,7 +1600,7 @@
         }
     else
         {
-        iAutoFlushTimer->Start( KAutoFlushTimeout, KAutoFlushTimeout, 
+        iAutoFlushTimer->Start( KAutoFlushTimeout * 1000000, KAutoFlushTimeout * 1000000, 
                                 TCallBack(AutoFlushTimerCallBack, this));
         }
     }
@@ -2219,6 +1618,35 @@
         }
     }
 
+// -----------------------------------------------------------------------------
+// StartMaintenance()
+// -----------------------------------------------------------------------------
+//
+void CThumbnailStore::StartMaintenance()
+    {
+    TN_DEBUG1( "CThumbnailStore::StartMaintenance()");
+    TInt err = KErrNone;
+    
+    if( iMaintenanceTimer && iMaintenanceTimer->IsActive() )
+        {
+        return;
+        }
+    else if (!iMaintenanceTimer)
+        {
+        TRAP(err, iMaintenanceTimer = CPeriodic::NewL(CActive::EPriorityIdle) );
+        }
+    
+    if (err != KErrNone && !iMaintenanceTimer)
+        {
+        TN_DEBUG2( "CThumbnailStore::StartMaintenanceTimer() - Error creating timer (%d)", err );
+        }
+    else
+        {
+        iMaintenanceTimer->Start( KStoreMaintenancePeriodic, KStoreMaintenancePeriodic, 
+                                  TCallBack(MaintenanceTimerCallBack, this));
+        }
+    }
+
 // ---------------------------------------------------------------------------
 // CThumbnailStore::AutoFlushTimerCallBack()
 // ---------------------------------------------------------------------------
@@ -2233,6 +1661,80 @@
     return KErrNone; // Return value ignored by CPeriodic
     }
 
+// ---------------------------------------------------------------------------
+// CThumbnailStore::MaintenanceTimerCallBack()
+// ---------------------------------------------------------------------------
+//
+TInt CThumbnailStore::MaintenanceTimerCallBack(TAny* aAny)
+    {
+    CThumbnailStore* self = static_cast<CThumbnailStore*>( aAny );
+ 
+    self->iMaintenanceTimer->Cancel();
+    
+    if (self->iIdle)
+        {
+        TN_DEBUG2( "CThumbnailStore::MaintenanceTimerCallBack() - maintenance, store %d", self->iDrive);
+    
+        // thumbmnail deletion
+        if (self->iDeleteThumbs)
+            {
+            TInt deleteCount = 0;
+            
+            // delete marked rows from database
+            TRAPD( err, deleteCount = self->DeleteMarkedL() );
+            if (err != KErrNone)
+                {
+                TN_DEBUG2( "CThumbnailStore::MaintenanceTimerCallBack() - cleanup failed, err %d", err);
+                return err;
+                }
+            
+            // no more marked rows
+            if (deleteCount < KStoreMaintenanceDeleteLimit || deleteCount == 0)
+                {
+                TN_DEBUG2( "CThumbnailStore::MaintenanceTimerCallBack() - cleanup finished, store %d", self->iDrive);
+                self->iDeleteThumbs = EFalse;
+                }     
+            }
+        
+        // file existance check
+        else if (self->iCheckFilesExist)
+            {
+            TBool finished = EFalse;
+        
+            TRAPD( err, finished = self->FileExistenceCheckL() );
+            if (err != KErrNone)
+                {
+                TN_DEBUG2( "CThumbnailStore::MaintenanceTimerCallBack() - file existance check failed, err %d", err);
+                return err;
+                }
+        
+            // all files checked.
+            if (finished)
+                {
+                TN_DEBUG2( "CThumbnailStore::MaintenanceTimerCallBack() - file existance check finished, store %d", self->iDrive);
+                self->iCheckFilesExist = EFalse;
+                }
+            }
+        
+        // next round
+        if (self->iIdle && ( self->iDeleteThumbs || self->iCheckFilesExist) )
+            {
+            self->StartMaintenance();
+            }  
+        else
+            {
+            // no need to monitor activity anymore
+            self->iActivityManager->Cancel();
+            }
+        }
+    else
+        {
+        TN_DEBUG1( "CThumbnailStore::MaintenanceTimerCallBack() - device not idle");
+        }
+
+    return KErrNone; // Return value ignored by CPeriodic
+    }
+
 TInt CThumbnailStore::CheckRowIDsL()
     {
     TN_DEBUG1( "CThumbnailStore::CheckRowIDs()");
@@ -2249,6 +1751,7 @@
         {
         stmt.Close();
         CleanupStack::PopAndDestroy( &stmt );
+        TN_DEBUG1( "CThumbnailStore::CheckRowIDs() failed 1 %d");
         return KErrNotSupported;
         }
     rowStatus = stmt.Next();
@@ -2257,9 +1760,18 @@
         {        
         inforows = stmt.ColumnInt64( column );  
         }
-            
+                
     stmt.Close();
     CleanupStack::PopAndDestroy( &stmt );
+    
+    if(ret < 0)
+        {
+#ifdef _DEBUG
+		TPtrC errorMsg2 = iDatabase.LastErrorMessage();
+	    TN_DEBUG2( "RThumbnailTransaction::ResetThumbnailIDs() lastError %S, ret = %d" , &errorMsg2);
+#endif
+        return ret;
+        }
             
     CleanupClosePushL( stmt );
     ret = stmt.Prepare( iDatabase, KGetDataRowID );
@@ -2267,6 +1779,7 @@
         {
         stmt.Close();
         CleanupStack::PopAndDestroy( &stmt );
+        TN_DEBUG1( "CThumbnailStore::CheckRowIDs() failed 2");
         return KErrNotSupported;
         }
     rowStatus = stmt.Next();
@@ -2278,6 +1791,15 @@
             
     stmt.Close();
     CleanupStack::PopAndDestroy( &stmt );
+    
+    if(ret < 0)
+        {
+#ifdef _DEBUG
+		TPtrC errorMsg2 = iDatabase.LastErrorMessage();
+	    TN_DEBUG2( "RThumbnailTransaction::ResetThumbnailIDs() lastError %S, ret = %d" , &errorMsg2);
+#endif
+        return ret;
+        }
             
     if( inforows != datarows)
         {
@@ -2290,94 +1812,97 @@
         }
     }
 
-void CThumbnailStore::CheckModifiedByIdL( TUint32 aId, TBool aTempTable,
-    TBool& aModified )
+TBool CThumbnailStore::CheckModifiedByPathL( const TDesC& aPath, const TInt64 aModified, TBool& modifiedChanged )
     {
-    TN_DEBUG1( "CThumbnailStore::CheckModifiedByIdL()");
-    
-    RSqlStatement stmt;
-    CleanupClosePushL( stmt );
-    TInt column( 0 );
+    TN_DEBUG2( "CThumbnailStore::CheckModifiedByPathL() %S", &aPath);
     
-    if( aTempTable )
-        {
-        User::LeaveIfError( stmt.Prepare( iDatabase, KThumbnailSelectTempPathModifiedByID ) );
-        }
-    else
-        {
-        User::LeaveIfError( stmt.Prepare( iDatabase, KThumbnailSelectPathModifiedByID ) );
-        }
-    TInt paramIndex = stmt.ParameterIndex( KThumbnailSqlParamId );
-    User::LeaveIfError( paramIndex );
-    User::LeaveIfError( stmt.BindInt( paramIndex, aId ));
-     
-    TInt rowStatus = stmt.Next();
-    
-    if(rowStatus == KSqlAtRow)
-        {
-        TPath path = stmt.ColumnTextL(column++);
-           
-        if (path.Length())
-            {
-            TInt64 modified = stmt.ColumnInt64( column );
-            TTime timeStamp;
-            iFs.Modified( path, timeStamp );
-            
-            if( modified != timeStamp.Int64() )
-                {
-                aModified = ETrue;
-                }
-            }
-        }
+    HBufC* path = aPath.AllocLC();
+    TPtr ptr(path->Des());
+    StripDriveLetterL( ptr );
+	
+    TBool ret(EFalse);
+
+    modifiedChanged = EFalse;
+
+   TInt column = 0;
+   
+   RSqlStatement stmt;
+   CleanupClosePushL( stmt );
+      
+   User::LeaveIfError( stmt.Prepare( iDatabase, KThumbnailSelectTempModifiedByPath ));
+   
+   TInt paramIndex = stmt.ParameterIndex( KThumbnailSqlParamPath );
+   User::LeaveIfError( paramIndex );
+   User::LeaveIfError( stmt.BindText( paramIndex, *path ));
     
-    stmt.Close();
-    CleanupStack::PopAndDestroy( &stmt );
-    }
-
-void CThumbnailStore::CheckModifiedByPathL( const TDesC& aPath, TBool aTempTable,
-    TBool& aModified )
-    {
-    TN_DEBUG1( "CThumbnailStore::CheckModifiedByPathL()");
-    
-    RSqlStatement stmt;
-    CleanupClosePushL( stmt );
-    TInt column( 0 );
+   TInt rowStatus = stmt.Next();
+   
+   TBool checkMain = EFalse;
+   
+   TN_DEBUG1( "CThumbnailStore::CheckModifiedL() -- temp" );
+   
+   while(rowStatus == KSqlAtRow || !checkMain)
+       {
+       if(rowStatus == KSqlAtRow)
+           {
+           ret = ETrue;
+           TInt64 oldModified = stmt.ColumnInt64( column );
+           
+           TN_DEBUG2( "CThumbnailStore::CheckModifiedL() -- timestamp old %Ld", oldModified);
+           TN_DEBUG2( "CThumbnailStore::CheckModifiedL() -- timestamp mds %Ld", aModified);
+          
+           if (oldModified < aModified)
+               {
+               TN_DEBUG1( "CThumbnailStore::CheckModifiedL() -- timestamp is newer than original" );
+               modifiedChanged = ETrue;
+               break;
+               }
+           else if (oldModified > aModified)
+               {
+               TN_DEBUG1( "CThumbnailStore::CheckModifiedL() -- timestamp is older than original" );
+               }
+           else if (oldModified == aModified)
+               {
+               TN_DEBUG1( "CThumbnailStore::CheckModifiedL() -- timestamp is the same as original" );
+               }
+            }
+           
+       rowStatus = stmt.Next();
+       
+       //switch to main table if modified not found from temp
+       if(rowStatus != KSqlAtRow && !checkMain && !modifiedChanged)
+           {
+           TN_DEBUG1( "CThumbnailStore::CheckModifiedL() -- main" );
+           //come here only once
+           checkMain = ETrue;
+           
+           stmt.Close();
+           CleanupStack::PopAndDestroy( &stmt );
+           CleanupClosePushL( stmt );
+           
+           User::LeaveIfError( stmt.Prepare( iDatabase, KThumbnailSelectModifiedByPath ));
+           
+           paramIndex = stmt.ParameterIndex( KThumbnailSqlParamPath );
+           User::LeaveIfError( paramIndex );
+           User::LeaveIfError( stmt.BindText( paramIndex, *path ));
+            
+           rowStatus = stmt.Next();
+           }
+       }
     
-    if( aTempTable )
-        {
-        User::LeaveIfError( stmt.Prepare( iDatabase, KThumbnailSelectTempModifiedByPath ) );
-        }
-    else
-        {
-        User::LeaveIfError( stmt.Prepare( iDatabase, KThumbnailSelectModifiedByPath ) );
-        }
-    TInt paramIndex = stmt.ParameterIndex( KThumbnailSqlParamPath );
-    User::LeaveIfError( paramIndex );
-    User::LeaveIfError( stmt.BindText( paramIndex, aPath ));
-     
-    TInt rowStatus = stmt.Next();
-    
-    if(rowStatus == KSqlAtRow)
-        {
-        TInt64 modified = stmt.ColumnInt64( column );
-        TTime timeStamp;
-        iFs.Modified( aPath, timeStamp );
-        
-        if( modified != timeStamp.Int64() )
-            {
-            aModified = ETrue;
-            }
-        }
-    
-    stmt.Close();
-    CleanupStack::PopAndDestroy( &stmt );
-    }
-
+   stmt.Close();
+   CleanupStack::PopAndDestroy( &stmt ); 
+   
+   CleanupStack::PopAndDestroy( path );
+   
+   return ret;
+}
+	
 // -----------------------------------------------------------------------------
-// PrepareBlacklistedItemsForRetry()
+// PrepareBlacklistedItemsForRetryL()
 // -----------------------------------------------------------------------------
 //
-void CThumbnailStore::PrepareBlacklistedItemsForRetry()
+void CThumbnailStore::PrepareBlacklistedItemsForRetryL()
     {
     TN_DEBUG1( "CThumbnailStore::PrepareBlacklistedItemsForRetry()" );
     
@@ -2391,24 +1916,237 @@
     User::LeaveIfError( stmt.BindInt( paramIndex, KThumbnailDbFlagBlacklisted ));
     TInt err = stmt.Exec();
    
-    TN_DEBUG2( "CThumbnailStore::PrepareBlacklistedItemsForRetry() - main table, err=%d", err );
+    TN_DEBUG2( "CThumbnailStore::PrepareBlacklistedItemsForRetryL() - main table, err=%d", err );
     
     CleanupStack::PopAndDestroy( &stmt );
     }
 
+// -----------------------------------------------------------------------------
+// DeleteMarkedL()
+// -----------------------------------------------------------------------------
+//
+TInt CThumbnailStore::DeleteMarkedL()
+    {
+#ifdef _DEBUG
+    TTime aStart, aStop;
+    aStart.UniversalTime();
+#endif
+    
+    TN_DEBUG1( "CThumbnailStore::DeleteMarkedL()" );
+    
+    TInt paramIndex = 0;
+    TInt paramIndex1 = 0;
+    TInt paramIndex2 = 0;
+    TInt rowStatus = 0;
+    TInt column = 0;
+    TInt64 rowid = 0;
+    TInt deleteCount = 0;
+      
+    RThumbnailTransaction transaction( iDatabase );
+    CleanupClosePushL( transaction );
+    transaction.BeginL();
+    
+    RSqlStatement stmt;
+    RSqlStatement stmt_info;
+    RSqlStatement stmt_infodata;
+    CleanupClosePushL( stmt );
+    
+    // select marked rows
+    User::LeaveIfError( stmt.Prepare( iDatabase, KThumbnailSqlSelectMarked ));
+    
+    paramIndex = stmt.ParameterIndex( KThumbnailSqlParamLimit );
+    User::LeaveIfError( paramIndex );
+    User::LeaveIfError( stmt.BindInt( paramIndex, KStoreMaintenanceDeleteLimit ));
+             
+    rowStatus = stmt.Next();  
+    
+    CleanupClosePushL( stmt_info );
+    User::LeaveIfError( stmt_info.Prepare( iDatabase, KThumbnailSqlDeleteInfoByRowID) );
+    CleanupClosePushL( stmt_infodata );
+    User::LeaveIfError( stmt_infodata.Prepare( iDatabase, KThumbnailSqlDeleteInfoDataByRowID) );    
+           
+    while(rowStatus == KSqlAtRow)
+       { 
+       rowid = stmt.ColumnInt64( column ); 
+       paramIndex1 = stmt_info.ParameterIndex( KThumbnailSqlParamRowID );
+       User::LeaveIfError( paramIndex1 );
+       User::LeaveIfError( stmt_info.BindInt64( paramIndex1, rowid ));
+              
+       TInt err = stmt_info.Exec();
+       stmt_info.Reset();
+       User::LeaveIfError( err );
+                    
+       paramIndex2 = stmt_infodata.ParameterIndex( KThumbnailSqlParamRowID );  
+       User::LeaveIfError( paramIndex2 );
+       User::LeaveIfError( stmt_infodata.BindInt64( paramIndex2, rowid ));
+                    
+       err = stmt_infodata.Exec();
+       stmt_infodata.Reset();
+       User::LeaveIfError( err );
+       deleteCount++;
+       
+       TN_DEBUG1( "CThumbnailStore::DeleteMarkedL() - thumbnail deleted" );
+       
+       rowStatus = stmt.Next();
+       }
+        
+    stmt_infodata.Close();
+    stmt_info.Close();
+    stmt.Close();
+    CleanupStack::PopAndDestroy( &stmt_infodata );
+    CleanupStack::PopAndDestroy( &stmt_info );
+    CleanupStack::PopAndDestroy( &stmt );    
+    
+    // remove successfully deleted paths from Deleted table
+    if (deleteCount > 0)
+        {
+        CleanupClosePushL( stmt );  
+        User::LeaveIfError( iDatabase.Exec( KThumbnailSqlDeleteFromDeleted ) ); 
+        
+        stmt.Close();
+        CleanupStack::PopAndDestroy( &stmt );
+        }
+    
+    transaction.CommitL();
+    CleanupStack::PopAndDestroy( &transaction );
+    
+#ifdef _DEBUG
+    aStop.UniversalTime();
+    TN_DEBUG2( "CThumbnailStore::DeleteMarkedL() took %d ms", (TInt)aStop.MicroSecondsFrom(aStart).Int64()/1000);
+#endif
+    
+    return deleteCount;
+    }
+
+// -----------------------------------------------------------------------------
+// FileExistenceCheckL()
+// -----------------------------------------------------------------------------
+//
+TInt CThumbnailStore::FileExistenceCheckL()
+    {
+#ifdef _DEBUG
+    TTime aStart, aStop;
+    aStart.UniversalTime();
+#endif
+    
+    TN_DEBUG1( "CThumbnailStore::FileExistenceCheckL()" );
+    
+    TInt paramIndex = 0;
+    TInt rowStatus = 0; 
+    TInt column = 0;
+    TInt64 rowid = 0;
+    TFileName path;
+    TFileName prevPath;
+    TFileName full;
+    TInt count = 0;
+    
+    TBool finished = EFalse;
+    
+    TChar dChar = 0;
+    User::LeaveIfError( iFs.DriveToChar( iDrive, dChar ));
+    
+    RThumbnailTransaction transaction( iDatabase );
+    CleanupClosePushL( transaction );    
+    transaction.BeginL();
+    
+    RSqlStatement stmt;
+    CleanupClosePushL( stmt );
+    
+    // get rows
+    User::LeaveIfError( stmt.Prepare( iDatabase, KThumbnailSelectAllPaths ));
+    
+    paramIndex = stmt.ParameterIndex( KThumbnailSqlParamRowID );
+    User::LeaveIfError( paramIndex );
+    User::LeaveIfError( stmt.BindInt64( paramIndex, iLastCheckedRowID ));
+    
+    paramIndex = stmt.ParameterIndex( KThumbnailSqlParamLimit );
+    User::LeaveIfError( paramIndex );
+    User::LeaveIfError( stmt.BindInt( paramIndex, KStoreMaintenanceExistLimit ));
+             
+    rowStatus = stmt.Next();     
+           
+    while(rowStatus == KSqlAtRow)
+        {
+        column = 0;
+        path.Zero();
+        
+        rowid = stmt.ColumnInt64( column++ );
+        stmt.ColumnText( column, path );
+    
+        full.Zero();
+        full.Append(dChar);
+        full.Append(KDrv);
+        full.Append(path);
+        
+        // if path matches previous one, skip
+        if (path.CompareF(prevPath) != 0)
+            {
+            // file doesn't exist anymore, mark thumbs deleted
+            if(!BaflUtils::FileExists( iFs, full ))
+                {
+                TN_DEBUG2( "CThumbnailStore::FileExistenceCheckL(%S) - not found", &full );
+                DeleteThumbnailsL(path, EFalse, EFalse);                    
+                }
+            
+            prevPath.Zero();
+            prevPath.Append(path);
+            }
+        
+        iLastCheckedRowID = rowid;
+        count++;
+       
+        // get next
+        rowStatus = stmt.Next();
+        }
+    
+    if (count < KStoreMaintenanceExistLimit)
+        {
+        // all rows checked
+        finished = ETrue;
+        }
+        
+    stmt.Close();
+    CleanupStack::PopAndDestroy( &stmt );    
+    
+    transaction.CommitL();
+    CleanupStack::PopAndDestroy( &transaction );
+    
+#ifdef _DEBUG
+    aStop.UniversalTime();
+    TN_DEBUG2( "CThumbnailStore::FileExistenceCheckL() took %d ms", (TInt)aStop.MicroSecondsFrom(aStart).Int64()/1000);
+#endif
+    
+    return finished;
+    }
+
+// -----------------------------------------------------------------------------
+// StripDriveLetter
+// -----------------------------------------------------------------------------
+//
+void CThumbnailStore::StripDriveLetterL( TDes& aPath )
+    {
+    TInt pos = aPath.Find(KDrv);
+    
+    // if URI contains drive letter
+    if ( pos == 1 )
+        {
+        aPath.Delete(0,pos+1);
+        }
+    }
+
 void CThumbnailStore::HandleDiskSpaceNotificationL( TBool aDiskFull )
     {
     TN_DEBUG2( "CThumbnailStore::HandleDiskSpaceNotificationL() aDiskFull = %d", aDiskFull );
     iDiskFull = aDiskFull;
     }
 
-
+#ifdef _DEBUG
 void CThumbnailStore::HandleDiskSpaceError(TInt aError )
+#else
+void CThumbnailStore::HandleDiskSpaceError(TInt /*aError*/ )
+#endif
     {
-    if (aError != KErrNone)
-        {
-        TN_DEBUG2( "CThumbnailStore::HandleDiskSpaceError() aError = %d", aError );
-        }
+    TN_DEBUG2( "CThumbnailStore::HandleDiskSpaceError() aError = %d", aError );
     }
 
 TBool CThumbnailStore::IsDiskFull()
@@ -2416,6 +2154,46 @@
     return iDiskFull;
     }
 
+// -----------------------------------------------------------------------------
+// ActivityDetected()
+// -----------------------------------------------------------------------------
+//
+void CThumbnailStore::ActivityChanged(const TBool aActive)
+    {
+    TN_DEBUG2( "CThumbnailStore::ActivityChanged() aActive == %d", aActive);
+    
+    if( aActive )
+        {
+        iIdle = EFalse;
+        }
+    else
+        {
+        TInt MPXHarvesting(0);
+        TInt DaemonProcessing(0);
+        TInt ret = RProperty::Get(KTAGDPSNotification, KMPXHarvesting, MPXHarvesting);
+        if(!ret)
+            return;
+        
+        TN_DEBUG2( "CThumbnailStore::ActivityChanged() KMPXHarvesting == %d", KMPXHarvesting);
+        
+        ret = RProperty::Get(KTAGDPSNotification, KDaemonProcessing, DaemonProcessing);
+        
+        if(!ret)
+            return;
+        
+        TN_DEBUG2( "CThumbnailStore::ActivityChanged() DaemonProcessing == %d", DaemonProcessing);
+        
+        if(!MPXHarvesting && !DaemonProcessing)
+            {
+            TN_DEBUG1( "CThumbnailStore::ActivityChanged() - starting maintenance");
+            iIdle = ETrue;
+            StartMaintenance();
+            }
+        }
+    }
+
+// CThumbnailStoreDiskSpaceNotifierAO class
+
 CThumbnailStoreDiskSpaceNotifierAO* CThumbnailStoreDiskSpaceNotifierAO::NewL(
         MThumbnailStoreDiskSpaceNotifierObserver& aObserver, TInt64 aThreshold, const TDesC& aFilename)
     {
@@ -2457,7 +2235,6 @@
     return (TDriveNumber)driveNumber;
     }
 
-
 CThumbnailStoreDiskSpaceNotifierAO::~CThumbnailStoreDiskSpaceNotifierAO()
     {
     TN_DEBUG1( "CThumbnailStoreDiskSpaceNotifierAO::~CThumbnailStoreDiskSpaceNotifierAO()");
@@ -2475,33 +2252,49 @@
         {
         TInt status = iStatus.Int();
         
+        TInt ret(KErrNone);
+        
         switch( status )
             {
             case KErrNone:
-                iFileServerSession.Volume( volumeInfo, iDrive );
+                ret = iFileServerSession.Volume( volumeInfo, iDrive );
                 
-                // Check if free space is less than threshold level
-                if( volumeInfo.iFree < iThreshold )
+                if(!ret)
                     {
-                    iDiskFull = ETrue;
-                    iObserver.HandleDiskSpaceNotificationL( iDiskFull );
-                    iState = EIterate;
-                    iIterationCount = 0;
-                    SetActive();
-                    TRequestStatus* status = &iStatus;
-                    User::RequestComplete( status, KErrNone );
-                    return;
+                    
+                    // Check if free space is less than threshold level
+                    if( volumeInfo.iFree < iThreshold )
+                        {
+                        TN_DEBUG1( "CThumbnailStoreDiskSpaceNotifierAO::RunL() FULL");
+                        iDiskFull = ETrue;
+                        iObserver.HandleDiskSpaceNotificationL( iDiskFull );
+                        iState = EIterate;
+                        iIterationCount = 0;
+                        SetActive();
+                        TRequestStatus* status = &iStatus;
+                        User::RequestComplete( status, KErrNone );
+                        return;
+                        }
+                    else
+                        {
+                        TN_DEBUG1( "CThumbnailStoreDiskSpaceNotifierAO::RunL() NOT FULL");
+                        iDiskFull = EFalse;
+                        iObserver.HandleDiskSpaceNotificationL( iDiskFull );
+                        }
                     }
                 else
                     {
+                    TN_DEBUG2( "CThumbnailStoreDiskSpaceNotifierAO::RunL() error %d NOT FULL", ret);
                     iDiskFull = EFalse;
                     iObserver.HandleDiskSpaceNotificationL( iDiskFull );
+                    User::Leave( ret );
                     }
+                
                 StartNotifier();
                 break;
 
             case KErrArgument:
-                TN_DEBUG1( "CThumbnailStoreDiskSpaceNotifierAO::GetDriveNumberL() KErrArgument");
+                TN_DEBUG1( "CThumbnailStoreDiskSpaceNotifierAO::RunL() KErrArgument");
                 User::Leave( status );
                 break;
             default:
@@ -2529,12 +2322,14 @@
                 iFileServerSession.Volume( volumeInfo, iDrive );
                 if ( volumeInfo.iFree >= iThreshold )
                     {
+                    TN_DEBUG1( "CThumbnailStoreDiskSpaceNotifierAO::RunL() NOT FULL");
                     iDiskFull = EFalse;
                     }
                 }
             }
         else
             {
+            TN_DEBUG1( "CThumbnailStoreDiskSpaceNotifierAO::RunL() NOT FULL");
             iDiskFull = EFalse;
             }
         iState = ENormal;
@@ -2543,13 +2338,15 @@
         }
     else
         {
+        TN_DEBUG1( "CThumbnailStoreDiskSpaceNotifierAO::RunL() KErrGeneral");
         User::Leave( KErrGeneral );
         }
     }
 
 TInt CThumbnailStoreDiskSpaceNotifierAO::RunError(TInt aError)
     {
-    TN_DEBUG1( "CThumbnailStoreDiskSpaceNotifierAO::RunError()");
+    TN_DEBUG2( "CThumbnailStoreDiskSpaceNotifierAO::RunError() %d", aError);
+    
     iObserver.HandleDiskSpaceError( aError );
     
     return KErrNone;
@@ -2558,6 +2355,7 @@
 void CThumbnailStoreDiskSpaceNotifierAO::DoCancel()
     {
     TN_DEBUG1( "CThumbnailStoreDiskSpaceNotifierAO::DoCancel()");
+    
     if( IsActive() )
         {   
         iFileServerSession.NotifyDiskSpaceCancel();
@@ -2581,10 +2379,21 @@
     User::LeaveIfError( iFileServerSession.Connect( KMessageSlotCount ) );
     
     TVolumeInfo volumeInfo;
-    iFileServerSession.Volume( volumeInfo, iDrive );    
-    if ( volumeInfo.iFree < iThreshold )
+    TInt ret = iFileServerSession.Volume( volumeInfo, iDrive );
+    
+    if( !ret )
         {
-        iDiskFull = ETrue;
+        if ( volumeInfo.iFree < iThreshold )
+            {
+            TN_DEBUG1( "CThumbnailStoreDiskSpaceNotifierAO::ConstructL() FULL");
+            iDiskFull = ETrue;
+            }
+        }
+    else
+        {
+        TN_DEBUG2( "CThumbnailStoreDiskSpaceNotifierAO::ConstructL() error %d NOT FULL", ret);
+        iDiskFull = EFalse;
+        User::Leave( ret );
         }
 
     iObserver.HandleDiskSpaceNotificationL( iDiskFull );
--- a/imagehandlingutilities/thumbnailmanager/tmcommon/inc/tmactivitymanager.h	Fri Feb 19 23:07:36 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/tmcommon/inc/tmactivitymanager.h	Fri Mar 12 15:43:57 2010 +0200
@@ -16,6 +16,7 @@
 */
 
 #include <e32base.h>
+#include <hwrmlight.h>
 
 #ifndef TMACTIVITYMANAGER_H
 #define TMACTIVITYMANAGER_H
@@ -25,12 +26,12 @@
 
 {
 public :
-    virtual void ActivityDetected() = 0;
-    virtual void InactivityDetected() = 0;
+    virtual void ActivityChanged(const TBool aActive) = 0;
 };
 
 
-class CTMActivityManager : public CActive
+class CTMActivityManager : public CActive,
+                           public MHWRMLightObserver
 
 {
 public:
@@ -53,6 +54,7 @@
     void Start();
     void Reset();
     void Stop();
+    TBool IsInactive();
 
 
 protected: // from CActive
@@ -63,8 +65,11 @@
 protected:
     CTMActivityManager(MTMActivityManagerObserver* aObserver, TInt aTimeout);
     void ConstructL();
-
-
+    void NotifyObserver();
+    
+private: //From MHWRMLightObserver
+    void LightStatusChanged(TInt aTarget, CHWRMLight::TLightStatus aStatus);
+    
 protected:
     enum TWatch { ENone = 0, EWaitingForInactivity, EWaitingForActivity };
 
@@ -73,7 +78,15 @@
     TWatch iWatch;
     MTMActivityManagerObserver* iObserver; ///The observer of activity status
     TInt iTimeout; ///Current inactivity period
+    
+    //Backlight control 
+    CHWRMLight* iLight;
+    //backlight status
+    TBool iLights;
 
+    //previous status
+    TInt iPreviousStatus;
+    TBool iFirstRound;
 };
 
 #endif // TMACTIVITYMANAGER_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/imagehandlingutilities/thumbnailmanager/tmcommon/inc/tmrpropertyobserver.h	Fri Mar 12 15:43:57 2010 +0200
@@ -0,0 +1,108 @@
+/*
+* Copyright (c) 2006-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* 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".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  TM RProperty Observer
+ *
+*/
+
+
+#ifndef TMRPROPERTYDOBSERVER_H
+#define TMRPROPERTYDOBSERVER_H
+
+#include <e32base.h>
+#include <w32std.h>
+#include <e32property.h> 
+
+
+/**
+ * Observer interface for signaling the RProperty change
+ */
+class MTMRPropertyObserver
+    {
+public:
+
+    virtual void RPropertyNotification(const TInt aError, const TUid aKeyCategory, const TUint aPropertyKey, const TInt aValue) = 0;
+    };
+
+/**
+ *  Active object for observing P&S keys
+ *
+ *  @since S60 v5.0
+ */
+class CTMRPropertyObserver: public CActive
+    {
+public:
+
+    /**
+     * Two-phased constructor.
+     *
+     * @since S60 v5.0
+     * @return Instance of CTMRPropertyObserver.
+     */
+    static CTMRPropertyObserver* NewL( MTMRPropertyObserver& aObserver, const TUid& aKeyCategory,
+                                      const TInt aPropertyKey, TBool aDefineKey);
+
+    /**
+     * Destructor
+     *
+     * @since S60 v5.0
+     */
+    virtual ~CTMRPropertyObserver();
+    
+protected:
+
+    /**
+     * Handles an active object's request completion event.
+     *
+     * @since S60 v5.0
+     */
+    void RunL();
+
+    /**
+     * Implements cancellation of an outstanding request.
+     *
+     * @since S60 v5.0
+     */
+    void DoCancel();
+
+private:
+
+    /**
+     * C++ default constructor
+     *
+     * @since S60 v5.0
+     * @return Instance of CTMRPropertyObserver.
+     */
+    CTMRPropertyObserver( MTMRPropertyObserver& aObserver, const TUid& aKeyCategory,
+                         const TInt iPropertyKey, TBool aDefineKey);
+
+    /**
+     * Symbian 2nd phase constructor can leave.
+     *
+     * @since S60 v5.0
+     */
+    void ConstructL();
+
+private:
+    
+    // not own
+    MTMRPropertyObserver& iObserver;
+    
+    const TUid& iKeyCategory;
+    RProperty iProperty;
+    TInt iPropertyKey;
+    
+    TBool iDefineKey;
+};
+
+#endif // TMRPROPERTYDOBSERVER_H
--- a/imagehandlingutilities/thumbnailmanager/tmcommon/src/tmactivitymanager.cpp	Fri Feb 19 23:07:36 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/tmcommon/src/tmactivitymanager.cpp	Fri Mar 12 15:43:57 2010 +0200
@@ -24,6 +24,7 @@
 //
 CTMActivityManager* CTMActivityManager::NewL(MTMActivityManagerObserver* aObserver, TInt aTimeout)
     {
+    TN_DEBUG1( "CTMActivityManager::NewL()");
     CTMActivityManager* self = new (ELeave) CTMActivityManager(aObserver, aTimeout);
     CleanupStack::PushL(self);
     self->ConstructL();
@@ -36,8 +37,9 @@
 // ---------------------------------------------------------------------------
 //
 CTMActivityManager::CTMActivityManager(MTMActivityManagerObserver* aObserver, TInt aTimeout)
-: CActive(CActive::EPriorityHigh), iObserver(aObserver), iTimeout(aTimeout)
-    {   
+: CActive(CActive::EPriorityHigh), iObserver(aObserver), iTimeout(aTimeout), iPreviousStatus(KErrNotFound)
+    {
+    TN_DEBUG1( "CTMActivityManager::CTMActivityManager()");
     CActiveScheduler::Add(this);
     }
 
@@ -47,6 +49,9 @@
 //
 CTMActivityManager::~CTMActivityManager()
     {
+    TN_DEBUG1( "CTMActivityManager::~CTMActivityManager()");
+    delete iLight;
+    iLight = NULL;
     Cancel();
     iTimer.Close();
     }
@@ -57,6 +62,7 @@
 //
 void CTMActivityManager::ConstructL()
     {
+    TN_DEBUG1( "CTMActivityManager::ConstructL()");
     iTimer.CreateLocal();
     }
 
@@ -66,6 +72,7 @@
 //
 void CTMActivityManager::SetTimeout(TInt aTimeout)
     {
+    TN_DEBUG1( "CTMActivityManager::SetTimeout()");
     iTimeout = aTimeout;
     Reset();
     }
@@ -76,6 +83,9 @@
 //
 void CTMActivityManager::Reset()
     {
+    TN_DEBUG1( "CTMActivityManager::Reset()");
+    delete iLight;
+    iLight = NULL;
     Cancel();
     Start();
     }
@@ -85,6 +95,7 @@
 // ---------------------------------------------------------------------------
 void CTMActivityManager::DoCancel()
     {
+    TN_DEBUG1( "CTMActivityManager::DoCancel()");
     iTimer.Cancel();
     iWatch = ENone;
     }
@@ -95,11 +106,20 @@
 //
 void CTMActivityManager::Start()
     {
-    if (!IsActive())
+    TN_DEBUG1( "CTMActivityManager::Start()");
+    
+    iFirstRound = ETrue;
+    
+    if(!iLight)
         {
-        iWatch = EWaitingForInactivity;
-        iTimer.Inactivity(iStatus, iTimeout);
+        TRAP_IGNORE(iLight = CHWRMLight::NewL(this));
+        }
+    
+    if( !IsActive() )
+        {
         SetActive();
+        TRequestStatus* statusPtr = &iStatus;
+        User::RequestComplete( statusPtr, KErrNone );
         }
     }
 
@@ -109,6 +129,22 @@
 //
 void CTMActivityManager::RunL()
     {
+    TN_DEBUG4( "CTMActivityManager::RunL(0x%08x) %d, observer = 0x%08x", this, iStatus.Int(), iObserver);
+    
+    if(iFirstRound)
+        {
+        TN_DEBUG1( "CTMActivityManager::RunL() iFirstRound");
+        iFirstRound = EFalse;
+        if (!IsActive())
+             {
+             iWatch = EWaitingForInactivity;
+             iTimer.Inactivity(iStatus, iTimeout);
+             SetActive();
+             }
+        NotifyObserver();
+        return;
+        }
+    
     if (iStatus == KErrNone)
         {
         if (iWatch == EWaitingForInactivity)
@@ -116,10 +152,9 @@
             TInt inactivity = User::InactivityTime().Int();
             if (inactivity >= iTimeout)
                 {
-                if (iObserver)
-                    {
-                    iObserver->InactivityDetected();
-                    }
+                TN_DEBUG1( "CTMActivityManager::RunL() inactive");
+                NotifyObserver();
+
             if (!IsActive()) //observer might have called a Reset()
                 {
                 iTimer.Inactivity(iStatus,0);
@@ -133,17 +168,15 @@
             }
         else if (iWatch == EWaitingForActivity)
             {
-            if (iObserver)
-                {
-                iObserver->ActivityDetected();
-                }
-            
+                TN_DEBUG1( "CTMActivityManager::RunL() active");
+                NotifyObserver();
+             
             if (!IsActive()) //observer might have called a Reset()
                 {
                 iTimer.Inactivity(iStatus,iTimeout);
                 iWatch = EWaitingForInactivity;
                 }
-        }
+            }
     
         if (!IsActive()) //observer might have called a Reset()
             {
@@ -154,6 +187,7 @@
         {
         iWatch = ENone;
         }
+        TN_DEBUG1( "CTMActivityManager::RunL() end");
     }
 
 // ---------------------------------------------------------------------------
@@ -162,11 +196,10 @@
 //
 TInt CTMActivityManager::RunError(TInt aError)
     {
-    TN_DEBUG1( "CTMActivityManager::RunError()");
+    TN_DEBUG2( "CTMActivityManager::RunError() %d", aError);
     
     if (aError != KErrNone)
         {
-        TN_DEBUG2( "CTMActivityManager::RunError = %d", aError );
         Reset();
         }
     
@@ -174,3 +207,63 @@
     return KErrNone;
     }
 
+// -----------------------------------------------------------------------------
+// IsInactive()
+// -----------------------------------------------------------------------------
+//
+TBool CTMActivityManager::IsInactive()
+    {
+#ifdef _DEBUG
+TN_DEBUG3( "CTMActivityManager::IsInactive()= %d, iLights = %d", User::InactivityTime().Int(), iLights);
+#endif
+
+    //if lights are off or inactivity timer is less that target the device is not idle
+    if( User::InactivityTime() >= TTimeIntervalSeconds(iTimeout) || !iLights )
+      {
+      TN_DEBUG1( "CTMActivityManager::IsInactive() ETrue");
+      return ETrue;
+      }
+    TN_DEBUG1( "CTMActivityManager::IsInactive() EFalse");
+    return EFalse;
+    }
+
+// -----------------------------------------------------------------------------
+// LightStatusChanged()
+// -----------------------------------------------------------------------------
+//
+void CTMActivityManager::LightStatusChanged(TInt /*aTarget*/, CHWRMLight::TLightStatus aStatus)
+    {
+    TN_DEBUG2( "CTMActivityManager::LightStatusChanged() aStatus == %d", aStatus);
+    
+     if( aStatus == CHWRMLight::ELightOff)
+        {
+        TN_DEBUG1( "CTMActivityManager::LightStatusChanged() -- OFF");
+        iLights = EFalse;
+        }
+    else
+        {
+        TN_DEBUG1( "CTMActivityManager::LightStatusChanged() -- ON");
+        iLights = ETrue;
+        }
+     
+        NotifyObserver();
+    }
+
+// -----------------------------------------------------------------------------
+// NotifyObserver()
+// -----------------------------------------------------------------------------
+//
+void CTMActivityManager::NotifyObserver()
+    {
+    TN_DEBUG1( "void CTMAActivityManager::NotifyObserver()");
+    TBool status = IsInactive();
+    
+    if( iPreviousStatus != status )
+        {
+        iPreviousStatus = status; 
+        if (iObserver)
+            {
+            iObserver->ActivityChanged(!status);
+            }
+        }
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/imagehandlingutilities/thumbnailmanager/tmcommon/src/tmsrproptertyobserver.cpp	Fri Mar 12 15:43:57 2010 +0200
@@ -0,0 +1,121 @@
+/*
+* Copyright (c) 2006-2007 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* 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".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  RPropery observer 
+*
+*/
+
+
+#include <e32base.h>
+
+#include "tmrpropertyobserver.h"
+#include "thumbnailmanagerconstants.h"
+#include "thumbnaillog.h"
+
+// ---------------------------------------------------------------------------
+// CTMRPropertyObserver::NewL()
+// ---------------------------------------------------------------------------
+//
+CTMRPropertyObserver* CTMRPropertyObserver::NewL( MTMRPropertyObserver& aObserver,
+                                                const TUid& aKeyCategory,
+                                                const TInt aPropertyKey,
+                                                TBool aDefineKey)
+    { 
+    CTMRPropertyObserver* self = new( ELeave )CTMRPropertyObserver( aObserver, 
+                                                                  aKeyCategory,
+                                                                  aPropertyKey,
+                                                                  aDefineKey);
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// CTMRPropertyObserver::CTMRPropertyObserver()
+// ---------------------------------------------------------------------------
+//
+CTMRPropertyObserver::CTMRPropertyObserver( MTMRPropertyObserver& aObserver,
+                                          const TUid& aKeyCategory,
+                                          const TInt aPropertyKey,
+                                          TBool aDefineKey)
+    : CActive( CActive::EPriorityStandard ), iObserver( aObserver ),
+      iKeyCategory( aKeyCategory ), iPropertyKey(aPropertyKey), iDefineKey( aDefineKey )
+    {   
+    CActiveScheduler::Add( this );
+    }
+
+// ---------------------------------------------------------------------------
+// CTMRPropertyObserver::ConstructL()
+// ---------------------------------------------------------------------------
+//
+void CTMRPropertyObserver::ConstructL()
+    { 
+    TN_DEBUG1( "CTMRPropertyObserver::ConstructL()");
+    // define P&S property types
+    if (iDefineKey)
+        {
+        RProperty::Define(iKeyCategory,iPropertyKey,
+                          RProperty::EInt);
+        }
+    
+    // attach to the property
+    TInt err = iProperty.Attach(iKeyCategory,iPropertyKey,EOwnerThread);
+    User::LeaveIfError(err);
+    
+    SetActive();
+    TRequestStatus* statusPtr = &iStatus;
+    User::RequestComplete( statusPtr, KErrNone );
+    }
+
+// ---------------------------------------------------------------------------
+// CTMRPropertyObserver::~CTMRPropertyObserver()
+// ---------------------------------------------------------------------------
+//
+CTMRPropertyObserver::~CTMRPropertyObserver()
+    {
+    TN_DEBUG1( "CTMRPropertyObserver::~CTMRPropertyObserver()");
+    Cancel();
+    iProperty.Close();
+    }
+
+// ---------------------------------------------------------------------------
+// CTMRPropertyObserver::RunL()
+// ---------------------------------------------------------------------------
+//
+void CTMRPropertyObserver::RunL()
+    {
+    TN_DEBUG1( "CTMRPropertyObserver::RunL()");
+    // resubscribe before processing new value to prevent missing updates
+    iProperty.Subscribe(iStatus);
+    SetActive();
+    
+    // retrieve the value
+    TInt value = 0;
+    TInt ret = iProperty.Get(value);
+
+    // observer callback
+    iObserver.RPropertyNotification(ret, iKeyCategory, iPropertyKey, value);
+    }
+
+// ---------------------------------------------------------------------------
+// CTMRPropertyObserver::DoCancel()
+// ---------------------------------------------------------------------------
+//
+void CTMRPropertyObserver::DoCancel()
+    {
+    TN_DEBUG1( "CTMRPropertyObserver::DoCancel()");
+    iProperty.Cancel();
+    }
+
+// End of file