Revision: 201007
authorDremov Kirill (Nokia-D-MSW/Tampere) <kirill.dremov@nokia.com>
Fri, 19 Mar 2010 09:35:30 +0200
changeset 14 2edacbf5d3f9
parent 1 235a7fc86938
child 15 7197e789b953
Revision: 201007 Kit: 201011
imagehandling_plat/group/bld.inf
imagehandling_plat/thumbnailmanager_api/group/bld.inf
imagehandling_plat/thumbnailmanager_api/inc/thumbnailmanager_qt.h
imagehandling_plat/thumbnailmanager_api/tsrc/conf/ThumbnailManagerTest.cfg
imagehandling_plat/thumbnailmanager_api/tsrc/data/mmc/ThumbnailManagerTest/camera.jpg
imagehandling_plat/thumbnailmanager_api/tsrc/group/ThumbnailManagerTest.pkg
imagehandling_plat/thumbnailmanager_api/tsrc/group/bld.inf
imagehandling_plat/thumbnailmanager_api/tsrc/src/ThumbnailManagerTestBlocks.cpp
imagehandlingutilities/group/bld.inf
imagehandlingutilities/thumbnailmanager/inc/thumbnaillog.h
imagehandlingutilities/thumbnailmanager/inc/thumbnailmanagerconstants.h
imagehandlingutilities/thumbnailmanager/plugins/audio/inc/thumbnailimagedecoderv3.h
imagehandlingutilities/thumbnailmanager/plugins/audio/src/thumbnailaudioprovider.cpp
imagehandlingutilities/thumbnailmanager/plugins/audio/src/thumbnailimagedecoderv3.cpp
imagehandlingutilities/thumbnailmanager/plugins/image/inc/thumbnailimagedecoder.h
imagehandlingutilities/thumbnailmanager/plugins/image/inc/thumbnailimagedecoderv2.h
imagehandlingutilities/thumbnailmanager/plugins/image/src/thumbnailimagedecoder.cpp
imagehandlingutilities/thumbnailmanager/plugins/image/src/thumbnailimagedecoderv2.cpp
imagehandlingutilities/thumbnailmanager/plugins/video/inc/thumbnailvideoprovider.h
imagehandlingutilities/thumbnailmanager/plugins/video/src/thumbnailvideoprovider.cpp
imagehandlingutilities/thumbnailmanager/sis/thumbnailmanager/ThumbnailManager_0x102830AB_v9.20.2_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/thumbagformatobserver.h
imagehandlingutilities/thumbnailmanager/thumbagdaemon/inc/thumbagprocessor.h
imagehandlingutilities/thumbnailmanager/thumbagdaemon/inc/thumblog.h
imagehandlingutilities/thumbnailmanager/thumbagdaemon/src/thumbagdaemon.cpp
imagehandlingutilities/thumbnailmanager/thumbagdaemon/src/thumbagformatobserver.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/thumbnailmanagerqt/bwins/thumbnailmanagerqt.def
imagehandlingutilities/thumbnailmanager/thumbnailmanagerqt/eabi/thumbnailmanagerqt.def
imagehandlingutilities/thumbnailmanager/thumbnailmanagerqt/inc/thumbnailmanager_p_qt.h
imagehandlingutilities/thumbnailmanager/thumbnailmanagerqt/src/thumbnailmanager_p_qt.cpp
imagehandlingutilities/thumbnailmanager/thumbnailmanagerqt/src/thumbnailmanager_qt.cpp
imagehandlingutilities/thumbnailmanager/thumbnailmanagerqt/thumbnailmanagerqt.iby
imagehandlingutilities/thumbnailmanager/thumbnailmanagerqt/thumbnailmanagerqt.pro
imagehandlingutilities/thumbnailmanager/thumbnailserver/group/thumbnailserver.mmp
imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/thumbnailcenrep.h
imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/thumbnailformatobserver.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/inc/thumbnailtask.h
imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/tmgetimei.h
imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/tmshutdownobserver.h
imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/tnmgetimei.h
imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailcenrep.cpp
imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnaildecodetask.cpp
imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailformatobserver.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/thumbnailserver/src/thumbnailtask.cpp
imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailtaskprocessor.cpp
imagehandlingutilities/thumbnailmanager/thumbnailserver/src/tmgetimei.cpp
imagehandlingutilities/thumbnailmanager/thumbnailserver/src/tmshutdownobserver.cpp
imagehandlingutilities/thumbnailmanager/thumbnailserver/src/tnmgetimei.cc
imagehandlingutilities/thumbnailmanager/tmcommon/inc/tmactivitymanager.h
imagehandlingutilities/thumbnailmanager/tmcommon/inc/tmformatobserver.h
imagehandlingutilities/thumbnailmanager/tmcommon/inc/tmrpropertyobserver.h
imagehandlingutilities/thumbnailmanager/tmcommon/inc/tmshutdownobserver.h
imagehandlingutilities/thumbnailmanager/tmcommon/src/tmactivitymanager.cpp
imagehandlingutilities/thumbnailmanager/tmcommon/src/tmformatobserver.cpp
imagehandlingutilities/thumbnailmanager/tmcommon/src/tmshutdownobserver.cpp
imagehandlingutilities/thumbnailmanager/tmcommon/src/tmsrproptertyobserver.cpp
layers.sysdef.xml
sysdef_1_4_0.dtd
sysdef_1_5_1.dtd
--- a/imagehandling_plat/group/bld.inf	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandling_plat/group/bld.inf	Fri Mar 19 09:35:30 2010 +0200
@@ -17,11 +17,13 @@
 */
 
 
+
 #include "../image_handling_library_api/group/bld.inf"
 #include "../3gp_library_api/group/bld.inf"
 #include "../thumbnailmanager_api/group/bld.inf"
 
 
+
 // End of File
 
 
--- a/imagehandling_plat/thumbnailmanager_api/group/bld.inf	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandling_plat/thumbnailmanager_api/group/bld.inf	Fri Mar 19 09:35:30 2010 +0200
@@ -29,6 +29,7 @@
 ../inc/thumbnailmanager.h     MW_LAYER_PLATFORM_EXPORT_PATH(thumbnailmanager.h)
 ../inc/thumbnailmanagerobserver.h     MW_LAYER_PLATFORM_EXPORT_PATH(thumbnailmanagerobserver.h)
 ../inc/thumbnailobjectsource.h     MW_LAYER_PLATFORM_EXPORT_PATH(thumbnailobjectsource.h)
+../inc/thumbnailmanager_qt.h    MW_LAYER_PLATFORM_EXPORT_PATH(thumbnailmanager_qt.h)
 
 #endif // RD_THUMBNAILMANAGER
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/imagehandling_plat/thumbnailmanager_api/inc/thumbnailmanager_qt.h	Fri Mar 19 09:35:30 2010 +0200
@@ -0,0 +1,282 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "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: Qt interface class to Thumbnail Manager
+*
+*/
+
+#ifndef THUMBNAILMANAGER_QT_H
+#define THUMBNAILMANAGER_QT_H
+
+#include <qobject>
+#include <QPixmap.h>
+
+class ThumbnailManagerPrivate;
+class QString;
+class QSize;
+
+/** default priority value */
+const int tnmWrapperPriorityIdle = -100;
+
+class ThumbnailManager : public QObject
+    {
+    Q_OBJECT
+
+public:
+
+
+    /** Thumbnail size. */
+    enum ThumbnailSize
+    {
+        /**
+         * Small thumbnail
+         */
+        ThumbnailSmall = 0, 
+        /**
+         * Medium thumbnail
+         */
+        ThumbnailMedium, 
+        /**
+         * Large thumbnail
+         */
+        ThumbnailLarge
+    };
+    
+    /** Mode of thumbnail creation. */
+    enum ThumbnailMode
+        {
+        /**
+         * Default mode. This means that:
+         * - Thumbnail must be as large as requested (unless the actual object is smaller).
+         * - Smaller thumbnails may be up scaled to desired resolution.
+         * - Aspect ratio is maintained and thumbnails are not cropped. The
+         *   resulting thumbnail may smaller in either width or height if
+         *   the aspect ratio of the object does not match the aspect ratio
+         *   of the requested size.
+         */
+        Default = 0, 
+
+        /**
+         * Allow thumbnails which are smaller than requested are. Thumbnail
+         * bitmaps are never up scaled if this flag is set.
+         */
+        AllowAnySize = 1, 
+
+        /**
+         * New thumbnail images are not created if this flag is set. Only
+         * existing thumbnails may be returned. If a requested thumbnail does
+         * not exist null pixmap will be returned.
+         */
+        DoNotCreate = 2, 
+
+        /**
+         * Thumbnail images are cropped to match requested aspect ratio. If
+         * this mode is set, the size of the resulting thumbnail always
+         * matches the requested size.
+         */
+        CropToAspectRatio = 4
+    };
+    
+    /**  Quality versus speed preference setting */
+    enum QualityPreference
+    {
+        /**
+         * Prefer thumbnails in the highest quality possible disregarding
+         * any negative impact on performance.
+         */
+        OptimizeForQuality, 
+
+        /**
+         * Get thumbnails as fast as possible, even if
+         * it means lower quality.
+         */
+        OptimizeForPerformance
+    };
+
+    
+    /**
+     * Constructor
+     * 
+     * @param parentPtr parent
+     */    
+    IMPORT_C ThumbnailManager( QObject* parentPtr = NULL );
+
+    /**
+     * Destructor
+     */
+    IMPORT_C ~ThumbnailManager();
+
+    /**
+     * Get quality versus performance preference.
+     *
+     * @return quality versus performance preference
+     */
+    IMPORT_C QualityPreference qualityPreference() const;
+
+    /**
+     * Set quality versus performance preference.
+     *
+     * @param qualityPreference New quality versus performance preference
+     *                           value.
+     * @return true on success
+     */
+    IMPORT_C bool setQualityPreference( QualityPreference qualityPreference );
+
+    /**
+     * Get the current desired size for thumbnail bitmaps.
+     *
+     * @return Current desired size for thumbnail bitmaps (in pixels).
+     */
+    IMPORT_C QSize thumbnailSize() const;
+
+    /**
+     * Set desired size for thumbnail bitmaps.
+     *
+     * @param thumbnailSize New desired thumbnail size.
+     * @return true on success
+     */
+    IMPORT_C bool setThumbnailSize( const QSize& thumbnailSize );
+
+    /**
+     * Set desired size for thumbnail bitmaps.
+     *
+     * @param thumbnailSize New desired thumbnail size.
+     * @return true on success
+     */
+    IMPORT_C bool setThumbnailSize( ThumbnailSize thumbnailSize );
+    
+    /**
+     * Get current mode for thumbnail generation.
+     *
+     * @return Current mode.
+     */
+    IMPORT_C ThumbnailMode mode() const;
+
+    /**
+     * Set mode for thumbnail generation.
+     *
+     * @param mode New flags.
+     * @return true on success 
+     */
+    IMPORT_C bool setMode( ThumbnailMode mode );
+
+    /**
+     * Get a thumbnail for an object file. If a thumbnail already exists, it
+     * is loaded and if a thumbnail does not exist, it is created
+     * transparently. If thumbnail loadinf fails thumbnailReady signal is emited 
+     * with null pixmap and error code.
+     *
+     * @param fileName      Source object or file
+     * @param clientData    Pointer to arbitrary client data.
+     *                      This pointer is not used by the API for
+     *                      anything other than returning it in the
+     *                      ThumbnailReady signal.
+     * @param priority      Priority for this operation
+     * @return              Thumbnail request ID or -1 if request failed. This can be used to
+     *                      cancel the request or change priority.
+     *                      The ID is specific to this tnm
+     *                      instance and may not be shared with other
+     *                      instances.
+     */
+    IMPORT_C int getThumbnail( const QString& fileName, void * clientData = NULL, 
+            int priority = tnmWrapperPriorityIdle );
+
+    /**
+     * Get a persistent thumbnail for an object file. If a thumbnail already
+     * exists, it is loaded and if a thumbnail does not exist, it is created
+     * transparently. If thumbnail loading fails thumbnailReady signal is emited 
+     * with null pixmap and error code.
+     *
+     * @param thumbnailId   Thumbnail ID
+     * @param clientData    Pointer to arbitrary client data.
+     *                      This pointer is not used by the API for
+     *                      anything other than returning it in the
+     *                      ThumbnailReady signal.
+     * @param priority      Priority for this operation
+     * @return              Thumbnail request ID or -1 if request failed. This can be used to
+     *                      cancel the request or change priority.
+     *                      The ID is specific to this tnm
+     *                      instance and may not be shared with other
+     *                      instances.
+     */    
+    IMPORT_C int getThumbnail( unsigned long int thumbnailId, void * clientData = NULL, 
+            int priority = tnmWrapperPriorityIdle );
+    
+    /**
+     * Set a thumbnail for an object file generated from pixmap delivered.
+     * thumbnailReady() signal will be emited when the operation is complete. 
+     * 
+     * @param source             Pixmap from which the thumbnail will be created
+     * @param fileName           file name
+     * @param clientData         Pointer to arbitrary client data.
+     *                           This pointer is not used by the API for
+     *                           anything other than returning it in the
+     *                           ThumbnailReady callback.
+     * @param priority           Priority for this operation
+     * @return                   Thumbnail request ID or -1 if request failed. This can be used to
+     *                           cancel the request or change priority. 
+     *                           
+     */    
+    IMPORT_C int setThumbnail( const QPixmap& source, const QString& fileName,
+            void * clientData = NULL, int priority = tnmWrapperPriorityIdle );
+    
+    /**
+     * Delete all thumbnails for a given object. This is an asynchronous
+     * operation, which always returns immediately.
+     *
+     * @param fileName      Source file
+     */
+    IMPORT_C void deleteThumbnails( const QString& fileName );
+
+    /**
+     * Delete all thumbnails for a given object. This is an asynchronous
+     * operation, which always returns immediately.
+     *
+     * @param thumbnailId      thumbnail id
+     */
+    IMPORT_C void deleteThumbnails( unsigned long int thumbnailId );
+
+    /**
+     * Cancel a thumbnail operation.
+     *
+     * @param id      Request ID for the operation to be cancelled.
+     * @return         true if cancelling was successful.
+     */
+    IMPORT_C bool cancelRequest( int id );
+
+    /**
+     * Change the priority of a queued thumbnail operation.
+     *
+     * @param id           Request ID for the request which to assign a new
+     *                      priority.
+     * @param newPriority  New priority value
+     * @return              true if change was successful.
+     */
+    IMPORT_C bool changePriority( int id, int newPriority );
+    
+signals:  
+    /**
+     * Final thumbnail bitmap generation or loading is complete.
+     *
+     * @param pixmap     An object representing the resulting thumbnail.
+     * @param clientData Client data
+     * @param id         Request ID for the operation
+     * @param errorCode  error code
+     */
+    void thumbnailReady( QPixmap , void * , int , int );    
+    
+private:
+    ThumbnailManagerPrivate* d;
+};
+
+#endif // THUMBNAILMANAGER_QT
--- a/imagehandling_plat/thumbnailmanager_api/tsrc/conf/ThumbnailManagerTest.cfg	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandling_plat/thumbnailmanager_api/tsrc/conf/ThumbnailManagerTest.cfg	Fri Mar 19 09:35:30 2010 +0200
@@ -54,8 +54,6 @@
 // reaches the server, but doesn't have enough time to complete yet
 // (milliseconds)
 KClientServerDelay 150
-KClientServerDelay2 25
-KClientServerDelay3 10
 
 // From TDisplayMode: value for 24-bit display mode
 EColor16M 8
@@ -1858,14 +1856,12 @@
 pause KTenSecondDelay
 
 tn UpdatePathL 99999 \data\ThumbnailManagerTest\updated_path.bmp
-waittestclass tn
 
 pause KTenSecondDelay
 
 tn SetFlagsL EDoNotCreate
 tn CreateSourceInstancePathL \data\ThumbnailManagerTest\RGB_VGA.jpg
 tn GetThumbnailL
-allownextresult KErrNotFound
 waittestclass tn
 tn DeleteSourceInstance
 
@@ -1938,7 +1934,7 @@
 tn GetThumbnailL
 tn DeleteSourceInstance
 
-pause KClientServerDelay2
+pause KClientServerDelay
 
 // The server should have the two thumbnail requests queued by now.
 // This should cancel the second one while letting the first one finish.
@@ -1972,22 +1968,25 @@
 tn DeleteThumbnails
 tn DeleteSourceInstance
 
-// First request with 100 priority
+// First request with 0 priority
 tn SetThumbnailSizeL 80 40
 tn CreateSourceInstanceHandleL \data\ThumbnailManagerTest\WIDE_800x400.gif
-tn GetThumbnailL 0 100
+tn GetThumbnailL 0 0
 tn DeleteSourceInstance
 
+// Short delay to make sure the server starts processing this request
+pause KClientServerDelay
+
 // Second request with negative priority
 tn SetThumbnailSizeL 1 1
 tn CreateSourceInstanceHandleL \data\ThumbnailManagerTest\TALL_400x800.bmp
-tn GetThumbnailL 0 -50
+tn GetThumbnailL 0 -10
 tn DeleteSourceInstance
 
 // Third request with positive priority
 tn SetThumbnailSizeL 40 30
 tn CreateSourceInstanceHandleL \data\ThumbnailManagerTest\SVG_640x480.svg
-tn GetThumbnailL 0 50
+tn GetThumbnailL 0 10
 tn DeleteSourceInstance
 
 // First request should complete first, since the server started processing
@@ -1995,7 +1994,8 @@
 waittestclass tn
 tn CheckThumbnailL 80 40 EColor16M
 
-// The third request should finish next
+// The third request should finish next, since it had the highest priority of
+// the other tasks.
 waittestclass tn
 tn CheckThumbnailL 40 30 EColor16M
 
@@ -2044,27 +2044,31 @@
 tn GetThumbnailL 0 0
 tn DeleteSourceInstance
 
+// Short delay to make sure the server starts processing this request
+pause KClientServerDelay
+
 // Second request with negative priority
 tn SetThumbnailSizeL 1 1
 tn CreateSourceInstanceHandleL \data\ThumbnailManagerTest\TALL_400x800.bmp
-tn GetThumbnailL 0 -50
+tn GetThumbnailL 0 -10
 tn DeleteSourceInstance
 
 // Third request with positive priority
 tn SetThumbnailSizeL 40 30
 tn CreateSourceInstanceHandleL \data\ThumbnailManagerTest\SVG_640x480.svg
-tn GetThumbnailL 0 50
+tn GetThumbnailL 0 10
 tn DeleteSourceInstance
 
 // Change the priority of the third request to a low value
-tn ChangePreviousPriority -100
+tn ChangePreviousPriority -20
 
 // First request should complete first, since the server started processing
 // it before the other requests were done
 waittestclass tn
 tn CheckThumbnailL 80 40 EColor16M
 
-// The second request should finish next
+// The second request should finish next, since it had the highest priority of
+// the other tasks.
 waittestclass tn
 tn CheckThumbnailL 1 1 EColor16M
 
@@ -2118,14 +2122,15 @@
 
 pause KTenSecondDelay
 
-tn DeleteSourceInstance
-
-tn CreateSourceInstancePathL \data\ThumbnailManagerTest\camera.jpg
 tn SetFlagsL EDoNotCreate
 tn SetThumbnailEnumSizeL EImageGridThumbnailSize
 tn GetThumbnailL
 waittestclass tn
 tn CheckThumbnailCenrepL EImageGridThumbnailSize EColor16M
+tn SetThumbnailEnumSizeL EImageListThumbnailSize
+tn GetThumbnailL
+waittestclass tn
+tn CheckThumbnailCenrepL EImageListThumbnailSize EColor16M
 tn SetThumbnailEnumSizeL EImageFullScreenThumbnailSize
 tn GetThumbnailL
 waittestclass tn
Binary file imagehandling_plat/thumbnailmanager_api/tsrc/data/mmc/ThumbnailManagerTest/camera.jpg has changed
--- a/imagehandling_plat/thumbnailmanager_api/tsrc/group/ThumbnailManagerTest.pkg	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandling_plat/thumbnailmanager_api/tsrc/group/ThumbnailManagerTest.pkg	Fri Mar 19 09:35:30 2010 +0200
@@ -45,5 +45,4 @@
 "..\data\mmc\ThumbnailManagerTest\WIDE_800x400.gif" - "e:\testing\data\ThumbnailManagerTest\WIDE_800x400.gif"
 "..\data\mmc\ThumbnailManagerTest\TestMBM.mbm" - "e:\testing\data\ThumbnailManagerTest\TestMBM.mbm"
 "..\data\mmc\ThumbnailManagerTest\mp3.mp3" - "e:\testing\data\ThumbnailManagerTest\mp3.mp3"
-"..\data\mmc\ThumbnailManagerTest\camera.jpg" - "e:\testing\data\ThumbnailManagerTest\camera.jpg"
 
--- a/imagehandling_plat/thumbnailmanager_api/tsrc/group/bld.inf	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandling_plat/thumbnailmanager_api/tsrc/group/bld.inf	Fri Mar 19 09:35:30 2010 +0200
@@ -43,6 +43,5 @@
 ../data/mmc/ThumbnailManagerTest/WIDE_800x400.gif /epoc32/winscw/c/data/ThumbnailManagerTest/WIDE_800x400.gif
 ../data/mmc/ThumbnailManagerTest/TestMBM.mbm /epoc32/winscw/c/data/ThumbnailManagerTest/TestMBM.mbm
 ../data/mmc/ThumbnailManagerTest/mp3.mp3 /epoc32/winscw/c/data/ThumbnailManagerTest/mp3.mp3
-../data/mmc/ThumbnailManagerTest/camera.jpg /epoc32/winscw/c/data/ThumbnailManagerTest/camera.jpg
 
 //  End of File
--- a/imagehandling_plat/thumbnailmanager_api/tsrc/src/ThumbnailManagerTestBlocks.cpp	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandling_plat/thumbnailmanager_api/tsrc/src/ThumbnailManagerTestBlocks.cpp	Fri Mar 19 09:35:30 2010 +0200
@@ -627,7 +627,6 @@
 TInt CThumbnailManagerTest::CheckThumbnailCenrepL( CStifItemParser& aItem )
     {
     TInt err = KErrNone;
-    TBool full = EFalse;
     
     TInt sizeType;
     TInt displaymode = 0;
@@ -635,12 +634,6 @@
     User::LeaveIfError( aItem.GetNextInt( displaymode ));
     
     TThumbnailSize size = (TThumbnailSize)sizeType;
-    if (size == EImageFullScreenThumbnailSize ||
-        size == EVideoFullScreenThumbnailSize ||
-        size == EAudioFullScreenThumbnailSize)
-        {
-        full = ETrue;
-        }
     
     if ( iThumbnail )
         {
@@ -670,10 +663,6 @@
             {
             iLog->Log( _L( "CheckThumbnailCenrepL - ok" ));
             }
-        else if (full && (thumbSize.iWidth <= width && thumbSize.iHeight <= height))
-            {
-            iLog->Log( _L( "CheckThumbnailCenrepL - fullscreen ok, not upscaled" ));
-            }
         else
             {
             iLog->Log( _L( "CheckThumbnailCenrepL - size mismatch" ));
--- a/imagehandlingutilities/group/bld.inf	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandlingutilities/group/bld.inf	Fri Mar 19 09:35:30 2010 +0200
@@ -16,9 +16,11 @@
 */
 
 
+
 #include "../thumbnailmanager/group/bld.inf"
 
 
+
 // End of File
 
 
--- a/imagehandlingutilities/thumbnailmanager/inc/thumbnaillog.h	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/inc/thumbnaillog.h	Fri Mar 19 09:35:30 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	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/inc/thumbnailmanagerconstants.h	Fri Mar 19 09:35:30 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,7 +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 = 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
@@ -83,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*" );
@@ -246,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
      */
@@ -362,8 +390,8 @@
     EChangePriority, 
 
     /**
-     * Create thumbnails for a file. File path is passed as a
-     * parameter.
+     * Deprecated
+     *
      */
     ECreateThumbnails, 
 
@@ -517,10 +545,6 @@
 enum TMDSQueryType
     {
     /**
-     * Query Id by Path
-     */
-    EId,
-    /**
      * Query Path by Id
      */
     EURI
--- a/imagehandlingutilities/thumbnailmanager/plugins/audio/inc/thumbnailimagedecoderv3.h	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/plugins/audio/inc/thumbnailimagedecoderv3.h	Fri Mar 19 09:35:30 2010 +0200
@@ -85,6 +85,13 @@
      * @return Size of original image.
      */
     const TSize& OriginalSize()const;
+    
+    /**
+     * Leave if image is corrupt
+     *
+     * @since S60 v5.0
+     */
+    void LeaveIfCorruptL(const TInt aError );
 
 private:
     /**
--- a/imagehandlingutilities/thumbnailmanager/plugins/audio/src/thumbnailaudioprovider.cpp	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/plugins/audio/src/thumbnailaudioprovider.cpp	Fri Mar 19 09:35:30 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 */)
     {
-
+    TN_DEBUG1( "CThumbnailAudioProvider::GetThumbnailL() - buffer no mime" );
+	__ASSERT_DEBUG((EFalse), User::Panic(_L("CThumbnailAudioProvider::GetThumbnailL"), KErrNotSupported));
     }
 
 // ---------------------------------------------------------------------------
--- a/imagehandlingutilities/thumbnailmanager/plugins/audio/src/thumbnailimagedecoderv3.cpp	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/plugins/audio/src/thumbnailimagedecoderv3.cpp	Fri Mar 19 09:35:30 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"
@@ -198,18 +198,25 @@
     iDecoder = NULL;
 	
     CImageDecoder::TOptions options = ( CImageDecoder::TOptions )( 
-            CImageDecoder::EOptionNoDither | CImageDecoder::EPreferFastDecode );
+            CImageDecoder::EOptionNoDither | CImageDecoder::EPreferFastDecode | CImageDecoder::EOptionAlwaysThread );
  
     TRAPD( decErr, iDecoder = CExtJpegDecoder::DataNewL(
             CExtJpegDecoder::EHwImplementation, iFs, *iBuffer, options ));
     
     if ( decErr != KErrNone )
         {
+        TN_DEBUG2( "CThumbnailImageDecoderv3::CreateDecoderL() - HW CExtJpegDecoder failed %d", decErr);
+        
+        LeaveIfCorruptL( decErr );
+        
         TRAP( decErr, iDecoder = CExtJpegDecoder::DataNewL(
                 CExtJpegDecoder::ESwImplementation, iFs, *iBuffer, options ));
         
         if ( decErr != KErrNone )
-            {                                              
+            {                             
+            TN_DEBUG2( "CThumbnailImageDecoderv3::CreateDecoderL() - SW CExtJpegDecoder failed %d", decErr);
+            
+            LeaveIfCorruptL( decErr );
             // don't force any mime type
             TRAPD( decErr, iDecoder = CImageDecoder::DataNewL( iFs, *iBuffer, options ) );
             if ( decErr != KErrNone )
@@ -217,7 +224,7 @@
                 delete iBuffer;
                 iBuffer = NULL;
                 
-                TN_DEBUG1( "CThumbnailImageDecoderv3::CreateDecoderL() - error" );
+                TN_DEBUG2( "CThumbnailImageDecoderv3::CreateDecoderL() - CImageDecoder error %d", decErr );
                 
                 User::Leave( decErr );
                 }     
@@ -246,4 +253,18 @@
     return iOriginalSize;
     }
 
+// -----------------------------------------------------------------------------
+// CThumbnailImageDecoder3::LeaveIfCorruptL()
+// Leave is image is corrupted
+// -----------------------------------------------------------------------------
+//
+void CThumbnailImageDecoderv3::LeaveIfCorruptL(const TInt aError )
+    {
+    //no sense to try other codecs if image is corrupted
+    if( aError == KErrCorrupt || aError == KErrUnderflow)
+        {
+        User::Leave( aError );
+        }
+    }
+
 //End of file
--- a/imagehandlingutilities/thumbnailmanager/plugins/image/inc/thumbnailimagedecoder.h	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/plugins/image/inc/thumbnailimagedecoder.h	Fri Mar 19 09:35:30 2010 +0200
@@ -102,6 +102,13 @@
      * @return Size of original image.
      */
     const TSize& OriginalSize()const;
+	
+     /**
+     * Leave if image is corrupt
+     *
+     * @since S60 v5.0
+     */
+    void LeaveIfCorruptL(const TInt aError );
 
 private:
     /**
--- a/imagehandlingutilities/thumbnailmanager/plugins/image/inc/thumbnailimagedecoderv2.h	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/plugins/image/inc/thumbnailimagedecoderv2.h	Fri Mar 19 09:35:30 2010 +0200
@@ -96,6 +96,13 @@
      * @since S60 v5.0
      */
     void CreateDecoderL();
+    
+     /**
+     * Leave if image is corrupt
+     *
+     * @since S60 v5.0
+     */
+    void LeaveIfCorruptL(const TInt aError );
 
 private:
     // data
--- a/imagehandlingutilities/thumbnailmanager/plugins/image/src/thumbnailimagedecoder.cpp	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/plugins/image/src/thumbnailimagedecoder.cpp	Fri Mar 19 09:35:30 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"
@@ -338,7 +338,7 @@
     // If the image is in jpeg format, try to get thumbnail from EXIF data (if EOptimizeForQuality not set)
     if ( IsJpeg() && !( aFlags == CThumbnailManager::EOptimizeForQuality ))
         {
-        TN_DEBUG1( "CThumbnailImageDecoder::CreateDecoderL() crete exif decoder" );
+        TN_DEBUG1( "CThumbnailImageDecoder::CreateDecoderL() create exif decoder" );
         TRAPD( err, CreateExifDecoderL( aFlags ));
         thumbFound = ( err == KErrNone );
         iEXIF = ETrue;
@@ -347,7 +347,7 @@
     if ( !thumbFound )
         {
         iEXIF = EFalse;
-        TN_DEBUG1( "CThumbnailImageDecoder::CreateDecoderL() crete normal decoder" );
+        TN_DEBUG1( "CThumbnailImageDecoder::CreateDecoderL() create normal decoder" );
         
         delete iDecoder;
         iDecoder = NULL;
@@ -362,12 +362,12 @@
         if ( aFlags == CThumbnailManager::EOptimizeForQuality )
             {
             options = ( CImageDecoder::TOptions )( CImageDecoder
-                ::EOptionNoDither );
+                ::EOptionNoDither | CImageDecoder::EOptionAlwaysThread );
             }
         else
             {
-            options = ( CImageDecoder::TOptions )( CImageDecoder
-                ::EOptionNoDither | CImageDecoder::EPreferFastDecode );
+            options  = ( CImageDecoder::TOptions )( CImageDecoder
+                ::EOptionNoDither | CImageDecoder::EPreferFastDecode | CImageDecoder::EOptionAlwaysThread );
             }
 
         if ( IsSvg())
@@ -407,11 +407,15 @@
                 
                 if ( decErr != KErrNone )
                     {                        
+                    TN_DEBUG2( "CThumbnailImageDecoder::CreateDecoderL() - CImageDecoder error %d", decErr );
+                    LeaveIfCorruptL(decErr);
+                    
                     // don't force any mime type
                     TRAPD( decErr, iDecoder = CImageDecoder::DataNewL( iFs, *iBuffer, options ) );
+                    
                     if ( decErr != KErrNone )
                         {                        
-                        TN_DEBUG1( "CThumbnailImageDecoder::CreateDecoderL() - error 2" );
+                        TN_DEBUG2( "CThumbnailImageDecoder::CreateDecoderL() - CImageDecoder no mime error %d", decErr );
                         
                         User::Leave( decErr );
                         }
@@ -422,7 +426,6 @@
             }
         else
             {
-            
             if ( !iBuffer )
                 {
                 TRAPD( decErr, iDecoder = CExtJpegDecoder::FileNewL(
@@ -430,12 +433,24 @@
                 
                 if ( decErr != KErrNone )
                     {
+                    TN_DEBUG2( "CThumbnailImageDecoder::CreateDecoderL() - HW CExtJpegDecoder failed %d", decErr);
+                    LeaveIfCorruptL(decErr);
+                    
                     TRAP( decErr, iDecoder = CExtJpegDecoder::FileNewL(
                             CExtJpegDecoder::ESwImplementation, iFs, fullName, options) );
                     
                     if ( decErr != KErrNone )
                         {
-                        iDecoder = CImageDecoder::FileNewL( iFile, ContentAccess::EPeek, options );
+                        TN_DEBUG2( "CThumbnailImageDecoder::CreateDecoderL() - SW CExtJpegDecoder failed %d", decErr);
+                        LeaveIfCorruptL(decErr);
+                        
+                        TRAP( decErr, iDecoder = CImageDecoder::FileNewL( iFile, ContentAccess::EPeek, options ));
+                        
+                        if( decErr != KErrNone)
+                            {
+                            TN_DEBUG2( "CThumbnailImageDecoder::CreateDecoderL() - CImageDecoder failed %d", decErr);
+                            User::Leave( decErr );
+                            }
                         
                         TN_DEBUG1( "CThumbnailImageDecoder::CreateDecoderL() - CImageDecoder created" );
                         }
@@ -456,21 +471,28 @@
                 
                 if ( decErr != KErrNone )
                     {
+                    TN_DEBUG2( "CThumbnailImageDecoder::CreateDecoderL() - HW CExtJpegDecoder failed %d", decErr);
+                    LeaveIfCorruptL(decErr);
+                    
                     TRAP( decErr, iDecoder = CExtJpegDecoder::DataNewL(
                             CExtJpegDecoder::ESwImplementation, iFs, *iBuffer, options ));
                     
                     if ( decErr != KErrNone )
-                        {                        
+                        {                       
+                        TN_DEBUG2( "CThumbnailImageDecoder::CreateDecoderL() - SW CExtJpegDecoder failed %d", decErr);
+                        LeaveIfCorruptL(decErr);
                         TRAPD( decErr, iDecoder = CImageDecoder::DataNewL( iFs, *iBuffer, iMimeType.Des8(), options) );
                         
                         if ( decErr != KErrNone )
                             {                        
+                            TN_DEBUG2( "CThumbnailImageDecoder::CreateDecoderL() - CImageDecoder failed %d", decErr);
+                            LeaveIfCorruptL(decErr);
                             // don't force any mime type
                             TRAPD( decErr, iDecoder = CImageDecoder::DataNewL( iFs, *iBuffer, options ) );
+
                             if ( decErr != KErrNone )
                                 {                                
-                                TN_DEBUG1( "CThumbnailImageDecoder::CreateDecoderL() - error 3" );
-                                
+                                TN_DEBUG2( "CThumbnailImageDecoder::CreateDecoderL() - CImageDecoder no mime failed %d", decErr);
                                 User::Leave( decErr );
                                 }
                             }
@@ -540,12 +562,12 @@
     CImageDecoder::TOptions options;
     if ( aFlags == CThumbnailManager::EOptimizeForQuality )
         {
-        options = ( CImageDecoder::TOptions )( CImageDecoder::EOptionNoDither );
+        options = ( CImageDecoder::TOptions )( CImageDecoder::EOptionNoDither | CImageDecoder::EOptionAlwaysThread );
         }
     else
         {
         options = ( CImageDecoder::TOptions )( CImageDecoder::EOptionNoDither |
-            CImageDecoder::EPreferFastDecode );
+            CImageDecoder::EPreferFastDecode | CImageDecoder::EOptionAlwaysThread );
         }
 
     TRAPD( err, iDecoder = CExtJpegDecoder::DataNewL( iFs, * iExifThumbImage,
@@ -588,4 +610,18 @@
     return iOriginalSize;
     }
 
+// -----------------------------------------------------------------------------
+// CThumbnailImageDecoder::LeaveIfCorruptL()
+// Leave is image is corrupted
+// -----------------------------------------------------------------------------
+//
+void CThumbnailImageDecoder::LeaveIfCorruptL(const TInt aError )
+    {
+    //no sense to try other codecs if image is corrupted
+    if( aError == KErrCorrupt || aError == KErrUnderflow)
+        {
+        User::Leave( aError );
+        }
+    }
+
 //End of file
--- a/imagehandlingutilities/thumbnailmanager/plugins/image/src/thumbnailimagedecoderv2.cpp	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/plugins/image/src/thumbnailimagedecoderv2.cpp	Fri Mar 19 09:35:30 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"
@@ -155,28 +155,34 @@
     iDecoder = NULL;
     
     CImageDecoder::TOptions options = ( CImageDecoder::TOptions )( 
-            CImageDecoder::EOptionNoDither | CImageDecoder::EPreferFastDecode );
+            CImageDecoder::EOptionNoDither | CImageDecoder::EPreferFastDecode | CImageDecoder::EOptionAlwaysThread );
 
     TRAPD( decErr, iDecoder = CExtJpegDecoder::DataNewL( 
             CExtJpegDecoder::EHwImplementation, iFs, *iBuffer, options ));
                     
     if ( decErr != KErrNone )
         {
+        TN_DEBUG2( "CThumbnailImageDecoderv2::CreateDecoderL() - HW CExtJpegDecoder failed = %d", decErr );
         TRAP( decErr, iDecoder = CExtJpegDecoder::DataNewL(
                 CExtJpegDecoder::ESwImplementation, iFs, *iBuffer, options ));
         
         if ( decErr != KErrNone )
             {
+            TN_DEBUG2( "CThumbnailImageDecoderv2::CreateDecoderL() - SW CExtJpegDecoder failed %d", decErr);
+            LeaveIfCorruptL( decErr );
+            
             TRAP( decErr, iDecoder = CImageDecoder::DataNewL( iFs, *iBuffer, KJpegMime(), options ) );
             
             if ( decErr != KErrNone )
-                {                        
+                {                  
+                TN_DEBUG2( "CThumbnailImageDecoderv2::CreateDecoderL() - CImageDecoder failed %d", decErr);
+                LeaveIfCorruptL( decErr );
+            
                 // don't force any mime type
                 TRAPD( decErr, iDecoder = CImageDecoder::DataNewL( iFs, *iBuffer, options ) );
                 if ( decErr != KErrNone )
                     {                    
-                    TN_DEBUG1( "CThumbnailImageDecoderv2::CreateDecoderL() - error" );
-                    
+                    TN_DEBUG2( "CThumbnailImageDecoderv2::CImageDecoder() - CImageDecoder no mime error %d", decErr  );
                     User::Leave( decErr );
                     }
                 }
@@ -196,4 +202,18 @@
     TN_DEBUG1( "CThumbnailImageDecoderv2::CreateDecoderL() end" );
     }
 
+// -----------------------------------------------------------------------------
+// CThumbnailImageDecoderv2::LeaveIfCorruptL()
+// Leave if image is corrupted
+// -----------------------------------------------------------------------------
+//
+void CThumbnailImageDecoderv2::LeaveIfCorruptL(const TInt aError )
+    {
+    //no sense to try other codecs if image is corrupted
+    if( aError == KErrCorrupt || aError == KErrUnderflow)
+        {
+        User::Leave( aError );
+        }
+    }
+
 //End of file
--- a/imagehandlingutilities/thumbnailmanager/plugins/video/inc/thumbnailvideoprovider.h	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/plugins/video/inc/thumbnailvideoprovider.h	Fri Mar 19 09:35:30 2010 +0200
@@ -20,7 +20,7 @@
 #define THUMBNAILVIDEOPROVIDER_H
 
 #include <ecom.h>
-#include <tnevideoclipinfo.h>
+#include <TNEVideoClipInfo.h>
 
 #include "thumbnailprovider.h"
 
--- a/imagehandlingutilities/thumbnailmanager/plugins/video/src/thumbnailvideoprovider.cpp	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/plugins/video/src/thumbnailvideoprovider.cpp	Fri Mar 19 09:35:30 2010 +0200
@@ -169,6 +169,7 @@
 void CThumbnailVideoProvider::GetThumbnailL( RFs& /*aFs*/, TDesC8& /*aBuffer*/)
     {
     TN_DEBUG1( "CThumbnailVideoProvider::GetThumbnailL() - nothing to do" );
+    User::Leave( KErrNotSupported );
     }
 
 // ---------------------------------------------------------------------------
Binary file imagehandlingutilities/thumbnailmanager/sis/thumbnailmanager/ThumbnailManager_0x102830AB_v9.20.2_SA_S60.50_Euro1.sis has changed
--- a/imagehandlingutilities/thumbnailmanager/sis/thumbnailmanager/package.pkg	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/sis/thumbnailmanager/package.pkg	Fri Mar 19 09:35:30 2010 +0200
@@ -17,7 +17,7 @@
 &EN
 
 ; Header
-#{"Thumbnail Manager"},(0x102830AB), 9, 20, 2, TYPE=SA, RU
+#{"Thumbnail Manager"},(0x102830AB), 10, 10, 3, TYPE=SA, RU
 
 ; Localised Vendor name
 %{"Nokia"}
--- a/imagehandlingutilities/thumbnailmanager/sis/thumbnailmanager/stub.pkg	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/sis/thumbnailmanager/stub.pkg	Fri Mar 19 09:35:30 2010 +0200
@@ -17,7 +17,7 @@
 &EN
 
 ; Header
-#{"ThumbnailManager"},(0x102830AB), 9, 20, 1, TYPE=SA
+#{"ThumbnailManager"},(0x102830AB), 10, 10, 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	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/sis/thumbnailmanagercenrep/package.pkg	Fri Mar 19 09:35:30 2010 +0200
@@ -17,7 +17,7 @@
 &EN
 
 ; Header
-#{"Thumbnail Manager Cenrep"},(0x10202BE9), 9, 20, 2, TYPE=SP
+#{"Thumbnail Manager Cenrep"},(0x10202BE9), 10, 10, 3, TYPE=SP
 
 ; Localised Vendor name
 %{"Symbian Software Ltd."}
--- a/imagehandlingutilities/thumbnailmanager/thumbagdaemon/group/thumbagdaemon.mmp	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbagdaemon/group/thumbagdaemon.mmp	Fri Mar 19 09:35:30 2010 +0200
@@ -36,18 +36,25 @@
 
 EPOCPROCESSPRIORITY 	background
 
+//MACRO MDS_URI_OBSERVER
+MACRO TWO_PHASED_TN_GENERATION
+
 SOURCEPATH              ../src
 SOURCE                  thumbagdaemon.cpp
-SOURCE					thumbagprocessor.cpp
-SOURCE					../../thumbnailserver/src/tmshutdownobserver.cpp 
-SOURCE					thumbagformatobserver.cpp
+SOURCE			thumbagprocessor.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
 
 USERINCLUDE             ../inc
 USERINCLUDE             ../../inc
-USERINCLUDE             ../../thumbnailserver/inc
+USERINCLUDE             ../../tmcommon/inc
 
 LIBRARY                 euser.lib
 LIBRARY         	mdeclient.lib
@@ -55,7 +62,8 @@
 LIBRARY                 centralrepository.lib
 LIBRARY 		harvesterclient.lib
 LIBRARY			bafl.lib 
-LIBRARY			mpxcollectionhelper.lib mpxcollectionutility.lib mpxcommon.lib
+LIBRARY			mpxcollectionhelper.lib mpxcollectionutility.lib mpxcommon.lib 
+LIBRARY 		hwrmlightclient.lib
 
 DEBUGLIBRARY            flogger.lib
 
--- a/imagehandlingutilities/thumbnailmanager/thumbagdaemon/inc/thumbagdaemon.h	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbagdaemon/inc/thumbagdaemon.h	Fri Mar 19 09:35:30 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);
     
@@ -135,6 +145,20 @@
      * @since S60 v5.0
      */
     void ConstructL();
+    
+	 /**
+     * Initilization helper
+     *
+     * @since S60 v5.2
+     */
+    void InitializeL();
+    
+    /**
+     * Callback for reconnect timer
+     *
+     * @since S60 v5.0
+     */
+    static TInt ReconnectCallBack(TAny* aAny);
 
 private:
 	
@@ -146,6 +170,9 @@
     
     TBool iShutdown;
  
+    // reconnect timer
+    CPeriodic* iReconnect;
+    
 #ifdef _DEBUG
     TUint32 iAddCounter;
     TUint32 iModCounter;
--- a/imagehandlingutilities/thumbnailmanager/thumbagdaemon/inc/thumbagformatobserver.h	Tue Feb 02 00:23:15 2010 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,94 +0,0 @@
-/*
-* Copyright (c) 2006 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:  Monitors File system for Format events
-*
-*/
-
-
-#ifndef CTHUMBAGFORMATOBSERVER_H
-#define CTHUMBAGFORMATOBSERVER_H
-
-#include <babackup.h>
-#include "f32file.h"
-#include "thumbagprocessor.h" 
-
-/**
- *  File System monitor class to monitor for format events
- *
- *  @lib thumbnailsserver.exe
- *  @since S60 3.0
- */
-NONSHARABLE_CLASS( CThumbAGFormatObserver ) : public CBase,
-                                             public MBackupOperationObserver
-    {
-
-public:
-
-    /**
-    * Two-phase constructor
-    * @param aObserver observer to the monitor
-    */
-    static CThumbAGFormatObserver* NewL( CThumbAGProcessor* aProcessor );
-
-    /**
-    * Two-phase constructor
-    * @param aObserver observer to the monitor
-    */
-    static CThumbAGFormatObserver* NewLC( CThumbAGProcessor* aProcessor );
-
-    /**
-    * Destructor
-    */
-    virtual ~CThumbAGFormatObserver();
-
-public: // New functions
-
-    /**
-    * Polls for the current monitor status
-    * If an event is happening, it will callback the observer of the event
-    */
-    void PollStatus();
-
-protected: // Base Class
-
-    /*
-    * From MBackupOperationObserver
-    * Notifies this class of the backup event.
-    * MMC App will signal a start / end.
-    */
-    void HandleBackupOperationEventL(const TBackupOperationAttributes& aBackupOperationAttributes);
-
-private:
-
-    /**
-    *  C++ constructor
-    *  aObserver observer to this event
-    */
-    CThumbAGFormatObserver ( CThumbAGProcessor* aProcessor );
-
-    /*
-    * Second phased constructor
-    */
-    void ConstructL();
-
-private: // data
-
-    CThumbAGProcessor* iProcessor;    
-    
-    CBaBackupSessionWrapper* iBackupSession;
-
-    
-    };
-
-#endif // CTHUMBAGFORMATOBSERVER_H
--- a/imagehandlingutilities/thumbnailmanager/thumbagdaemon/inc/thumbagprocessor.h	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbagdaemon/inc/thumbagprocessor.h	Fri Mar 19 09:35:30 2010 +0200
@@ -29,9 +29,11 @@
 #include <harvesterclient.h>
 #include <e32property.h>
 #include <mpxcollectionobserver.h>
+#include "tmactivitymanager.h"
+#include "tmformatobserver.h"
+#include "tmrpropertyobserver.h"
 
 //FORWARD DECLARATIONS
-class CThumbAGFormatObserver;
 class MMPXCollectionUtility;
 
 /**
@@ -43,7 +45,10 @@
                          public MThumbnailManagerObserver,
                          public MMdEQueryObserver,
                          public MHarvesterEventObserver,
-                         public MMPXCollectionObserver
+                         public MMPXCollectionObserver,
+                         public MTMActivityManagerObserver,
+                         public MTMFormatObserver,
+                         public MTMRPropertyObserver
     {
 public:
 
@@ -80,7 +85,11 @@
              HarvesterEventState aHarvesterEventState,
              TInt aItemsLeft );
     
-private: // From MMPXCollectionObserver
+    //From MTMFormatObserver
+    void FormatNotification(TBool aFormat);
+    
+private: 
+    // From MMPXCollectionObserver
     /// See @ref MMPXCollectionObserver::HandleCollectionMessageL
     void HandleCollectionMessage( CMPXMessage* aMessage,  TInt aError );
 
@@ -92,7 +101,13 @@
     
     /// See @ref MMPXCollectionObserver::HandleCollectionMediaL
     void HandleCollectionMediaL( const CMPXMedia& aMedia, TInt aError );
-
+    
+private: //From MTMActivityManagerObserver
+    void ActivityChanged(const TBool aActive);
+    
+private: //From MTMRPropertyObserver
+    void RPropertyNotification(const TInt aError, const TUid aKeyCategory, const TUint aPropertyKey, const TInt aValue);
+    
 public:     
     
     /**
@@ -111,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
@@ -131,11 +146,9 @@
     
     void SetForceRun( const TBool aForceRun );
     
-    void SetFormat(TBool aStatus);
+protected:
     
-    void QueryForPlaceholdersL();
-
-protected:
+    void QueryAllItemsL();
     
     /**
      * QueryL
@@ -145,6 +158,8 @@
      */
     void QueryL( RArray<TItemId>& aIDArray );
     
+    void QueryPlaceholdersL();
+    
 protected:
 
     /**
@@ -219,7 +234,15 @@
      * @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:
     
     // not own
@@ -229,24 +252,24 @@
     // own
     CThumbnailManager* iTMSession;
     CMdEObjectQuery* iQuery;
-    CMdEObjectQuery* iQueryForPlaceholders;
+    CMdEObjectQuery* iQueryAllItems;
+    CMdEObjectQuery* iQueryPlaceholders;
     
     RArray<TItemId> iAddQueue;
     RArray<TItemId> iModifyQueue;
-    RArray<TItemId> iRemoveQueue;
-    RArray<TItemId> iPresentQueue;
+    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;
     
-    RArray<TItemId> iTempModifyQueue;
-    RArray<TItemId> iTempAddQueue;
-    
-    RArray<TItemId> iPlaceholderIDs;
+    TBool i2ndRound;    
     
     TBool iQueryActive;
     TBool iQueryReady;
     
-    TBool iQueryForPlaceholdersActive;
-    
     TBool iModify;
     TInt iProcessingCount;
 
@@ -254,8 +277,11 @@
     TBool iHarvesting;
     TBool iHarvestingTemp;
     
+	//Flag is MDS placeholder harvesting active
+    TBool iPHHarvesting;
+    TBool iPHHarvestingTemp;
+    
     CPeriodic* iPeriodicTimer;
-    TBool iTimerActive;
 
 	//MDS Harvester client
     RHarvesterClient iHarvesterClient;
@@ -263,24 +289,22 @@
     //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;
-    
-    CThumbAGFormatObserver* iFormatObserver;
+   
+    CTMFormatObserver* iFormatObserver;
    
     TBool iFormatting;
     TBool iSessionDied;
@@ -291,6 +315,19 @@
     
 	//Flag is MPX harvesting or MTP synchronisation in progress
     TBool iMPXHarvesting;
+    //inactivity polling timer
+    CPeriodic* iInactivityTimer;
+    //overall status of device
+    TBool iIdle;
+    
+    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/inc/thumblog.h	Tue Feb 02 00:23:15 2010 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,55 +0,0 @@
-/*
-* 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:  Log commands 
-*
-*/
-
-
-#ifndef THUMBLOG_H
-#define THUMBLOG_H
-
-#include <e32debug.h>
-#include <utf.h>
-
-#ifdef _DEBUG
-
-#define WLOG(a) RDebug::Print(_L(a))
-#define WLOG1(a,b) RDebug::Print(_L(a),(b))
-#define WLOG2(a,b,c) RDebug::Print(_L(a),(b),(c))
-#define WLOG3(a,b,c,d) RDebug::Print(_L(a),(b),(c),(d))
-
-#define HLOG(a)  RDebug::Print((a))
-#define HLOG1(a, b)  RDebug::Print((a), (b))
-#define HLOG2(a, b, c)  RDebug::Print((a), (b), (c))
-#define HLOG3(a, b, c, d)  RDebug::Print((a), (b), (c), (d))
-#define HLOG4(a, b, c, d, e)  RDebug::Print((a), (b), (c), (d), (e))
-#define HLOG5(a, b, c, d, e, f)  RDebug::Print((a), (b), (c), (d), (e), (f))
-
-#else 
-
-#define WLOG(a)
-#define WLOG1(a,b)
-#define WLOG2(a,b,c)
-#define WLOG3(a,b,c,d)
-
-#define HLOG(a)
-#define HLOG1(a, b)
-#define HLOG2(a, b, c) 
-#define HLOG3(a, b, c, d) 
-#define HLOG4(a, b, c, d, e) 
-#define HLOG5(a, b, c, d, e, f) 
-
-#endif
-
-#endif  // THUMBLOG_H
--- a/imagehandlingutilities/thumbnailmanager/thumbagdaemon/src/thumbagdaemon.cpp	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbagdaemon/src/thumbagdaemon.cpp	Fri Mar 19 09:35:30 2010 +0200
@@ -62,7 +62,8 @@
 // ---------------------------------------------------------------------------
 //
 CThumbAGDaemon::CThumbAGDaemon()
- 	: CServer2( CActive::EPriorityStandard, CServer2::EUnsharableSessions )
+ 	: CServer2( CActive::EPriorityStandard, CServer2::EUnsharableSessions ), iShutdownObserver(NULL), 
+ 	       iMDSShutdownObserver(NULL), iMdESession(NULL), iProcessor(NULL)
  	{
  	// No implementation required
  	}
@@ -82,34 +83,74 @@
     iModCounter = 0;
     iDelCounter = 0;
 #endif
-	
+    
+    InitializeL();
+    
+    iReconnect = CPeriodic::NewL(CActive::EPriorityIdle);
+    	
+	TN_DEBUG1( "CThumbAGDaemon::ConstructL() - end" );
+	}
+
+// ---------------------------------------------------------------------------
+// ~CThumbAGDaemon
+// ---------------------------------------------------------------------------
+//
+void CThumbAGDaemon::InitializeL()
+    {
+    TN_DEBUG1( "CThumbAGDaemon::InitializeL() - begin" );
+    
     if (DaemonEnabledL())
         {
-        TN_DEBUG1( "CThumbAGDaemon::ConstructL() - create observers" );
+        TN_DEBUG1( "CThumbAGDaemon::InitializeL() - create observers" );
         
-    	// create shutdown observer
+        // create shutdown observer
+        if(iMDSShutdownObserver)
+            {
+            delete iMDSShutdownObserver;
+            iMDSShutdownObserver = NULL;
+            }     
         iMDSShutdownObserver = CTMShutdownObserver::NewL( *this, KMdSPSShutdown, KMdSShutdown, EFalse );
-    	iShutdownObserver = CTMShutdownObserver::NewL( *this, KTAGDPSNotification, KShutdown, ETrue );  
-    	iShutdown = EFalse;
-    	
+
+        if(iShutdownObserver)
+            {
+            delete iShutdownObserver;
+            iShutdownObserver = NULL;
+            }
+        iShutdownObserver = CTMShutdownObserver::NewL( *this, KTAGDPSNotification, KShutdown, ETrue );  
+        iShutdown = EFalse;
+        
         // create processor
-        iProcessor = NULL;
-        iProcessor = CThumbAGProcessor::NewL();	
-    	
-        TN_DEBUG1( "CThumbAGDaemon::ConstructL() - connect to MDS" );
+        if(iProcessor)
+            {
+            delete iProcessor;
+            iProcessor = NULL; 
+            }
+        
+        iProcessor = CThumbAGProcessor::NewL(); 
+        
+        TN_DEBUG1( "CThumbAGDaemon::InitializeL() - connect to MDS" );
         
-    	// connect to MDS
-    	iMdESession = NULL;
-    	iMdESession = CMdESession::NewL( *this );
+        if(iMdESession)
+            {
+            TRAP_IGNORE( iMdESession->RemoveObjectObserverL( *this ) );
+            TRAP_IGNORE( iMdESession->RemoveObjectObserverL( *this ) );
+            TRAP_IGNORE( iMdESession->RemoveObjectObserverL( *this ) );
+            TRAP_IGNORE( iMdESession->RemoveObjectPresentObserverL( * this  ));
+        
+            // connect to MDS
+            delete iMdESession;
+            iMdESession = NULL;
+            }
+
+        iMdESession = CMdESession::NewL( *this );
         }
     else
         {
         // no error here, but need to shutdown daemon neatly
         User::Leave(KErrNone);
         }
-	
-	TN_DEBUG1( "CThumbAGDaemon::ConstructL() - end" );
-	}
+        TN_DEBUG1( "CThumbAGDaemon::InitializeL() - end" );
+    }
 
 // ---------------------------------------------------------------------------
 // ~CThumbAGDaemon
@@ -124,6 +165,13 @@
     delete iMDSShutdownObserver;
     delete iShutdownObserver;
     
+    if(iReconnect)
+        {
+        iReconnect->Cancel();
+        delete iReconnect;
+        iReconnect = NULL;
+        }
+    
     if (iProcessor)
         {
         delete iProcessor;
@@ -132,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;
@@ -203,7 +257,6 @@
     if (aError == KErrNone)
         {
         iProcessor->SetMdESession(iMdESession);
-        TRAP_IGNORE(iProcessor->QueryForPlaceholdersL());
         
         TRAPD( err, AddObserversL() );
         if (err != KErrNone)
@@ -223,12 +276,55 @@
 //
 void CThumbAGDaemon::HandleSessionError( CMdESession& /*aSession*/, TInt aError )
     {
+    TN_DEBUG2( "CThumbAGDaemon::HandleSessionError == %d", aError );
     if (aError != KErrNone)
         {
-        TN_DEBUG2( "CThumbAGDaemon::HandleSessionError == %d", aError );
+        // 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
 // -----------------------------------------------------------------------------
@@ -249,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
     
@@ -271,11 +367,13 @@
         // If delete event, remove IDs from Modify and Add queues
         if ( aType == ENotifyRemove )
             {
-            iProcessor->RemoveFromQueues( aObjectIdArray );
+            iProcessor->RemoveFromQueues( aObjectIdArray, EFalse);
             }
         
         // 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" );
@@ -287,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" );
@@ -314,48 +416,50 @@
     //tread present objects as added
     if(aPresent)
         {
-        TRAP_IGNORE( iProcessor->QueryForPlaceholdersL());
         if ( aObjectIdArray.Count() > 0) 
-           {
-		   // do not force run of these items
-           TRAP(err, iProcessor->AddToQueueL(ENotifyModify, aObjectIdArray, ETrue));
+            {
+		    // do not force run of these items
+            RPointerArray<HBufC> dummyArray;
+            TRAP(err, iProcessor->AddToQueueL(ENotifyAdd, aObjectIdArray, dummyArray, ETrue));
            
-           TN_DEBUG2( "CThumbAGDaemon::HandleObjectPresentNotification() - ENotifyAdd %d", aObjectIdArray.Count() );
-           
+            TN_DEBUG2( "CThumbAGDaemon::HandleObjectPresentNotification() - ENotifyAdd %d", aObjectIdArray.Count() );     
            
-#ifdef _DEBUG
-           iAddCounter = iAddCounter + aObjectIdArray.Count();
+           #ifdef _DEBUG
+           iAddCounter = aObjectIdArray.Count();
            if (err != KErrNone)
                {
                TN_DEBUG1( "CThumbAGDaemon::HandleObjectPresentNotification() - error adding to queue" );
                }
-#endif
+           #endif
            }
         }
     else
         {
         TN_DEBUG1( "CThumbAGDaemon::HandleObjectPresentNotification() - handle not present" );
-        TRAP_IGNORE( iProcessor->QueryForPlaceholdersL() );
-#ifdef _DEBUG    
-        if( iModCounter < aObjectIdArray.Count() )
+
+        #ifdef _DEBUG    
+        if( iAddCounter < aObjectIdArray.Count() )
             {
-            iModCounter = 0;
+            iAddCounter = 0;
             }
         else
             {
-            iModCounter = iModCounter - aObjectIdArray.Count();
+            iDelCounter = aObjectIdArray.Count();
             }
-#endif
+        #endif
            
         if ( aObjectIdArray.Count() > 0) 
-           {
-           iProcessor->RemoveFromQueues( aObjectIdArray, ETrue );
-           }
+            {
+            iProcessor->RemoveFromQueues( aObjectIdArray, ETrue );
+            }
         }
     
     #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" );
@@ -404,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 );
@@ -436,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/thumbagformatobserver.cpp	Tue Feb 02 00:23:15 2010 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,129 +0,0 @@
-/*
-* Copyright (c) 2006 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:  File System format monitor
-*
-*/
-
-#include "thumbagformatobserver.h"
-#include "thumbnaillog.h"
- 
-#include <e32base.h>
-#include <f32file.h>
-
-
-// ======== MEMBER FUNCTIONS ========
-
-CThumbAGFormatObserver::CThumbAGFormatObserver ( CThumbAGProcessor* aProcessor): 
-     iProcessor( aProcessor )
-    {
-    TN_DEBUG1( "CThumbAGFormatObserver::CThumbAGFormatObserver()");
-    
-    }
-    
-    
-// ---------------------------------------------------------------------------
-// Second Phase Constructor
-// ---------------------------------------------------------------------------
-//
-void CThumbAGFormatObserver::ConstructL()
-    {
-    TN_DEBUG1("CThumbAGFormatObserver::ConstructL in");
-
-    iBackupSession = CBaBackupSessionWrapper::NewL();
-    iBackupSession->RegisterBackupOperationObserverL( *this );
-
-
-    TN_DEBUG1("CThumbAGFormatObserver::ConstructL out");
-    }
-
-
-// ---------------------------------------------------------------------------
-// Two-Phased Constructor
-// ---------------------------------------------------------------------------
-//
-CThumbAGFormatObserver* CThumbAGFormatObserver::NewL(CThumbAGProcessor* aProcessor )
-    {
-    CThumbAGFormatObserver* self = CThumbAGFormatObserver::NewLC( aProcessor );
-    CleanupStack::Pop( self );
-    return self;
-    }
-
-
-// ---------------------------------------------------------------------------
-// Two-Phased Constructor
-// ---------------------------------------------------------------------------
-//
-CThumbAGFormatObserver* CThumbAGFormatObserver::NewLC( CThumbAGProcessor* aProcessor )
-    {
-    CThumbAGFormatObserver* self = new( ELeave ) CThumbAGFormatObserver( aProcessor );
-    CleanupStack::PushL( self );
-    self->ConstructL();
-    return self;
-    }
-
-
-// ---------------------------------------------------------------------------
-// destructor
-// ---------------------------------------------------------------------------
-//
-CThumbAGFormatObserver::~CThumbAGFormatObserver()
-    {
-
-    if( iBackupSession )
-        {
-        iBackupSession->DeRegisterBackupOperationObserver( *this );
-        }
-    delete iBackupSession;
-    }
-
-// ---------------------------------------------------------------------------
-// Checks the current status
-// ---------------------------------------------------------------------------
-//
-void CThumbAGFormatObserver::PollStatus()
-    {
-    
-    TN_DEBUG1("CThumbAGFormatObserver::PollStatus()");
-    
-    TBool formatting = iBackupSession->IsBackupOperationRunning();
-    
-    if( formatting )
-        {     
-        iProcessor->SetFormat(ETrue);   
-        }
-    }
-
-// ---------------------------------------------------------------------------
-// CThumbnailFormatObserver::HandleBackupOperationEventL
-// Handles a format operation
-// ---------------------------------------------------------------------------
-//
-void CThumbAGFormatObserver::HandleBackupOperationEventL(
-                  const TBackupOperationAttributes& aBackupOperationAttributes)
-    {
-    TN_DEBUG1("CThumbAGFormatObserver::HandleBackupOperationEventL in");
-
-    if( aBackupOperationAttributes.iOperation == EStart )
-        {
-        iProcessor->SetFormat(ETrue);
-        }
-    else  // TOperationType::EEnd or TOperationType::EAbort
-        {
-        iProcessor->SetFormat(EFalse);
-        }
-
-    TN_DEBUG1("CThumbAGObserver::HandleBackupOperationEventL out");
-    }
-
-
--- a/imagehandlingutilities/thumbnailmanager/thumbagdaemon/src/thumbagprocessor.cpp	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbagdaemon/src/thumbagprocessor.cpp	Fri Mar 19 09:35:30 2010 +0200
@@ -21,14 +21,15 @@
 #include <mdeconstants.h>
 #include <centralrepository.h>
 
+#include <mpxcollectionutility.h>
+#include <mpxmessagegeneraldefs.h>
+#include <mpxcollectionmessage.h>
+#include <coreapplicationuisdomainpskeys.h> 
+
 #include "thumbagprocessor.h"
 #include "thumbnaillog.h"
 #include "thumbnailmanagerconstants.h"
 #include "thumbnailmanagerprivatecrkeys.h"
-#include "thumbagformatobserver.h"
-#include <mpxcollectionutility.h>
-#include <mpxmessagegeneraldefs.h>
-#include <mpxcollectionmessage.h>
 
 // ---------------------------------------------------------------------------
 // CThumbAGProcessor::NewL()
@@ -64,14 +65,9 @@
     {
     TN_DEBUG1( "CThumbAGProcessor::ConstructL() - begin" );
     
-#ifdef _DEBUG
-    iAddCounter = 0;
-    iModCounter = 0;
-    iDelCounter = 0;
-#endif
-    
     iTMSession = CThumbnailManager::NewL( *this );
-    
+    iQueryAllItems = NULL;
+    iQueryPlaceholders = NULL;
     iQuery = NULL;
     iQueryActive = EFalse;
     iModify = EFalse;
@@ -84,18 +80,31 @@
     
     iPeriodicTimer = CPeriodic::NewL(CActive::EPriorityIdle);
     
-    //do some initializing async in RunL()
-    iInit = ETrue;
-    iForceRun = EFalse;    
+    SetForceRun( EFalse );    
     iActive = EFalse;
     
-    iFormatObserver = CThumbAGFormatObserver::NewL( this );
+    iFormatObserver = CTMFormatObserver::NewL( *this );
        
     iFormatting = EFalse;     
     iSessionDied = EFalse;
     
     iCollectionUtility = NULL;
-        
+    
+    iActivityManager = CTMActivityManager::NewL( this, KBackgroundGenerationIdle);
+
+    UpdatePSValues(ETrue);
+
+    if(iForegroundGenerationObserver)
+      {
+      delete iForegroundGenerationObserver;
+      iForegroundGenerationObserver = NULL;
+      }
+    
+    RProperty::Define(KTAGDPSNotification, KMPXHarvesting, RProperty::EInt);
+    
+	//start foreground generation observer
+    iForegroundGenerationObserver = CTMRPropertyObserver::NewL( *this, KTAGDPSNotification, KForceBackgroundGeneration, ETrue );  
+    
     TN_DEBUG1( "CThumbAGProcessor::ConstructL() - end" );
     }
 
@@ -107,6 +116,25 @@
     {
     TN_DEBUG1( "CThumbAGProcessor::~CThumbAGProcessor() - begin" );
     
+    if(iForegroundGenerationObserver)
+      {
+      delete iForegroundGenerationObserver;
+      iForegroundGenerationObserver = NULL;
+      }
+    
+    if(iActivityManager)
+        {
+        delete iActivityManager;
+        iActivityManager = NULL;
+        }
+    
+    if (iInactivityTimer)
+        {
+        iInactivityTimer->Cancel();
+        delete iInactivityTimer;
+        iInactivityTimer = NULL;
+        }
+    
     if(iPeriodicTimer)
         {
         iPeriodicTimer->Cancel();
@@ -115,8 +143,9 @@
     
     if (!iInit)
         {
+    /*
         iHarvesterClient.RemoveHarvesterEventObserver(*this);
-        iHarvesterClient.Close();
+        iHarvesterClient.Close();*/
         }
     
     if ( iCollectionUtility )
@@ -127,6 +156,13 @@
 
     Cancel();
     
+    if(iQueryPlaceholders)
+        {
+        iQueryPlaceholders->Cancel();
+        delete iQueryPlaceholders;
+        iQueryPlaceholders = NULL;
+        }
+    
     if (iQuery)
         {
         iQuery->Cancel();
@@ -134,21 +170,20 @@
         iQuery = NULL;
         }
     
-    if (iQueryForPlaceholders)
+    if (iQueryAllItems)
        {
-       iQueryForPlaceholders->Cancel();
-       delete iQueryForPlaceholders;
-       iQueryForPlaceholders = NULL;
+       iQueryAllItems->Cancel();
+       delete iQueryAllItems;
+       iQueryAllItems = NULL;
        }
-    
+
     iAddQueue.Close();
     iModifyQueue.Close();
-    iRemoveQueue.Close();
+    iRemoveQueue.ResetAndDestroy();
     iQueryQueue.Close();
-    iPresentQueue.Close();
-    iTempModifyQueue.Close();
-    iTempAddQueue.Close();
-    iPlaceholderIDs.Close();
+    iPlaceholderQueue.Close();
+	  
+    i2ndRoundGenerateQueue.Close();
     
     if (iTMSession)
         {
@@ -176,65 +211,119 @@
 // CThumbAGProcessor::HandleQueryCompleted()
 // -----------------------------------------------------------------------------
 //
-void CThumbAGProcessor::HandleQueryCompleted( CMdEQuery& /*aQuery*/, const TInt aError )
+void CThumbAGProcessor::HandleQueryCompleted( CMdEQuery& aQuery, const TInt aError )
     {
-
-    if( iQueryForPlaceholdersActive && iQueryForPlaceholders)
+    TN_DEBUG3( "CThumbAGProcessor::HandleQueryCompleted, aError == %d Count== %d", aError, aQuery.Count());
+    
+    if(&aQuery == iQueryPlaceholders)
         {
-        TN_DEBUG3( "CThumbAGProcessor::HandleQueryCompletedv2, aError == %d Count== %d", aError, iQueryForPlaceholders->Count());
+        TN_DEBUG1( "CThumbAGProcessor::HandleQueryCompleted - iQueryPlaceholders completed");
         
+        iPlaceholderQueue.Reset();
         // if no errors in query
         if (aError == KErrNone )
             {
-            
-            for(TInt i = 0; i < iQueryForPlaceholders->Count(); i++)
+            for(TInt i = 0; i < iQueryPlaceholders->Count(); i++)
+               {    
+               const CMdEObject* object = &iQueryPlaceholders->Result(i);
+              
+               if(!object)
+                   {
+                   continue;
+                   }
+              
+               if(!object->Placeholder())
+                   {
+                   TN_DEBUG2( "CThumbAGProcessor::HandleQueryCompleted %d not placeholder", object->Id());
+                   continue;
+                   }
+              
+               /*if (iPlaceholderQueue.Find( object->Id() ) == KErrNotFound)
+                   {
+                   TN_DEBUG2( "CThumbAGProcessor::HandleQueryCompleted %d added to placeholder queue", object->Id());*/
+                   TRAP_IGNORE( iPlaceholderQueue.AppendL( object->Id() )); 
+                 //}
+               }
+           }
+           delete iQueryPlaceholders;
+           iQueryPlaceholders = NULL;
+        }
+    else if(&aQuery == iQueryAllItems)
+        {
+        TN_DEBUG1( "CThumbAGProcessor::HandleQueryCompleted - QueryAllItems completed");
+        // if no errors in query
+        if (aError == KErrNone )
+            {
+            for(TInt i = 0; i < iQueryAllItems->Count(); i++)
                 {    
-                const CMdEObject* object = &iQueryForPlaceholders->Result(i);
-                
+                const CMdEObject* object = &iQueryAllItems->Result(i);
+               
                 if(!object)
-                    continue;
-                
-                if(!object->Placeholder())
                     {
-                    TN_DEBUG2( "CThumbAGProcessor::HandleQueryCompletedv2 %d not placeholder",object->Id());
                     continue;
                     }
-                
-                if (iPlaceholderIDs.Find( object->Id() ) == KErrNotFound)
-                   {
-                   TRAP_IGNORE( iPlaceholderIDs.AppendL( object->Id() )); 
-                   }
+               
+                if (iAddQueue.Find( object->Id() ) == KErrNotFound && iModifyQueue.Find( object->Id()) == KErrNotFound  )
+                    {
+                    TRAP_IGNORE( iAddQueue.AppendL( object->Id() ));
+                    }
                 }
-                
+#ifdef _DEBUG
+TN_DEBUG2( "CThumbAGProcessor::HandleQueryCompleted IN-COUNTERS---------- Amount: %d, Add",iQueryAllItems->Count());
+#endif
             }
-        else
+            //free query
+            delete iQueryAllItems;
+            iQueryAllItems = NULL;
+        }
+    else if(&aQuery == iQuery )
+        {
+        TN_DEBUG1( "CThumbAGProcessor::HandleQueryCompleted - Query completed");
+        
+        if(iQueryActive)
             {
-            TN_DEBUG1( "CThumbAGProcessor::HandleQueryCompleted() FAILED!");   
+            iQueryReady = ETrue;
+            iQueryActive = EFalse;
             }
-        
-        iQueryForPlaceholdersActive = EFalse;
-        }
-    
-    else if(iQueryActive)
-        {
-        TN_DEBUG3( "CThumbAGProcessor::HandleQueryCompleted, aError == %d Count== %d", aError, iQuery->Count());
-        iQueryReady = ETrue;
-        iQueryActive = EFalse;
     
         // if no errors in query
         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;
-            TN_DEBUG1( "CThumbAGProcessor::HandleQueryCompleted() FAILED!");   
+            TN_DEBUG1( "CThumbAGProcessor::HandleQueryCompleted() Query FAILED!");   
             }
         }
     else
         {
         TN_DEBUG1( "CThumbAGProcessor::HandleQueryCompleted() - NO QUERY ACTIVE"); 
+        __ASSERT_DEBUG((EFalse), User::Panic(_L("CThumbAGProcessor::HandleQueryCompleted()"), -1));
         }
     
     ActivateAO();
@@ -247,6 +336,7 @@
 void CThumbAGProcessor::ThumbnailPreviewReady( MThumbnailData& /*aThumbnail*/, 
                                                TThumbnailRequestId /*aId*/)
     {
+    TN_DEBUG1( "CThumbAGProcessor::ThumbnailPreviewReady()");
     // No implementation required
     }
 
@@ -258,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 )
@@ -268,7 +364,7 @@
 		
         iSessionDied = ETrue;
         
-        if( !iTimerActive)
+        if( !iPeriodicTimer->IsActive())
             {
             StartTimeout();
 			}
@@ -281,6 +377,7 @@
         }
     
     ActivateAO();
+	
     TN_DEBUG1( "CThumbAGProcessor::ThumbnailReady() - end" );
     }
 
@@ -294,11 +391,19 @@
     
     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 );
         }
+    
+    __ASSERT_DEBUG((iDefNamespace), User::Panic(_L("CThumbAGProcessor::SetMdESession() !iDefNamespace "), KErrBadHandle));
+       
+    //do async init
+    iInit = ETrue;
+    
 	ActivateAO();
     }
 
@@ -307,149 +412,133 @@
 // ---------------------------------------------------------------------------
 //
 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" );
-    
-    if(aPresent)
-        {
-        TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() - Add to SetPresentQueue" );
-        for (int i=0; i<aIDArray.Count(); i++)
-             {
-             // only add to Present queue if not already in Add or Present queue        
-              if (iAddQueue.Find( aIDArray[i] ) == KErrNotFound)
-                  {
-                  if (iPresentQueue.Find( aIDArray[i] ) == KErrNotFound)
-                      {
-                      iPresentQueue.AppendL(aIDArray[i]);
-                      }
-                  }
-             }     
-        }
+
     // update queues
-    else if (aType == ENotifyAdd)
+    if (aType == ENotifyAdd)
         {
         TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() - ENotifyAdd" );
         
         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)
                 {
-                //if in Present Queue remove from there and and put to add queue
-                TInt index = iPresentQueue.Find( aIDArray[i] );
-                if( index != KErrNotFound)
-                    {
-                    iPresentQueue.Remove( index );
-                    }
-                iAddQueue.AppendL(aIDArray[i]); 
-                iTempAddQueue.AppendL(aIDArray[i]);
+                iAddQueue.AppendL(aIDArray[i]);
                 }
             }
         }
     else if (aType == ENotifyModify)
         {
         TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() - ENotifyModify" );
+        
+        if(iPHHarvesting)
+            {
+        
+            TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() - PH  harvesting active, treat like add" );
+            for (int i=0; i<aIDArray.Count(); i++)
+                {
+                TInt itemIndex = iPlaceholderQueue.Find( aIDArray[i] );
+                                
+                if (itemIndex >= 0)
+                    {
+                    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
+            {
+            TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() - PH  harvesting finished, check is real modify!" );
             
-        for (int i=0; i<aIDArray.Count(); i++)
-             {
-             TInt itemIndex = iPlaceholderIDs.Find( aIDArray[i] );
-             if(itemIndex >= 0 )
-                 {
-                 TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() - harvesting now ended for this placeholder - not Real ENotifyModify" );
-                 iPlaceholderIDs.Remove(itemIndex);
-                 TN_DEBUG2( "CThumbAGProcessor::AddToQueueL() - placeholders left %d", iPlaceholderIDs.Count() );
-                 if (iAddQueue.Find( aIDArray[i] ) == KErrNotFound)
-                     {
-                     iAddQueue.AppendL(aIDArray[i]);
-                     }
-                 if (iTempModifyQueue.Find( aIDArray[i] ) == KErrNotFound)
-                     {
-                     iTempModifyQueue.AppendL( aIDArray[i] );
-                     }
-                 }
-             else if ( iTempAddQueue.Find( aIDArray[i] ) == KErrNotFound)
-                 {
-                 TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() - Real ENotifyModify, force run" );
-                 iModifyQueue.InsertL( aIDArray[i], 0 );
-                  
-                 TInt itemIndex = iAddQueue.Find( aIDArray[i] );
-                 if(itemIndex >= 0)
+            TInt itemIndex(KErrNotFound);
+            
+            for (int i=0; i<aIDArray.Count(); i++)
+                {
+                itemIndex = iPlaceholderQueue.Find( aIDArray[i] );
+                
+                if (itemIndex >= 0)
+                    {
+                    TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() - placeholder modify, remove from placeholder queue");
+                    iPlaceholderQueue.Remove( itemIndex );
+                    }
+                else
+                    {
+                    TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() - real modify");
+                    itemIndex = iAddQueue.Find( aIDArray[i] );
+                                    
+                    if (itemIndex >= 0)
+                        {
+                        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 );
+	                        }
+					}
+                    
+                    TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() - append to modify queue");
+                    iModifyQueue.AppendL(aIDArray[i]);
+                    
+                    SetForceRun( ETrue );
+                    } 
+                }
+            }
+        }
+        else if (aType == ENotifyRemove)
+            {
+            TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() - ENotifyRemove, remove IDs from all queues");
+            
+            for (int i=0; i<aIDArray.Count(); i++)
+                {
+                // can be removed from Add queue
+                TInt itemIndex = iAddQueue.Find( aIDArray[i] );
+                if(itemIndex >= 0)
                     {
                     iAddQueue.Remove(itemIndex);
                     }
-                 itemIndex = iPresentQueue.Find( aIDArray[i] );
-                 if(itemIndex >= 0)
+    
+                // ..and Modify Queue
+                itemIndex = iModifyQueue.Find( aIDArray[i] );
+                if(itemIndex >= 0)
                     {
-                    iPresentQueue.Remove(itemIndex);
+                    iModifyQueue.Remove(itemIndex);
                     }
-                 SetForceRun( ETrue );
-                 }
-             else
-                 {
-                 if (iTempModifyQueue.Find( aIDArray[i] ) == KErrNotFound)
-                     {
-                     TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() - harvesting now ended for this file - not Real ENotifyModify" );
-                     iTempModifyQueue.AppendL( aIDArray[i] );
-                     }
-                else
-                     {
-                     TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() - harvesting ended allready for this file - Real ENotifyModify, force run" );
-                     iModifyQueue.InsertL( aIDArray[i], 0 );
-                     TInt itemIndex = iAddQueue.Find( aIDArray[i] );
-                     if(itemIndex >= 0)
-                        {
-                        iAddQueue.Remove(itemIndex);
-                        }
-                     itemIndex = iPresentQueue.Find( aIDArray[i] );
-                     if(itemIndex >= 0)
-                        {
-                        iPresentQueue.Remove(itemIndex);
-                        }
-                     SetForceRun( ETrue );
-                     }
-                 } 
-             }        
-        }
-    else if (aType == ENotifyRemove)
-        {
-        TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() - ENotifyRemove" );
-        
-        for (int i=0; i<aIDArray.Count(); 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
             {
-            // only add to Remove queue if not already in Remove queue        
-            if (iRemoveQueue.Find( aIDArray[i] ) == KErrNotFound)
-                {
-                iRemoveQueue.AppendL(aIDArray[i]);
-                }
-
-            // can be removed from Add queue
-            TInt itemIndex = iAddQueue.Find( aIDArray[i] );
-            if(itemIndex >= 0)
-                {
-                iAddQueue.Remove(itemIndex);
-                }
-            // ..and Present Queue
-            itemIndex = iPresentQueue.Find( aIDArray[i] );
-            if(itemIndex >= 0)
-                {
-                iPresentQueue.Remove(itemIndex);
-                }
-            // ..and Modify Queue
-            itemIndex = iModifyQueue.Find( aIDArray[i] );
-            if(itemIndex >= 0)
-                {
-                iModifyQueue.Remove(itemIndex);
-                }
-            }  
-        }
-    else
-        {
-        // should not come here
-        TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() -  should not come here" );
-        return;
-        }
-
+	        TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() -  should not come here" );
+	        User::Leave( KErrArgument );
+            }
+#endif
+    
     ActivateAO(); 
     
     TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() - end" );
@@ -463,109 +552,94 @@
     {
     TN_DEBUG1( "CThumbAGProcessor::CreateThumbnailsL() - begin" );
     
-    if( iModify )
+    __ASSERT_DEBUG((iTMSession), User::Panic(_L("CThumbAGProcessor::CreateThumbnailsL() !iTMSession "), KErrBadHandle));
+    __ASSERT_DEBUG((iDefNamespace), User::Panic(_L("CThumbAGProcessor::CreateThumbnailsL() !iDefNamespace "), KErrBadHandle));
+    
+    if(!iTMSession || !iDefNamespace)
         {
-        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 );
+        return;
+        }
+    
+    TInt orientationVal = 0;
+    TInt64 modifiedVal = 0;
+    
+    CMdEProperty* orientation = NULL;
+    CMdEObjectDef& imageObjectDef = iDefNamespace->GetObjectDefL( MdeConstants::Image::KImageObject );       
+    TInt orientErr = aObject->Property( imageObjectDef.GetPropertyDefL( MdeConstants::Image::KOrientationProperty ), orientation, 0 );
+    
+    if (orientErr == KErrNone)
+        {
+        orientationVal = orientation->Uint16ValueL();
+        }
         
-        if (orientErr == KErrNone)
-            {
-            orientationVal = orientation->Uint16ValueL();
-            }
-        
-        CMdEProperty* modified = NULL;
-        CMdEObjectDef& objDef2 = iDefNamespace->GetObjectDefL( MdeConstants::Object::KBaseObject );       
-        TInt modifyErr = aObject->Property( objDef2.GetPropertyDefL( MdeConstants::Object::KLastModifiedDateProperty ), modified, 0 );
-        
-        if (modifyErr >= 0)
+    CMdEProperty* modified = NULL;
+    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();
+        }
+    
+    // update thumbs
+    if (iTMSession)
+        {
+		// 2nd round and modify updates both sizes if needed
+        if( i2ndRound )
             {
-            modifiedVal = modified->TimeValueL().Int64();
+            //generate both if needed
+            TN_DEBUG1( "CThumbAGProcessor::CreateThumbnailsL() EOptimizeForQuality ");
+            iTMSession->SetQualityPreferenceL( CThumbnailManager::EOptimizeForQuality );
             }
-        
-        // modify existing thumbs
-        if (iTMSession)
+		// 1st roung generation
+        else
             {
-			// run as lower priority than getting but higher that creating thumbnails
-            TRAPD(err, iTMSession->UpdateThumbnailsL(aObject->Id(), aObject->Uri(), orientationVal, modifiedVal, CActive::EPriorityIdle ));
+            //1st round
+            TN_DEBUG1( "CThumbAGProcessor::CreateThumbnailsL() EOptimizeForQualityWithPreview");
+            iTMSession->SetQualityPreferenceL( CThumbnailManager::EOptimizeForQualityWithPreview );
+            
+            CMdEObjectDef& videoObjectDef = iDefNamespace->GetObjectDefL( MdeConstants::Video::KVideoObject );
             
-            if ( err != KErrNone )
+            // add item to 2nd round queue 
+            if(iLastQueue == &iAddQueue || iLastQueue == &iModifyQueue)
                 {
-                TN_DEBUG2( "CThumbAGProcessor::UpdateThumbnailsL, iTMSession error == %d", err );
-                
-                iSessionDied = ETrue;
-                iActive = EFalse;
+                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();
-                } 
-            else
-                {
-                iActive = ETrue;
+                return;
                 }
             }
+
+        // run as lower priority than getting but higher that creating thumbnails
+        TRAPD(err, iTMSession->UpdateThumbnailsL(KNoId, aObject->Uri(), orientationVal, modifiedVal, CActive::EPriorityIdle ));
+      
+        if ( err != KErrNone )
+            {
+            TN_DEBUG2( "CThumbAGProcessor::CreateThumbnailsL, iTMSession error == %d", err );
+            
+            iSessionDied = ETrue;
+            iActive = EFalse;
+            ActivateAO();
+            } 
         else
             {
-            ActivateAO();
+            iActiveCount++;
+            iActive = ETrue;
             }
-        
-#ifdef _DEBUG
-        iModCounter++;
-#endif     
         }
     else
         {
-        CThumbnailObjectSource* source = NULL;
-        CMdEProperty* mimeType = NULL;
-        CMdEObjectDef& objDef = iDefNamespace->GetObjectDefL( MdeConstants::Object::KBaseObject );       
-        TInt mime = aObject->Property( objDef.GetPropertyDefL( MdeConstants::Object::KItemTypeProperty ), mimeType, 0 );
-        
-        // create new thumbs
-        if (mime != KErrNotFound)
-            {
-            source = CThumbnailObjectSource::NewLC(aObject->Uri(), aObject->Id(), mimeType->TextValueL());
-            }
-        else
-            {
-            source = CThumbnailObjectSource::NewLC(aObject->Uri(), aObject->Id());
-            }
+        ActivateAO();
+        }
         
-        if (iTMSession)
-            {
-            // run as very low priority task
-            TInt id = iTMSession->CreateThumbnails(*source, CActive::EPriorityIdle );
-            if ( id < 0 )
-                {
-                TN_DEBUG2( "CThumbAGProcessor::CreateThumbnailsL, iTMSession error == %d", id );
-                           
-                iSessionDied = ETrue;
-                iActive = EFalse;
-                CleanupStack::PopAndDestroy( source );
-                ActivateAO();
-                } 
-           else
-                {
-                iActive = ETrue;
-                CleanupStack::PopAndDestroy( source );
-                }
-            
-            }
-        else
-            {
-            ActivateAO();
-            }
-        
-#ifdef _DEBUG
-        iAddCounter++;
-#endif
-        }
-    
-#ifdef _DEBUG
-    TN_DEBUG3( "CThumbAGProcessor::OUT-COUNTERS----------, Add = %d Modify = %d", 
-               iAddCounter, iModCounter );
-#endif
-   
     TN_DEBUG1( "CThumbAGProcessor::CreateThumbnailsL() - end" );
     }
 
@@ -577,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
@@ -593,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() );
@@ -636,11 +722,73 @@
     
     iQuery->FindL();
     
-    iQueryQueue.Reset();
-    
     TN_DEBUG1( "CThumbAGProcessor::QueryL() - end" );
     }
 
+
+// ---------------------------------------------------------------------------
+// CThumbAGProcessor::QueryForPlaceholders()
+// ---------------------------------------------------------------------------
+//
+
+void CThumbAGProcessor::QueryPlaceholdersL()
+    {
+    TN_DEBUG1( "CThumbAGProcessor::QueryPlaceholdersL" );
+    
+    __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 )
+        {
+        if( !iQueryPlaceholders->IsComplete() )
+            {
+            TN_DEBUG1( "CThumbAGProcessor::QueryPlaceholdersL active- skip" );
+            return;
+            }
+        
+        // delete old query
+        iQueryPlaceholders->Cancel();
+        delete iQueryPlaceholders;
+        iQueryPlaceholders = NULL;
+        }
+   
+    TN_DEBUG1( "CThumbAGProcessor::QueryPlaceholdersL - start" );
+
+    CMdEObjectDef& imageObjDef = iDefNamespace->GetObjectDefL( MdeConstants::Image::KImageObject );
+    CMdEObjectDef& videoObjDef = iDefNamespace->GetObjectDefL( MdeConstants::Video::KVideoObject );
+    CMdEObjectDef& audioObjDef = iDefNamespace->GetObjectDefL( MdeConstants::Audio::KAudioObject );
+    
+    CMdEObjectDef& objDef = iDefNamespace->GetObjectDefL( MdeConstants::Object::KBaseObject);
+    iQueryPlaceholders = iMdESession->NewObjectQueryL( *iDefNamespace, objDef, this );
+        
+    iQueryPlaceholders->SetResultMode( EQueryResultModeItem );
+    
+    CMdELogicCondition& rootCondition = iQueryPlaceholders->Conditions();
+    rootCondition.SetOperator( ELogicConditionOperatorOr );
+    
+    CMdEObjectCondition& imagePHObjectCondition = rootCondition.AddObjectConditionL(imageObjDef);
+    imagePHObjectCondition.SetPlaceholderOnly( ETrue );
+    imagePHObjectCondition.SetNotPresent( ETrue );
+    
+    CMdEObjectCondition& videoPHObjectCondition = rootCondition.AddObjectConditionL(videoObjDef);
+    videoPHObjectCondition.SetPlaceholderOnly( ETrue );
+    videoPHObjectCondition.SetNotPresent( ETrue );
+    
+    CMdEObjectCondition& audioPHObjectCondition = rootCondition.AddObjectConditionL(audioObjDef);
+    audioPHObjectCondition.SetPlaceholderOnly( ETrue );
+    audioPHObjectCondition.SetNotPresent( ETrue );
+    
+    iQueryPlaceholders->FindL();  
+   
+    TN_DEBUG1( "CThumbAGProcessor::QueryPlaceholdersL - end" );
+    }
+
+
 // ---------------------------------------------------------------------------
 // CThumbAGProcessor::RunL()
 // ---------------------------------------------------------------------------
@@ -651,26 +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 );
-            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" );
+        TRAP_IGNORE(QueryAllItemsL());
+		
+        TN_DEBUG1( "CThumbAGProcessor::RunL() - Initialisation 2 done" );
         return;
         }
     
@@ -684,9 +871,11 @@
         if (err != KErrNone)
             {
             iTMSession = NULL;
+            ActivateAO();
             TN_DEBUG2( "CThumbAGProcessor::RunL() - Session restart failed, error == %d", err );
             }        
-        else {
+        else 
+            {
             iSessionDied = EFalse;
             }
         }    
@@ -694,95 +883,123 @@
     // 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;   
         }
     
-    //Iforce run can proceed from this point
-    if( !iForceRun )
+    
+    //force run can proceed from this point
+#ifdef _DEBUG
+	if( iForegroundRun )
+		{
+      	TN_DEBUG1( "void CThumbAGProcessor::RunL() KForceBackgroundGeneration enabled");
+	  	}
+	
+    if( iForceRun )
         {
-        //check if harvesting or waiting timeout
-        if( iHarvesting || iTimerActive || iMPXHarvesting )
+        TN_DEBUG1( "CThumbAGProcessor::RunL() - *** FORCED RUN ***");
+        }
+#endif
+	
+  	if( /*iForceRun || */iForegroundRun )
+      	{
+        TN_DEBUG1( "void CThumbAGProcessor::RunL() skip idle detection!");
+      	CancelTimeout();
+     	 }
+  	else
+	    {
+        if(iActivityManager)
             {
-            TN_DEBUG1( "void CThumbAGProcessor::RunL() Harvester or timer active, abort");
+            iIdle = iActivityManager->IsInactive();
+            }
+	    
+        if( !iIdle || iHarvesting || iMPXHarvesting || iPeriodicTimer->IsActive() )
+            {
+            TN_DEBUG1( "void CThumbAGProcessor::RunL() device not idle");
             return;
             }
         else
             {
             //check is server idle
-	        TInt idle(-1);
-
-            TInt ret = RProperty::Get(KServerIdle, KIdle, idle);
-	        
-	        if(ret == KErrNone )
-	            {
-	            if(!idle)
-	                {
-					//start wait timer and retry on after callback
-	                TN_DEBUG1( "CThumbAGProcessor::RunL() server not idle, wait... " );
-	                if( !iTimerActive)
-	                    {
-	                    StartTimeout();
-	                    }
-	                return;
-	                }
-	            }
-	        else
-	            {
-	            TN_DEBUG2( "CThumbAGProcessor::RunL() get KServerIdle failed %d, continue...", ret );
-	            }
+            TInt serveIdle(KErrNotFound);
+            TInt ret = RProperty::Get(KServerIdle, KIdle, serveIdle);
+            
+            if(ret == KErrNone )
+                {
+                if(!serveIdle)
+                    {
+                    //start inactivity timer and retry on after callback
+                    TN_DEBUG1( "void CThumbAGProcessor::RunL() server not idle");
+                    StartTimeout();
+                    return;
+                    }
+                }
+            TN_DEBUG1( "void CThumbAGProcessor::RunL() device and server idle, process");
             }
-        }
-    else
-        {
-        TN_DEBUG1( "void CThumbAGProcessor::RunL() forced run");
-        }
-    
+	    }
     
     //Handle completed MDS Query
     if( iQueryReady && iProcessingCount)
         {
         TInt err(KErrNone);
-        if((iForceRun && iModify) || (!iForceRun && !iModify))
+        //if force or non forced
+        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;    
             }
@@ -798,13 +1015,12 @@
             //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
         else if( iModify || err )
@@ -813,16 +1029,35 @@
             }
         }
     //waiting for MDS query to complete
-    else if( iQueryActive || iQueryForPlaceholdersActive )
+    else if( iQueryActive )
         {
-        if(iForceRun && !iModify && iQueryActive)
+        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  
@@ -831,52 +1066,66 @@
             }    
         }
 
-    // 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() add thumbnails");
+        TN_DEBUG1( "void CThumbAGProcessor::RunL() update 1st round thumbnails");
+        
+        i2ndRound = EFalse;
         
         // query for object info
         iQueryActive = ETrue;
         
         QueryL( iAddQueue );     
         }
-    else if ( iPresentQueue.Count() > 0 )
+    else if ( iRemoveQueue.Count() > 0 )
         {
-        TN_DEBUG1( "void CThumbAGProcessor::RunL() add thumbnails for present thumbnails" );
-                
+        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;
-                
-        QueryL( iPresentQueue );  
+        i2ndRound = ETrue;
+        QueryL( i2ndRoundGenerateQueue );     
         }
-    
+        
     TN_DEBUG1( "CThumbAGProcessor::RunL() - end" );
     }
 
@@ -895,62 +1144,94 @@
          TInt /*aItemsLeft*/ )
     {
     TN_DEBUG3( "CThumbAGProcessor::HarvestingUpdated -- start() aHEObserverType = %d, aHarvesterEventState = %d", aHEObserverType, aHarvesterEventState );
-  
+
+    #ifdef _DEBUG
+    if( aHEObserverType == EHEObserverTypePlaceholder)
+        {
+        TN_DEBUG1( "CThumbAGProcessor::HarvestingUpdated -- type EHEObserverTypePlaceholder");
+        }
+    else if( aHEObserverType == EHEObserverTypeOverall)
+        {
+        TN_DEBUG1( "CThumbAGProcessor::HarvestingUpdated -- type EHEObserverTypeOverall");
+        }
+    #endif
+    
+    //placeholder harvesting
     if( aHEObserverType == EHEObserverTypePlaceholder)
         {
-        TRAP_IGNORE( QueryForPlaceholdersL() );
-        return;
-        }    
-    
-    if( aHEObserverType != EHEObserverTypeOverall)
-        {
-        return;
-        }
+        switch(aHarvesterEventState)
+            {
+            case EHEStateStarted:
+            case EHEStateHarvesting:
+            case EHEStateResumed:
+                {
+                iPHHarvestingTemp = ETrue;
+                break;
+                }
+            case EHEStatePaused:
+            case EHEStateFinished:
+            case EHEStateUninitialized:
+                {
+                iPHHarvestingTemp = EFalse;
+                break;
+                }
+            };
     
-    switch(aHarvesterEventState)
-        {
-        case EHEStateStarted:
-        case EHEStateHarvesting:
-        case EHEStatePaused:
-        case EHEStateResumed:
-           {
-           iHarvestingTemp = ETrue;
-           break;
-           }
-        case EHEStateFinished:
-        case EHEStateUninitialized:
-           {
-           iHarvestingTemp = EFalse;
-           break;
-           }
-        };
-    
-    if(iHarvestingTemp == iHarvesting)
-        {
-        TN_DEBUG2( "CThumbAGProcessor::HarvestingUpdated -- no change %d", iHarvesting);
-        }
-    else
-        {
-        iHarvesting = iHarvestingTemp;
-        
-        if( iHarvesting )
+        if(iPHHarvestingTemp != iPHHarvesting)
             {
-            TN_DEBUG1( "CThumbAGProcessor::HarvestingUpdated -- MDS harvesterin started");
-            CancelTimeout();
-            }
-        else
-            {
-             TN_DEBUG1( "CThumbAGProcessor::HarvestingUpdated -- MDS harvesting finished ");
-             // continue processing if needed
-            StartTimeout();
-                 
-             iTempModifyQueue.Reset();
-             iTempAddQueue.Reset();
-             iPlaceholderIDs.Reset();
+            iPHHarvesting = iPHHarvestingTemp;
+           
+            if( iPHHarvesting )
+                {
+                TN_DEBUG1( "CThumbAGProcessor::HarvestingUpdated -- MDS placeholder harvesterin started");
+                }
+            else
+                {
+                TN_DEBUG1( "CThumbAGProcessor::HarvestingUpdated -- MDS placeholder harvesting finished");
+                TRAP_IGNORE(QueryPlaceholdersL());
+                }
             }
         }
-
-    TN_DEBUG3( "CThumbAGProcessor::HarvestingUpdated -- end() iHarvesting == %d, iMPXHarvesting == %d", iHarvesting, iMPXHarvesting);
+    //overall harvesting
+    else if ( aHEObserverType == EHEObserverTypeOverall)
+        {
+        switch(aHarvesterEventState)
+            {
+            case EHEStateStarted:
+            case EHEStateHarvesting:
+            case EHEStatePaused:
+            case EHEStateResumed:
+                {
+                iHarvestingTemp = ETrue;
+                break;
+                }
+            case EHEStateFinished:
+            case EHEStateUninitialized:
+                {
+                iHarvestingTemp = EFalse;
+                break;
+                }
+            };
+        
+        if(iHarvestingTemp != iHarvesting)
+            {
+            iHarvesting = iHarvestingTemp;
+            
+            if( iHarvesting )
+                {
+                TN_DEBUG1( "CThumbAGProcessor::HarvestingUpdated -- MDS harvesterin started");
+                CancelTimeout();
+                }
+            else
+                {
+                TN_DEBUG1( "CThumbAGProcessor::HarvestingUpdated -- MDS harvesting finished ");
+                // continue processing if needed
+                StartTimeout();
+                }
+            }
+        }
+   
+    TN_DEBUG3( "CThumbAGProcessor::HarvestingUpdated -- end() iHarvesting == %d, iPHHarvesting == %d ", iHarvesting, iPHHarvesting);
     }
 
 // ---------------------------------------------------------------------------
@@ -959,17 +1240,13 @@
 //
 void CThumbAGProcessor::StartTimeout()
     {
+    TN_DEBUG1( "CThumbAGProcessor::StartTimeout()");
     CancelTimeout();
     
     if(!iHarvesting && !iMPXHarvesting && !iPeriodicTimer->IsActive())
         {
-        iPeriodicTimer->Start( KHarvestingCompleteTimeout, KHarvestingCompleteTimeout, 
+        iPeriodicTimer->Start( KHarvestingCompleteTimeout, KHarvestingCompleteTimeout,
                 TCallBack(PeriodicTimerCallBack, this));
-        iTimerActive = ETrue;
-        }
-    else
-        {
-        iTimerActive = EFalse;
         }
     }
 
@@ -979,26 +1256,36 @@
 //
 void CThumbAGProcessor::CancelTimeout()
     {
-    if(iTimerActive)
-       {
-       iPeriodicTimer->Cancel();
-       }
-    iTimerActive = EFalse;
+    if(iPeriodicTimer->IsActive())
+        {
+        iPeriodicTimer->Cancel();
+        }
     }
 
 // ---------------------------------------------------------------------------
 // CThumbAGProcessor::RunError()
 // ---------------------------------------------------------------------------
 //
+#ifdef _DEBUG
 TInt CThumbAGProcessor::RunError(TInt aError)
+#else
+TInt CThumbAGProcessor::RunError(TInt /*aError*/)
+#endif
     {
-    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;
     }
@@ -1009,24 +1296,29 @@
 //
 void CThumbAGProcessor::ActivateAO()
     {
+#ifdef _DEBUG
+    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)
         {
         TN_DEBUG1( "CThumbAGProcessor::ActivateAO() - FORMATTING - DAEMON ON PAUSE");
         return;
         }
         
-    if( !IsActive() && (!iHarvesting || iForceRun ))
+    if( !IsActive() )
         {
-#ifdef _DEBUG
-        if( iForceRun )
-            {
-            TN_DEBUG1( "CThumbAGProcessor::ActivateAO() - *** FORCED RUN ***");
-            }
-#endif
         SetActive();
         TRequestStatus* statusPtr = &iStatus;
         User::RequestComplete( statusPtr, KErrNone );
         }
+
+    UpdatePSValues();
     }
 
 // ---------------------------------------------------------------------------
@@ -1063,15 +1355,24 @@
     TBool audioFull( EFalse );
 
     // get cenrep values
-    rep->Get( KAutoCreateImageGrid, imageGrid );
-    rep->Get( KAutoCreateImageList, imageList );
-    rep->Get( KAutoCreateImageFullscreen, imageFull );
-    rep->Get( KAutoCreateVideoGrid, videoGrid );
-    rep->Get( KAutoCreateVideoList, videoList );
-    rep->Get( KAutoCreateVideoFullscreen, videoFull );
-    rep->Get( KAutoCreateAudioGrid, audioGrid );
-    rep->Get( KAutoCreateAudioList, audioList );
-    rep->Get( KAutoCreateAudioFullscreen, audioFull );
+    TInt ret = rep->Get( KAutoCreateImageGrid, imageGrid );
+    TN_DEBUG2( "CThumbAGProcessor::CheckAutoCreateValuesL() KAutoCreateImageGrid %d", ret);
+    ret = rep->Get( KAutoCreateImageList, imageList );
+    TN_DEBUG2( "CThumbAGProcessor::CheckAutoCreateValuesL() KAutoCreateImageList %d", ret);
+    ret = rep->Get( KAutoCreateImageFullscreen, imageFull );
+    TN_DEBUG2( "CThumbAGProcessor::CheckAutoCreateValuesL() KAutoCreateImageFullscreen %d", ret);
+    ret = rep->Get( KAutoCreateVideoGrid, videoGrid );
+    TN_DEBUG2( "CThumbAGProcessor::CheckAutoCreateValuesL() KAutoCreateVideoGrid %d", ret);
+    ret = rep->Get( KAutoCreateVideoList, videoList );
+    TN_DEBUG2( "CThumbAGProcessor::CheckAutoCreateValuesL() KAutoCreateVideoList %d", ret);
+    ret = rep->Get( KAutoCreateVideoFullscreen, videoFull );
+    TN_DEBUG2( "CThumbAGProcessor::CheckAutoCreateValuesL() KAutoCreateVideoFullscreen %d", ret);
+    ret = rep->Get( KAutoCreateAudioGrid, audioGrid );
+    TN_DEBUG2( "CThumbAGProcessor::CheckAutoCreateValuesL() KAutoCreateAudioGrid %d", ret);
+    ret = rep->Get( KAutoCreateAudioList, audioList );
+    TN_DEBUG2( "CThumbAGProcessor::CheckAutoCreateValuesL() KAutoCreateAudioList %d", ret);
+    ret = rep->Get( KAutoCreateAudioFullscreen, audioFull );
+    TN_DEBUG2( "CThumbAGProcessor::CheckAutoCreateValuesL() KAutoCreateAudioFullscreen %d", ret);
     
     iAutoImage = EFalse;
     iAutoVideo = EFalse;
@@ -1098,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 );
     
@@ -1107,6 +1412,14 @@
     for (int i=0; i< aIDArray.Count(); i++)
         {
         TN_DEBUG2( "CThumbAGProcessor::RemoveFromQueues() - %d", aIDArray[i]);
+
+        itemIndex = iPlaceholderQueue.Find( aIDArray[i] );
+                         
+        if(itemIndex >= 0)
+            {
+            iPlaceholderQueue.Remove(itemIndex);
+            TN_DEBUG1( "CThumbAGProcessor::RemoveFromQueues() - iPlaceholderQueue" );
+            }
                 
         itemIndex = iAddQueue.Find( aIDArray[i] );
         
@@ -1114,44 +1427,42 @@
             {
             iAddQueue.Remove(itemIndex);
             TN_DEBUG1( "CThumbAGProcessor::RemoveFromQueues() - iAddQueue" );
-            continue;
             }
-        
-        itemIndex = iPresentQueue.Find( aIDArray[i] );
+
+        itemIndex = i2ndRoundGenerateQueue.Find( aIDArray[i] );
                 
         if(itemIndex >= 0)
             {
-            iPresentQueue.Remove(itemIndex);
-            TN_DEBUG1( "CThumbAGProcessor::RemoveFromQueues() - iPresentQueue" );
-            continue;
+            i2ndRoundGenerateQueue.Remove(itemIndex);
+            TN_DEBUG1( "CThumbAGProcessor::RemoveFromQueues() - i2ndRoundGenerateQueue" );
             }
-   
+        
         itemIndex = iModifyQueue.Find( aIDArray[i] );
          
         if(itemIndex >= 0)
-           {
-           iModifyQueue.Remove(itemIndex);
-           TN_DEBUG1( "CThumbAGProcessor::RemoveFromQueues() - iModifyQueue" );
+            {
+            iModifyQueue.Remove(itemIndex);
+            TN_DEBUG1( "CThumbAGProcessor::RemoveFromQueues() - iModifyQueue" );
 			 
-           if( iModifyQueue.Count() == 0)
-			  {
-			  iForceRun = EFalse;
-		      }
+            if( iModifyQueue.Count() == 0)
+			    {
+			    SetForceRun( EFalse );
+		        }
 			 
-           continue;
-           }
+            continue;
+            }
     
-        if( aRemoveFromDelete )
-           {
-           itemIndex = iRemoveQueue.Find( aIDArray[i] );
+        /*if( aRemoveFromDelete )
+            {
+            itemIndex = iRemoveQueue.Find( aIDArray[i] );
              
-           if(itemIndex >= 0)
-              {
-              iRemoveQueue.Remove(itemIndex);
-              TN_DEBUG1( "CThumbAGProcessor::RemoveFromQueues() - iRemoveQueue" );
-              continue;
-              }
-           }
+            if(itemIndex >= 0)
+                {
+                iRemoveQueue.Remove(itemIndex);
+                TN_DEBUG1( "CThumbAGProcessor::RemoveFromQueues() - iRemoveQueue" );
+                continue;
+                }
+            }*/
         }
     
     TN_DEBUG1( "CThumbAGProcessor::RemoveFromQueues() - end" );
@@ -1173,75 +1484,57 @@
     }
 
 // ---------------------------------------------------------------------------
-// CThumbAGProcessor::SetFormat()
-// ---------------------------------------------------------------------------
-//
-
-void CThumbAGProcessor::SetFormat(TBool aStatus)
-    {
-    TN_DEBUG2( "CThumbAGProcessor::SetFormat(%d) - end", aStatus );
-    
-    iFormatting = aStatus;
-    if(!aStatus)
-        {
-        ActivateAO();
-        }
-    }
-
-// ---------------------------------------------------------------------------
 // CThumbAGProcessor::QueryForPlaceholders()
 // ---------------------------------------------------------------------------
 //
-
-void CThumbAGProcessor::QueryForPlaceholdersL()
+void CThumbAGProcessor::QueryAllItemsL()
     {
-    TN_DEBUG1( "CThumbAGProcessor::QueryForPlaceholders" );
-    if(iQueryForPlaceholdersActive)
+    TN_DEBUG1( "CThumbAGProcessor::QueryAllItemsL" );
+    
+    __ASSERT_DEBUG((iMdESession), User::Panic(_L("CThumbAGProcessor::QueryAllItemsL() !iMdeSession "), KErrBadHandle));
+    
+    if(!iMdESession)
+         {
+         return;
+         }
+    
+    if( iQueryAllItems )
         {
-        TN_DEBUG1( "CThumbAGProcessor::QueryForPlaceholders - skip" );
-        return;
+        if( !iQueryAllItems->IsComplete() )
+            {
+            TN_DEBUG1( "CThumbAGProcessor::QueryAllItemsL active- skip" );
+            return;
+            }
+        
+        // delete old query
+        iQueryAllItems->Cancel();
+        delete iQueryAllItems;
+        iQueryAllItems = NULL;
         }
     
-    TN_DEBUG1( "CThumbAGProcessor::QueryForPlaceholders - start" );
-
-    // delete old query
-    if (iQueryForPlaceholders)
-       {
-       iQueryForPlaceholdersActive = EFalse;
-       iQueryForPlaceholders->Cancel();
-       delete iQueryForPlaceholders;
-       iQueryForPlaceholders = NULL;
-       }
+    TN_DEBUG1( "CThumbAGProcessor::QueryAllItemsL - start" );
     
     CMdEObjectDef& imageObjDef = iDefNamespace->GetObjectDefL( MdeConstants::Image::KImageObject );
     CMdEObjectDef& videoObjDef = iDefNamespace->GetObjectDefL( MdeConstants::Video::KVideoObject );
     CMdEObjectDef& audioObjDef = iDefNamespace->GetObjectDefL( MdeConstants::Audio::KAudioObject );
     
     CMdEObjectDef& objDef = iDefNamespace->GetObjectDefL( MdeConstants::Object::KBaseObject);
-    iQueryForPlaceholders = iMdESession->NewObjectQueryL( *iDefNamespace, objDef, this );
+    iQueryAllItems = iMdESession->NewObjectQueryL( *iDefNamespace, objDef, this );
         
-    iQueryForPlaceholders->SetResultMode( EQueryResultModeItem );
+    iQueryAllItems->SetResultMode( EQueryResultModeItem );
     
-    CMdELogicCondition& rootCondition = iQueryForPlaceholders->Conditions();
+    CMdELogicCondition& rootCondition = iQueryAllItems->Conditions();
     rootCondition.SetOperator( ELogicConditionOperatorOr );
     
     CMdEObjectCondition& imagePHObjectCondition = rootCondition.AddObjectConditionL(imageObjDef);
-    imagePHObjectCondition.SetPlaceholderOnly( ETrue );
-    imagePHObjectCondition.SetNotPresent( ETrue );
     
     CMdEObjectCondition& videoPHObjectCondition = rootCondition.AddObjectConditionL(videoObjDef);
-    videoPHObjectCondition.SetPlaceholderOnly( ETrue );
-    videoPHObjectCondition.SetNotPresent( ETrue );
     
     CMdEObjectCondition& audioPHObjectCondition = rootCondition.AddObjectConditionL(audioObjDef);
-    audioPHObjectCondition.SetPlaceholderOnly( ETrue );
-    audioPHObjectCondition.SetNotPresent( ETrue );
     
-    iQueryForPlaceholders->FindL();  
+    iQueryAllItems->FindL();  
     
-    iQueryForPlaceholdersActive = ETrue;
-    
-    TN_DEBUG1( "CThumbAGProcessor::QueryForPlaceholders - end" );
+    TN_DEBUG1( "CThumbAGProcessor::QueryAllItemsL - end" );
     }
 
 // -----------------------------------------------------------------------------
@@ -1250,9 +1543,7 @@
 // Handle collection message.
 // -----------------------------------------------------------------------------
 //
-
-void CThumbAGProcessor::HandleCollectionMessage( CMPXMessage* aMessage,
-                                                        TInt aError )
+void CThumbAGProcessor::HandleCollectionMessage( CMPXMessage* aMessage, TInt aError )
     {
     if ( aError != KErrNone || !aMessage )
         {
@@ -1271,40 +1562,50 @@
             {
             TInt op( *aMessage->Value<TInt>( KMPXMessageGeneralType ) );
                
-           switch( op )
-               {
-			   //when MTP sync or music collection is started then pause processing
-               case EMcMsgRefreshStart:
-               case EMcMsgUSBMTPStart:
-                   TN_DEBUG1("CThumbAGProcessor::HandleCollectionMessage MPX refresh started" );
-                   iMPXHarvesting = ETrue;
-                   CancelTimeout();
-                   break;
-			   //when MTP sync or music collection refresh is complete then resume processing
-               case EMcMsgRefreshEnd:
-               case EMcMsgUSBMTPEnd:
-               case EMcMsgUSBMTPNotActive:
-                   TN_DEBUG1("CThumbAGProcessor::HandleCollectionMessage MPX refresh finished/not active" );
-                   iMPXHarvesting = EFalse;
-                   StartTimeout();
-                   break;
-               default:
-                   break;
-               }
-           TN_DEBUG3( "CThumbAGProcessor::HandleCollectionMessage -- end() iHarvesting == %d, iMPXHarvesting == %d", iHarvesting, iMPXHarvesting);
+            switch( op )
+                {
+			    //when MTP sync or music collection is started then pause processing
+                case EMcMsgRefreshStart:
+                case EMcMsgUSBMTPStart:
+                    TN_DEBUG1("CThumbAGProcessor::HandleCollectionMessage MPX refresh started" );
+                    iMPXHarvesting = ETrue;
+                    CancelTimeout();
+                    break;
+			    //when MTP sync or music collection refresh is complete then resume processing
+                case EMcMsgRefreshEnd:
+                case EMcMsgUSBMTPEnd:
+                case EMcMsgUSBMTPNotActive:
+                    TN_DEBUG1("CThumbAGProcessor::HandleCollectionMessage MPX refresh finished/not active" );
+                    iMPXHarvesting = EFalse;
+                    StartTimeout();
+                    break;
+                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);
             }
         }
     }
+
 // -----------------------------------------------------------------------------
 // CThumbAGProcessor::HandleOpenL
 // From MMPXCollectionObserver
 // Handles the collection entries being opened.
 // -----------------------------------------------------------------------------
 //
-void CThumbAGProcessor::HandleOpenL( const CMPXMedia& /*aEntries*/,
-                                            TInt /*aIndex*/,
-                                            TBool /*aComplete*/,
-                                            TInt /*aError*/ )
+void CThumbAGProcessor::HandleOpenL( const CMPXMedia& /*aEntries*/, TInt /*aIndex*/,
+                                               TBool /*aComplete*/, TInt /*aError*/ )
      {
      // not needed here
      }
@@ -1331,4 +1632,107 @@
     // not needed here
     }
 
+// -----------------------------------------------------------------------------
+// ActivityChanged()
+// -----------------------------------------------------------------------------
+//
+void CThumbAGProcessor::ActivityChanged(const TBool aActive)
+    {
+    TN_DEBUG2( "void CThumbAGProcessor::ActivityChanged() aActive == %d", aActive);
+    if(aActive)
+        {
+        iIdle = EFalse;
+        }
+    else
+        {
+        iIdle = ETrue; 
+        
+        if(iAddQueue.Count() + iModifyQueue.Count() + iRemoveQueue.Count() + i2ndRoundGenerateQueue.Count() > 0 )
+            {
+            ActivateAO();
+            }
+        }
+    }
+
+
+// ---------------------------------------------------------------------------
+// CThumbAGProcessor::FormatNotification
+// Handles a format operation
+// ---------------------------------------------------------------------------
+//
+void CThumbAGProcessor::FormatNotification( TBool aFormat )
+    {
+    TN_DEBUG2( "CThumbAGProcessor::FormatNotification(%d)", aFormat );
+    
+    iFormatting = aFormat;
+    if(!aFormat)
+        {
+        ActivateAO();
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// 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	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailclient/inc/thumbnailsession.h	Fri Mar 19 09:35:30 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	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailclient/src/thumbnailrequestactive.cpp	Fri Mar 19 09:35:30 2010 +0200
@@ -192,6 +192,7 @@
             }
         }
     
+    iTimer->Cancel();
     iTimer->Start( KClientRequestTimeout, KClientRequestTimeout, 
                    TCallBack(TimerCallBack, this));
     SetActive();
@@ -204,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 )
         {
@@ -233,18 +234,22 @@
     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 );
         
-        iSession.RequestThumbnailL( iFile, iParams.iTargetUri, iParamsPckg, iStatus );
+        iSession.RequestThumbnailL( iFile, iParams.iFileName, iParamsPckg, iStatus );
         CleanupStack::PopAndDestroy( &iFile );
         
         iTimer->Start( KClientRequestTimeout, KClientRequestTimeout, 
@@ -253,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 );
@@ -269,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();
@@ -313,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();    
@@ -382,10 +429,10 @@
 //
 void CThumbnailRequestActive::ReleaseServerBitmap()
     {
-    TN_DEBUG1( "CThumbnailRequestActive::ReleaseServerBitmap");
-    
     if ( iBitmapHandle && iSession.Handle())
         {
+    	TN_DEBUG1( "CThumbnailRequestActive::ReleaseServerBitmap");
+    
         iSession.ReleaseBitmap( iBitmapHandle );
         iBitmapHandle = 0;
         }
@@ -464,6 +511,7 @@
     iParams.iControlFlags = (aGeneratePersistentSizesOnly ?
     						EThumbnailGeneratePersistentSizesOnly :
     						EThumbnailNoControlFlags);    
+    iParams.iOriginalControlFlags = iParams.iControlFlags;
     iParams.iBitmapHandle = 0;
     iParams.iSize = aSize;
     iParams.iDisplayMode = aDisplayMode;
@@ -497,7 +545,8 @@
     iClientData = aClientData;
     iParams.iControlFlags = (aGeneratePersistentSizesOnly ?
                             EThumbnailGeneratePersistentSizesOnly :
-                            EThumbnailNoControlFlags);    
+                            EThumbnailNoControlFlags);
+    iParams.iOriginalControlFlags = iParams.iControlFlags;
     iParams.iBitmapHandle = 0;
     iParams.iSize = aSize;
     iParams.iDisplayMode = aDisplayMode;
@@ -530,7 +579,7 @@
     iParams.iControlFlags = (aGeneratePersistentSizesOnly ?
     						EThumbnailGeneratePersistentSizesOnly :
     						EThumbnailNoControlFlags);
-    						
+    iParams.iOriginalControlFlags = iParams.iControlFlags;
     iParams.iBitmapHandle = 0;
     iParams.iSize = aSize;
     iParams.iDisplayMode = aDisplayMode;
@@ -562,7 +611,7 @@
     iParams.iControlFlags = (aGeneratePersistentSizesOnly ?
                             EThumbnailGeneratePersistentSizesOnly :
                             EThumbnailNoControlFlags);
-                           
+    iParams.iOriginalControlFlags = iParams.iControlFlags;  
     iParams.iMimeType = TDataType( aMimeType );
     iParams.iBitmapHandle = 0;
     iParams.iSize = aSize;
@@ -593,7 +642,7 @@
     iParams.iControlFlags = (aGeneratePersistentSizesOnly ?
                             EThumbnailGeneratePersistentSizesOnly :
                             EThumbnailNoControlFlags);
-                           
+    iParams.iOriginalControlFlags = iParams.iControlFlags;  
     iParams.iBitmapHandle = 0;
     iParams.iSize = aSize;
     iParams.iThumbnailSize = aThumbnailSize;
@@ -644,6 +693,7 @@
     iRequestType = EReqUpdateThumbnails;
     
     iParams.iControlFlags = EThumbnailGeneratePersistentSizesOnly;   
+    iParams.iOriginalControlFlags = iParams.iControlFlags;
     iParams.iBitmapHandle = 0;
     iParams.iDisplayMode = aDisplayMode;
     iParams.iRequestId = iRequestId;
@@ -730,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	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailclient/src/thumbnailsession.cpp	Fri Mar 19 09:35:30 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 )
     {
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailmanagerqt/bwins/thumbnailmanagerqt.def	Fri Mar 19 09:35:30 2010 +0200
@@ -0,0 +1,18 @@
+EXPORTS
+	?getThumbnail@ThumbnailManager@@QAEHABVQString@@PAXH@Z @ 1 NONAME ; int ThumbnailManager::getThumbnail(class QString const &, void *, int)
+	?qualityPreference@ThumbnailManager@@QBE?AW4QualityPreference@1@XZ @ 2 NONAME ; enum ThumbnailManager::QualityPreference ThumbnailManager::qualityPreference(void) const
+	?cancelRequest@ThumbnailManager@@QAE_NH@Z @ 3 NONAME ; bool ThumbnailManager::cancelRequest(int)
+	?setMode@ThumbnailManager@@QAE_NW4ThumbnailMode@1@@Z @ 4 NONAME ; bool ThumbnailManager::setMode(enum ThumbnailManager::ThumbnailMode)
+	?setQualityPreference@ThumbnailManager@@QAE_NW4QualityPreference@1@@Z @ 5 NONAME ; bool ThumbnailManager::setQualityPreference(enum ThumbnailManager::QualityPreference)
+	?setThumbnail@ThumbnailManager@@QAEHABVQPixmap@@ABVQString@@PAXH@Z @ 6 NONAME ; int ThumbnailManager::setThumbnail(class QPixmap const &, class QString const &, void *, int)
+	?thumbnailSize@ThumbnailManager@@QBE?AVQSize@@XZ @ 7 NONAME ; class QSize ThumbnailManager::thumbnailSize(void) const
+	??1ThumbnailManager@@UAE@XZ @ 8 NONAME ; ThumbnailManager::~ThumbnailManager(void)
+	??0ThumbnailManager@@QAE@PAVQObject@@@Z @ 9 NONAME ; ThumbnailManager::ThumbnailManager(class QObject *)
+	?setThumbnailSize@ThumbnailManager@@QAE_NW4ThumbnailSize@1@@Z @ 10 NONAME ; bool ThumbnailManager::setThumbnailSize(enum ThumbnailManager::ThumbnailSize)
+	?deleteThumbnails@ThumbnailManager@@QAEXABVQString@@@Z @ 11 NONAME ; void ThumbnailManager::deleteThumbnails(class QString const &)
+	?setThumbnailSize@ThumbnailManager@@QAE_NABVQSize@@@Z @ 12 NONAME ; bool ThumbnailManager::setThumbnailSize(class QSize const &)
+	?deleteThumbnails@ThumbnailManager@@QAEXK@Z @ 13 NONAME ; void ThumbnailManager::deleteThumbnails(unsigned long)
+	?changePriority@ThumbnailManager@@QAE_NHH@Z @ 14 NONAME ; bool ThumbnailManager::changePriority(int, int)
+	?getThumbnail@ThumbnailManager@@QAEHKPAXH@Z @ 15 NONAME ; int ThumbnailManager::getThumbnail(unsigned long, void *, int)
+	?mode@ThumbnailManager@@QBE?AW4ThumbnailMode@1@XZ @ 16 NONAME ; enum ThumbnailManager::ThumbnailMode ThumbnailManager::mode(void) const
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailmanagerqt/eabi/thumbnailmanagerqt.def	Fri Mar 19 09:35:30 2010 +0200
@@ -0,0 +1,21 @@
+EXPORTS
+	_ZN16ThumbnailManager12getThumbnailERK7QStringPvi @ 1 NONAME
+	_ZN16ThumbnailManager12getThumbnailEmPvi @ 2 NONAME
+	_ZN16ThumbnailManager12setThumbnailERK7QPixmapRK7QStringPvi @ 3 NONAME
+	_ZN16ThumbnailManager13cancelRequestEi @ 4 NONAME
+	_ZN16ThumbnailManager14changePriorityEii @ 5 NONAME
+	_ZN16ThumbnailManager16deleteThumbnailsERK7QString @ 6 NONAME
+	_ZN16ThumbnailManager16deleteThumbnailsEm @ 7 NONAME
+	_ZN16ThumbnailManager16setThumbnailSizeENS_13ThumbnailSizeE @ 8 NONAME
+	_ZN16ThumbnailManager16setThumbnailSizeERK5QSize @ 9 NONAME
+	_ZN16ThumbnailManager20setQualityPreferenceENS_17QualityPreferenceE @ 10 NONAME
+	_ZN16ThumbnailManager7setModeENS_13ThumbnailModeE @ 11 NONAME
+	_ZN16ThumbnailManagerC1EP7QObject @ 12 NONAME
+	_ZN16ThumbnailManagerC2EP7QObject @ 13 NONAME
+	_ZN16ThumbnailManagerD0Ev @ 14 NONAME
+	_ZN16ThumbnailManagerD1Ev @ 15 NONAME
+	_ZN16ThumbnailManagerD2Ev @ 16 NONAME
+	_ZNK16ThumbnailManager13thumbnailSizeEv @ 17 NONAME
+	_ZNK16ThumbnailManager17qualityPreferenceEv @ 18 NONAME
+	_ZNK16ThumbnailManager4modeEv @ 19 NONAME
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailmanagerqt/inc/thumbnailmanager_p_qt.h	Fri Mar 19 09:35:30 2010 +0200
@@ -0,0 +1,197 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "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: 
+*
+*/
+
+#ifndef THUMBNAILMANAGER_P_QT_H
+#define THUMBNAILMANAGER_P_QT_H
+
+#include <qobject>
+#include <thumbnailmanager.h>
+#include <thumbnailmanager_qt.h>
+#include <thumbnailmanagerobserver.h>
+#include <qpixmap.h>
+
+class QString;
+class QPixmap;
+class QSize;
+class CThumbnailManager;
+class MThumbnailData;
+class CFbsBitmap;
+class QByteArray;
+
+
+class ThumbnailManagerPrivate : 
+public QObject,
+public MThumbnailManagerObserver
+    {
+    Q_OBJECT
+public:
+
+    /**
+     * Constructor
+     */    
+        
+    ThumbnailManagerPrivate();
+
+    /**
+     * Destructor
+     */
+    virtual ~ThumbnailManagerPrivate();
+
+    /**
+     * Get quality versus performance preference.
+     */
+    ThumbnailManager::QualityPreference qualityPreference() const;
+    
+    /**
+     * Set quality versus performance preference.
+     */
+    bool setQualityPreference( ThumbnailManager::QualityPreference qualityPreference );
+    
+    /**
+     * Get the current desired size for thumbnail bitmaps.
+     */
+    QSize thumbnailSize() const;
+
+    /**
+     * Set desired size for thumbnail bitmaps.
+     */
+    bool setThumbnailSize( const QSize& aThumbnailSize );
+    
+    /**
+     * Set desired size for thumbnail bitmaps.
+     */
+    bool setThumbnailSize( ThumbnailManager::ThumbnailSize thumbnailSize );
+
+    /**
+     * Get current mode for thumbnail generation.
+     */
+    ThumbnailManager::ThumbnailMode mode() const;
+
+    /**
+     * Set mode for thumbnail generation. 
+     */
+    bool setMode( ThumbnailManager::ThumbnailMode mode );
+
+    /**
+     * Get a thumbnail for an object file. If a thumbnail already exists, it
+     * is loaded and if a thumbnail does not exist, it is created
+     * transparently. 
+     */
+    int getThumbnail( const QString& fileName, void * clientData, 
+            int priority );
+
+    /**
+     * Get a persistent thumbnail for an object file. If a thumbnail already
+     *  exists, it is loaded and if a thumbnail does not exist, it is created
+     * transparently. 
+     */    
+    int getThumbnail( unsigned long int aThumbnailId, void * clientData, 
+            int priority );
+    
+    /**
+     * Set a thumbnail for an object file generated from pixmap delivered.
+     * thumbnailReady() signal will be emited when the operation is complete.                           
+     */    
+    int setThumbnail( const QPixmap& source, const QString& fileName,
+            void * clientData, int priority );
+    
+    /**
+     * Delete all thumbnails for a given object. This is an asynchronous
+     * operation, which always returns immediately.
+     */
+    void deleteThumbnails( const QString& fileName );
+
+    /**
+     * Delete all thumbnails for a given object. This is an asynchronous
+     * operation, which always returns immediately.
+     */
+    void deleteThumbnails( unsigned long int thumbnailId );
+    
+    /**
+     * Cancel a thumbnail operation.
+     */
+    bool cancelRequest( int id );
+
+    /**
+     * Change the priority of a queued thumbnail operation.
+     */
+    bool changePriority( int id, int newPriority );
+
+    //FROM  MThumbnailManagerObserver
+    /**
+     * Preview thumbnail generation or loading is complete.
+     *
+     * This callback is not called unless EOptimizeForQualityWithPreview flag
+     * was specified.
+     *
+     * This callback is not called if any of the following is true:
+     * - an error occurred while processing the preview thumbnail
+     * - a suitable existing thumbnail was not found
+     * - a high quality thumbnail is already available
+     *
+     * The MThumbnailData instance is only valid for the duration of
+     * this call. It may not be stored for later use. If the client should
+     * want to use the bitmap data later, it can claim ownership of the
+     * CFbsBitmap object by calling DetachBitmap().
+     *
+     * @since S60 v5.0
+     * @param aThumbnail     An object representing the resulting thumbnail.
+     * @param aId            Request ID for the operation
+     */
+    void ThumbnailPreviewReady( MThumbnailData& aThumbnail,
+        TThumbnailRequestId aId );
+
+    /**
+     * Final thumbnail bitmap generation or loading is complete.
+     *
+     * The MThumbnailData instance is only valid for the duration of
+     * this call. It may not be stored for later use. If the client should
+     * want to use the bitmap data later, it can claim ownership of the
+     * CFbsBitmap object by calling DetachBitmap().
+     *
+     * @since S60 v5.0
+     * @param aError         Error code.
+     * @param aThumbnail     An object representing the resulting thumbnail.
+     * @param aId            Request ID for the operation.
+     */
+    void ThumbnailReady( TInt aError, MThumbnailData& aThumbnail,
+        TThumbnailRequestId aId );
+    
+
+signals:
+
+    /**
+     * Final thumbnail bitmap generation or loading is complete.
+     */
+    void thumbnailReady( QPixmap , void * , int , int );
+    
+    
+private:
+    /**
+     * Copy CFbsBitmap into a QPixmap.
+     */
+    QPixmap copyPixmap( CFbsBitmap* bitmap );
+    
+    
+private:
+
+    CThumbnailManager* iThumbnailManager;
+    
+    QByteArray* byteArray;
+};
+
+#endif // ThumbnailManager_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailmanagerqt/src/thumbnailmanager_p_qt.cpp	Fri Mar 19 09:35:30 2010 +0200
@@ -0,0 +1,236 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "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: 
+*
+*/
+
+#include <fbs.h>
+#include <qtcore>
+#include <qpixmap.h>
+#include <thumbnailmanager.h>
+#include <thumbnaildata.h>
+
+#include "thumbnailmanager_qt.h"
+#include "thumbnailmanager_p_qt.h"
+
+ThumbnailManagerPrivate::ThumbnailManagerPrivate() : iThumbnailManager( NULL ), byteArray( NULL )
+{
+    TRAP_IGNORE(
+        iThumbnailManager = CThumbnailManager::NewL( *this );
+        iThumbnailManager->SetDisplayModeL( EColor64K );
+        );
+}
+
+ThumbnailManagerPrivate::~ThumbnailManagerPrivate()
+{
+    if( iThumbnailManager ){
+        delete iThumbnailManager;
+    }
+    if( byteArray ){
+        delete byteArray;
+    }
+}
+
+ThumbnailManager::QualityPreference ThumbnailManagerPrivate::qualityPreference() const
+{
+    return static_cast<ThumbnailManager::QualityPreference>( iThumbnailManager->QualityPreference() );
+}
+
+bool ThumbnailManagerPrivate::setQualityPreference( ThumbnailManager::QualityPreference qualityPreference )
+{
+    TRAPD( err, iThumbnailManager->SetQualityPreferenceL( static_cast<CThumbnailManager::TThumbnailQualityPreference>(qualityPreference) ));
+    return ( err == KErrNone );
+}
+
+QSize ThumbnailManagerPrivate::thumbnailSize() const
+{
+    TSize tsize( iThumbnailManager->ThumbnailSize() );
+    QSize qsize( tsize.iWidth, tsize.iHeight);
+    return qsize;
+}
+
+bool ThumbnailManagerPrivate::setThumbnailSize( const QSize& thumbnailSize )
+{
+    TRAPD( err, iThumbnailManager->SetThumbnailSizeL( TSize( thumbnailSize.width(), thumbnailSize.height() ) ) );
+    return ( err == KErrNone );
+}
+
+bool ThumbnailManagerPrivate::setThumbnailSize( ThumbnailManager::ThumbnailSize thumbnailSize )
+{
+    TThumbnailSize size(EUnknownThumbnailSize);
+    switch( thumbnailSize ){
+    case ThumbnailManager::ThumbnailSmall:
+        size = EListThumbnailSize;
+        break;
+    case ThumbnailManager::ThumbnailMedium:
+        size = EGridThumbnailSize;
+        break;
+    case ThumbnailManager::ThumbnailLarge:
+        size = EFullScreenThumbnailSize;
+        break;
+    default:
+        break;
+    }
+
+    TRAPD( err, iThumbnailManager->SetThumbnailSizeL( size ) );
+    return ( err == KErrNone );
+}
+
+ThumbnailManager::ThumbnailMode ThumbnailManagerPrivate::mode() const
+{
+    return static_cast<ThumbnailManager::ThumbnailMode>( iThumbnailManager->Flags() );
+}
+
+bool ThumbnailManagerPrivate::setMode( ThumbnailManager::ThumbnailMode mode )
+{
+    TRAPD( err, iThumbnailManager->SetFlagsL( static_cast<CThumbnailManager::TThumbnailFlags>( mode ) ) );
+    return ( err == KErrNone );
+}
+
+int ThumbnailManagerPrivate::getThumbnail( const QString& fileName, void* clientData, 
+        int priority )
+{
+    int result( -1 );
+    QString symbFileName( fileName );
+
+    if( symbFileName.contains( "/" ) )
+        symbFileName.replace( "/", "\\", Qt::CaseSensitive );
+    
+    RBuf buf;
+    TRAP_IGNORE( 
+        CleanupClosePushL( buf );
+        buf.CreateL( symbFileName.length() );
+        buf.Copy( symbFileName.utf16(), symbFileName.length() );
+        CThumbnailObjectSource* objSrc = CThumbnailObjectSource::NewLC( buf, KNullDesC );
+        result = iThumbnailManager->GetThumbnailL( *objSrc, clientData, priority );
+        CleanupStack::PopAndDestroy( 2, &buf );
+    );
+    return result;
+}
+
+int ThumbnailManagerPrivate::getThumbnail( unsigned long int aThumbnailId, void* clientData, 
+        int priority )
+{
+    int result( -1 );
+    TRAP_IGNORE( result = iThumbnailManager->GetThumbnailL( aThumbnailId, clientData, priority ));
+    return result;
+}    
+
+int ThumbnailManagerPrivate::setThumbnail( const QPixmap& source, const QString& fileName, 
+        void * clientData, int priority )
+{
+    int result( -1 );
+    RBuf file;
+    _LIT( mime, "image/png" );
+
+    if( !byteArray ){
+        byteArray = new QByteArray();
+    }
+    QBuffer buffer( byteArray );
+    buffer.open( QBuffer::ReadWrite );
+    QDataStream dataStream( &buffer );
+
+    dataStream << source;
+
+    int offset = ( dataStream.version() >= 5 ? 4 : 0 );
+    
+    TRAP_IGNORE( 
+        CleanupClosePushL( file );
+        file.CreateL( fileName.length() );
+        file.Copy( fileName.utf16(), fileName.length() );
+
+        HBufC* mimetype = HBufC::NewLC( 9 );
+        mimetype->Des() = mime();
+
+        TPtrC8* ptr = new TPtrC8( reinterpret_cast<const TUint8*>( byteArray->data() + offset ), byteArray->count() - offset );
+                
+        CThumbnailObjectSource* objSrc = CThumbnailObjectSource::NewLC( ptr, *mimetype, file );
+        result = iThumbnailManager->SetThumbnailL( *objSrc, clientData, priority );
+        CleanupStack::PopAndDestroy( 3, &file );
+    );
+    return result;
+}
+
+void ThumbnailManagerPrivate::deleteThumbnails( const QString& fileName )
+{
+    QString symbFileName( fileName );
+
+    if( symbFileName.contains( "/" ) )
+        symbFileName.replace( "/", "\\", Qt::CaseSensitive );
+
+    RBuf buf;
+    TRAP_IGNORE( CleanupClosePushL( buf );
+        buf.CreateL( symbFileName.length() );
+        buf.Copy( symbFileName.utf16(), symbFileName.length() );
+        CThumbnailObjectSource* objSrc = CThumbnailObjectSource::NewL( buf, KNullDesC );
+        iThumbnailManager->DeleteThumbnails( *objSrc );
+        CleanupStack::PopAndDestroy( &buf );
+        delete objSrc;
+    );
+}
+
+void ThumbnailManagerPrivate::deleteThumbnails( unsigned long int thumbnailId )
+{
+    iThumbnailManager->DeleteThumbnails( thumbnailId );
+}
+
+bool ThumbnailManagerPrivate::cancelRequest( int id )
+{
+    return ( iThumbnailManager->CancelRequest( id ) == KErrNone );
+}
+
+bool ThumbnailManagerPrivate::changePriority( int id, int newPriority )
+{
+    return ( iThumbnailManager->ChangePriority( id, newPriority ) == KErrNone );
+}
+
+QPixmap ThumbnailManagerPrivate::copyPixmap( CFbsBitmap* bitmap )
+{
+    TSize size = bitmap->SizeInPixels();
+    int bytesPerLine = bitmap->ScanLineLength( size.iWidth,
+            bitmap->DisplayMode() );
+    const uchar* dataPtr = ( const uchar* ) bitmap->DataAddress();
+
+    return QPixmap::fromImage( QImage(  dataPtr,
+                                        size.iWidth,
+                                        size.iHeight,
+                                        bytesPerLine,
+                                        QImage::Format_RGB16 ) );
+}
+
+void ThumbnailManagerPrivate::ThumbnailPreviewReady( MThumbnailData& /*aThumbnail*/,
+    TThumbnailRequestId /*aId*/ )
+{
+}
+
+void ThumbnailManagerPrivate::ThumbnailReady( TInt aError, MThumbnailData& aThumbnail,
+    TThumbnailRequestId aId )
+{
+    if( byteArray ){
+        delete byteArray;
+        byteArray = NULL;
+    }
+    
+    QPixmap* pixmap( NULL );
+
+    if( aError == KErrNone ){
+        pixmap = new QPixmap( copyPixmap( aThumbnail.Bitmap() ) );
+    }else {
+        pixmap = new QPixmap();
+    }
+    
+    emit thumbnailReady( *pixmap, aThumbnail.ClientData(), aId, aError );
+    delete pixmap;
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailmanagerqt/src/thumbnailmanager_qt.cpp	Fri Mar 19 09:35:30 2010 +0200
@@ -0,0 +1,113 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "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: 
+*
+*/
+
+#include <qsize.h>
+#include "thumbnailmanager_qt.h"
+#include "thumbnailmanager_p_qt.h"
+ 
+EXPORT_C ThumbnailManager::ThumbnailManager( QObject* parentPtr ) :
+QObject( parentPtr ),
+d( new ThumbnailManagerPrivate() )
+{
+    QObject::connect( d, SIGNAL( thumbnailReady( QPixmap , void * , int , int ) ),
+            this, SIGNAL( thumbnailReady( QPixmap , void * , int , int ) ) );
+}
+
+
+EXPORT_C ThumbnailManager::~ThumbnailManager()
+{
+    QObject::disconnect( d, SIGNAL( thumbnailReady( QPixmap , void * , int , int ) ),
+            this, SIGNAL( thumbnailReady( QPixmap , void * , int , int ) ) );
+    if( NULL != d ){
+        delete d;
+    }
+}
+
+EXPORT_C ThumbnailManager::QualityPreference ThumbnailManager::qualityPreference() const
+{
+    return d->qualityPreference();
+}
+
+EXPORT_C bool ThumbnailManager::setQualityPreference( QualityPreference
+    qualityPreference )
+{
+    return d->setQualityPreference( qualityPreference );
+}
+ 
+EXPORT_C QSize ThumbnailManager::thumbnailSize() const
+{
+    return d->thumbnailSize();
+}
+
+EXPORT_C bool ThumbnailManager::setThumbnailSize( const QSize& thumbnailSize )
+{
+    return d->setThumbnailSize( thumbnailSize );
+}
+
+EXPORT_C bool ThumbnailManager::setThumbnailSize( ThumbnailSize thumbnailSize )
+{
+    return d->setThumbnailSize( thumbnailSize );
+}
+
+EXPORT_C ThumbnailManager::ThumbnailMode ThumbnailManager::mode() const
+{
+    return d->mode();
+}
+
+EXPORT_C bool ThumbnailManager::setMode( ThumbnailMode mode )
+{
+    return d->setMode( mode );
+}
+
+EXPORT_C int ThumbnailManager::getThumbnail( const QString& fileName, void * clientData, 
+        int priority )
+{
+    return d->getThumbnail( fileName, clientData, priority );
+}
+
+EXPORT_C int ThumbnailManager::getThumbnail( unsigned long int thumbnailId, void * clientData, 
+        int priority )
+{
+    return d->getThumbnail( thumbnailId, clientData, priority );
+}    
+
+EXPORT_C int ThumbnailManager::setThumbnail( const QPixmap& source, const QString& filename,
+        void * clientData , int priority )
+{
+    return d->setThumbnail( source, filename, clientData, priority );
+}
+
+EXPORT_C void ThumbnailManager::deleteThumbnails( const QString& fileName )
+{
+    d->deleteThumbnails( fileName );
+}
+
+EXPORT_C void ThumbnailManager::deleteThumbnails( unsigned long int thumbnailId )
+{
+    d->deleteThumbnails( thumbnailId );
+}
+
+EXPORT_C bool ThumbnailManager::cancelRequest( int id )
+{
+    return d->cancelRequest( id );
+}
+
+EXPORT_C bool ThumbnailManager::changePriority( int id, int newPriority )
+{
+    return d->changePriority( id, newPriority );
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailmanagerqt/thumbnailmanagerqt.iby	Fri Mar 19 09:35:30 2010 +0200
@@ -0,0 +1,25 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "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: 
+*
+*/
+
+#ifndef __THUMBNAILMANAGER_QT_IBY__
+#define __THUMBNAILMANAGER_QT_IBY__
+
+#include <bldvariant.hrh>
+
+file=ABI_DIR\BUILD_DIR\thumbnailmanagerqt.dll                       SHARED_LIB_DIR\thumbnailmanagerqt.dll
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailmanagerqt/thumbnailmanagerqt.pro	Fri Mar 19 09:35:30 2010 +0200
@@ -0,0 +1,51 @@
+#
+# Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of "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: 
+#
+#
+
+TEMPLATE = lib
+TARGET = thumbnailmanagerqt
+
+symbian:TARGET.UID3=0x20029F65
+
+
+INCLUDEPATH += .
+INCLUDEPATH += $$MW_LAYER_SYSTEMINCLUDE
+
+TARGET.CAPABILITY = CAP_GENERAL_DLL
+
+symbian:TARGET.EPOCALLOWDLLDATA = 1
+
+# Input
+LIBS +=     -lthumbnailmanager.dll \
+            -lfbscli.dll
+
+
+SOURCES += src/thumbnailmanager_qt.cpp \
+           src/thumbnailmanager_p_qt.cpp  
+          
+HEADERS += ../../../imagehandling_plat/thumbnailmanager_api/inc/thumbnailmanager_qt.h \
+           inc/thumbnailmanager_p_qt.h  
+
+BLD_INF_RULES.prj_exports += "thumbnailmanagerqt.iby /epoc32/rom/include/core/mw/"
+
+myDefInclude = "NOSTRICTDEF" \
+"$${LITERAL_HASH}if defined(WINS)"\
+"DEFFILE  bwins/thumbnailmanagerqt.def "\
+"$${LITERAL_HASH}else "\
+"DEFFILE  eabi/thumbnailmanagerqt.def "\
+"$${LITERAL_HASH}endif"
+MMP_RULES += myDefInclude
+
--- a/imagehandlingutilities/thumbnailmanager/thumbnailserver/group/thumbnailserver.mmp	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/group/thumbnailserver.mmp	Fri Mar 19 09:35:30 2010 +0200
@@ -49,19 +49,24 @@
 SOURCE                  thumbnaildiskunmountobserver.cpp
 SOURCE                  thumbnailcenrep.cpp 
 SOURCE                  thumbnailmemorycardobserver.cpp 
-SOURCE			        tmshutdownobserver.cpp 
-SOURCE 			        thumbnaildecodetask.cpp
+SOURCE		        thumbnaildecodetask.cpp
 #ifdef RD_MDS_2_5
-SOURCE					thumbnailmdsquerytask.cpp
+SOURCE			thumbnailmdsquerytask.cpp
 #endif // RD_MDS_2_5
-SOURCE					tnmgetimei.cc
-SOURCE					thumbnailformatobserver.cpp
+SOURCE			tmgetimei.cpp 
+
+SOURCEPATH		../../tmcommon/src
+SOURCE			tmshutdownobserver.cpp
+SOURCE			tmformatobserver.cpp
+SOURCE			tmactivitymanager.cpp
+
 
 // Default system include paths for middleware layer modules.
 MW_LAYER_SYSTEMINCLUDE
 
 USERINCLUDE             ../inc
 USERINCLUDE             ../../inc
+USERINCLUDE             ../../tmcommon/inc
 
 LIBRARY                 fbscli.lib
 LIBRARY                 euser.lib
@@ -74,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	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/thumbnailcenrep.h	Fri Mar 19 09:35:30 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/thumbnailformatobserver.h	Tue Feb 02 00:23:15 2010 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,94 +0,0 @@
-/*
-* Copyright (c) 2006 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:  Monitors File system for Format events
-*
-*/
-
-
-#ifndef CTHUMBNAILFORMATOBSERVER_H
-#define CTHUMBNAILFORMATOBSERVER_H
-
-#include <babackup.h>
-#include "f32file.h"
-#include "thumbnailserver.h" 
-
-/**
- *  File System monitor class to monitor for format events
- *
- *  @lib thumbnailsserver.exe
- *  @since S60 3.0
- */
-NONSHARABLE_CLASS( CThumbnailFormatObserver ) : public CBase,
-                                             public MBackupOperationObserver
-    {
-
-public:
-
-    /**
-    * Two-phase constructor
-    * @param aObserver observer to the monitor
-    */
-    static CThumbnailFormatObserver* NewL( CThumbnailServer* aServer );
-
-    /**
-    * Two-phase constructor
-    * @param aObserver observer to the monitor
-    */
-    static CThumbnailFormatObserver* NewLC( CThumbnailServer* aServer );
-
-    /**
-    * Destructor
-    */
-    virtual ~CThumbnailFormatObserver();
-
-public: // New functions
-
-    /**
-    * Polls for the current monitor status
-    * If an event is happening, it will callback the observer of the event
-    */
-    void PollStatus();
-
-protected: // Base Class
-
-    /*
-    * From MBackupOperationObserver
-    * Notifies this class of the backup event.
-    * MMC App will signal a start / end.
-    */
-    void HandleBackupOperationEventL(const TBackupOperationAttributes& aBackupOperationAttributes);
-
-private:
-
-    /**
-    *  C++ constructor
-    *  aObserver observer to this event
-    */
-    CThumbnailFormatObserver ( CThumbnailServer* aServer );
-
-    /*
-    * Second phased constructor
-    */
-    void ConstructL();
-
-private: // data
-
-    CThumbnailServer* iServer;    
-    
-    CBaBackupSessionWrapper* iBackupSession;
-
-    
-    };
-
-#endif // CTHUMBNAILFORMATOBSERVER_H
--- a/imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/thumbnailgeneratetask.h	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/thumbnailgeneratetask.h	Fri Mar 19 09:35:30 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 );
 
     /**
@@ -134,6 +134,15 @@
      * @param aOriginalSize Original size of bitmap.
      */
     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:
     // Data
@@ -192,6 +201,10 @@
      */
     TThumbnailSize iThumbnailSize;    
     
+	 /**
+     * timestamp
+     */
+    TInt64 iModified;
 
     /**
      * Size of the original image.
@@ -212,8 +225,6 @@
      */
     CThumbnailProvider* iProvider;
     
-    TThumbnailId iThumbnailId;
-    
     TBool iScaledBitmapToPool;
     
 #ifdef _DEBUG
--- a/imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/thumbnailmdsquerytask.h	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/thumbnailmdsquerytask.h	Fri Mar 19 09:35:30 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	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/thumbnailscaletask.h	Fri Mar 19 09:35:30 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	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/thumbnailserver.h	Fri Mar 19 09:35:30 2010 +0200
@@ -32,6 +32,7 @@
 #include "thumbnailmanagerconstants.h" // TThumbnailServerRequestId
 #include "thumbnailstore.h"     // TThumbnailPersistentSize
 #include "tmshutdownobserver.h"
+#include "tmformatobserver.h"
 
 // Needed for creating server thread.
 const TUint KDefaultHeapSize = 160 * 1024;
@@ -44,7 +45,6 @@
 class CThumbnailServerSession;
 class CThumbnailDiskUnmountObserver;
 class CThumbnailMemoryCardObserver;
-class CThumbnailFormatObserver;
 
 /**
  * Helper function to destroy all objects which are referred to
@@ -75,7 +75,8 @@
  */
 NONSHARABLE_CLASS( CThumbnailServer ): public CPolicyServer,
                                        public MMdESessionObserver,
-                                       public MTMShutdownObserver
+                                       public MTMShutdownObserver,
+                                       public MTMFormatObserver
     {
 public:
 
@@ -135,6 +136,9 @@
     // from MTMShutdownObserver
     void ShutdownNotification();
 
+    //From MTMFormatObserver
+    void FormatNotification(TBool aFormat);    
+    
     /**
      * Adds bitmap to bitmap pool. Server assumes ownership of the bitmap and
      * implements reference counting to know when it is safe to delete
@@ -144,9 +148,10 @@
      * @since S60 v5.0
      * @param aSession Server side session which owns the bitmap.
      * @param aBitmap Bitmap to be added to pool.
+     * @param aRequestId Session specific thumbnail request ID.
      */
     void AddBitmapToPoolL( CThumbnailServerSession* aSession, CFbsBitmap*
-        aBitmap );
+        aBitmap, TThumbnailServerRequestId aRequestId );
 
     /**
      * Store thumbnail.
@@ -162,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);
 
     /**
@@ -184,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
@@ -320,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
@@ -370,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 );
     
     /** 
@@ -434,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
@@ -526,7 +511,12 @@
      */
     void OpenStoresL();
     
- 
+    /**
+     * Callback for reconnect timer
+     *
+     * @since S60 v5.0
+     */
+    static TInt ReconnectCallBack(TAny* aAny);
 
 private:
 
@@ -572,6 +562,12 @@
          * Not own.
          */
         CFbsBitmap* iBitmap;
+        
+        /**
+         * Request Id 
+         */
+        TThumbnailRequestId iRequestId;        
+        
         };
 
 private:
@@ -650,7 +646,7 @@
     
     CThumbnailMemoryCardObserver* iMMCObserver;
     
-    CThumbnailFormatObserver* iFormatObserver;
+    CTMFormatObserver* iFormatObserver;
 
     /**
      * Databases for each drive, identified by drive (EDriveC, etc).
@@ -672,6 +668,9 @@
     
     TBool iFormatting;
     
+    // reconnect timer
+    CPeriodic* iReconnect;
+    
 #ifdef _DEBUG
     TUint32 iPlaceholderCounter;
 #endif
--- a/imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/thumbnailserversession.h	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/thumbnailserversession.h	Fri Mar 19 09:35:30 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
@@ -256,12 +248,19 @@
     /**
      * Update thumbnails by Thumbnail ID.
      * 
-     * 
      * @since S60 v5.0
      * @param aMessage Message.
      */
     void UpdateThumbnailsL( const RMessage2& aMessage );
     
+    /**
+     * Checks if client thread is still alive and RMessage2 handle valid.
+     *
+     * @since S60 v5.0
+     * @param aMessage Message.
+     */
+    TBool ClientThreadAlive(RMessage2& aMessage);    
+    
 private:
     // data
     /**
--- a/imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/thumbnailsql.h	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/thumbnailsql.h	Fri Mar 19 09:35:30 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,27 +198,25 @@
 //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 LIMIT 1"  );
-_LIT8( KThumbnailSelectTempModifiedByID, "SELECT Modified FROM TempThumbnailInfo WHERE TNId = :TNId AND ThumbFromPath = 1 LIMIT 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" );
 _LIT8 ( KGetDataRowID, "SELECT MAX (ThumbnailInfoData.rowID) FROM ThumbnailInfoData" );
 
 //remove KThumbnailDbFlagBlacklisted flag
-_LIT8( KThumbnailRemoveBlacklistedFlag, "UPDATE ThumbnailInfo SET Flags = Flags & ~:Flag WHERE Flags & :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	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/thumbnailstore.h	Fri Mar 19 09:35:30 2010 +0200
@@ -25,7 +25,7 @@
 #include "thumbnailcenrep.h"
 #include "thumbnailmanagerconstants.h"
 #include "thumbnaillog.h"
-#include "thumbnailserver.h"
+#include "tmactivitymanager.h"
 
 class RFs;
 class CFbsBitmap;
@@ -57,7 +57,7 @@
 
 
 /**
-* MMdSDiskSpaceNotifierObserver
+* MThumbnailStoreDiskSpaceNotifierObserver
 * Observer interface for a disk space notifier.
 */
 class MThumbnailStoreDiskSpaceNotifierObserver
@@ -80,7 +80,7 @@
     };
 
 /**
-* CMSDiskSpaceNotifierAO.
+* CThumbnailStoreDiskSpaceNotifierAO.
 * A disk space notifier class
 */
 class CThumbnailStoreDiskSpaceNotifierAO : public CActive
@@ -187,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 
@@ -229,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 );
 
     /**
@@ -258,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
@@ -314,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.
@@ -445,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:
     /**
@@ -464,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.
@@ -487,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);
 
     /**
@@ -498,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.
@@ -523,6 +462,8 @@
      */
     void StopAutoFlush();
     
+    void StartMaintenance();
+    
     /**
      * Callback for harvesting complete timer
      *
@@ -531,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  );
+    static TInt MaintenanceTimerCallBack(TAny* aAny);
+    
+    /**
+    * Touches blacklisted items
+    *
+    */
+    void PrepareBlacklistedItemsForRetryL();
     
     /**
-     * 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  );
+    * Deletes thumbs added to Deleted table
+    *
+    */
+    TInt DeleteMarkedL();
     
     /**
-    * Removes blacklisted flag from all entrys
+    * Checks if thumbnail source files are still in the file system.
+    * If not, delete corresponding thumbs.
     *
+    * @return ETrue, if finished.
     */
-    void RemoveDbFlagL(TThumbnailDbFlags aFlag);
+    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
 
@@ -603,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/inc/thumbnailtask.h	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/thumbnailtask.h	Fri Mar 19 09:35:30 2010 +0200
@@ -177,6 +177,14 @@
      * @since S60 v5.0
      */
     virtual void Continue();
+    
+    /**
+     * Checks if client thread is still alive and RMessage2 handle valid.
+     *
+     * @since S60 v5.0
+     * @param aGetThread Need to get thread first.
+     */
+    TBool ClientThreadAlive(const TBool aGetThread = ETrue);    
 
 protected:
     // data
@@ -205,6 +213,8 @@
      * Message.
      */
     RMessage2 iMessage;
+    
+    RThread iClientThread;
 };
 
 #endif // THUMBNAILTASK_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/tmgetimei.h	Fri Mar 19 09:35:30 2010 +0200
@@ -0,0 +1,50 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "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:  Helper class to get IMEI number. 
+*
+*/
+
+#ifndef TMGETIMEI_H
+#define TMGETIMEI_H
+
+#include <e32base.h>
+#include <etel3rdparty.h>
+
+#include "thumbnailmanagerconstants.h"
+
+class CTMGetImei: public CActive
+    {
+    private:
+        CTelephony *iTelephony;
+        CTelephony::TPhoneIdV1 iV1; 
+        TBuf<KImeiBufferSize> iImei;
+        CActiveSchedulerWait iAsw;
+    public:
+        virtual ~CTMGetImei();
+        static CTMGetImei* NewL();
+        static CTMGetImei* NewLC();
+        TBuf<KImeiBufferSize> GetIMEI();
+
+        void DoCancel();
+
+        void RunL();
+
+    private:
+        CTMGetImei(): CActive(EPriorityStandard), iTelephony(NULL)
+        {}
+        void ConstructL();
+    };
+
+#endif //TNMGETIMEI_H
+
--- a/imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/tmshutdownobserver.h	Tue Feb 02 00:23:15 2010 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,108 +0,0 @@
-/*
-* 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 Shutdown Observer
- *
-*/
-
-
-#ifndef TMSHUTDOWNOBSERVER_H
-#define TMSHUTDOWNOBSERVER_H
-
-#include <e32base.h>
-#include <w32std.h>
-#include <e32property.h> 
-
-
-/**
- * Observer interface for signaling the need for shutdown
- */
-class MTMShutdownObserver
-    {
-public:
-
-    virtual void ShutdownNotification() = 0;
-    };
-
-/**
- *  Active object for observing P&S keys
- *
- *  @since S60 v5.0
- */
-class CTMShutdownObserver: public CActive
-    {
-public:
-
-    /**
-     * Two-phased constructor.
-     *
-     * @since S60 v5.0
-     * @return Instance of CTMShutdownObserver.
-     */
-    static CTMShutdownObserver* NewL( MTMShutdownObserver& aObserver, const TUid& aKeyCategory,
-                                      const TInt aPropertyKey, TBool aDefineKey);
-
-    /**
-     * Destructor
-     *
-     * @since S60 v5.0
-     */
-    virtual ~CTMShutdownObserver();
-    
-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 CTMShutdownObserver.
-     */
-    CTMShutdownObserver( MTMShutdownObserver& aObserver, const TUid& aKeyCategory,
-                         const TInt iPropertyKey, TBool aDefineKey);
-
-    /**
-     * Symbian 2nd phase constructor can leave.
-     *
-     * @since S60 v5.0
-     */
-    void ConstructL();
-
-private:
-    
-    // not own
-    MTMShutdownObserver& iObserver;
-    
-    const TUid& iKeyCategory;
-    RProperty iProperty;
-    TInt iPropertyKey;
-    
-    TBool iDefineKey;
-};
-
-#endif // TMSHUTDOWNOBSERVER_H
--- a/imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/tnmgetimei.h	Tue Feb 02 00:23:15 2010 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,51 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "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:  Helper class to get IMEI number. 
-*
-*/
-
-#ifndef _TNMGETIMEI_H_
-#define _TNMGETIMEI_H_
-
-#include <e32base.h>
-#include <etel3rdparty.h>
-
-#include "thumbnailmanagerconstants.h"
-
-class CTnmgetimei: public CActive
-    {
-    private:
-        CTelephony *iTelephony;
-        CTelephony::TPhoneIdV1 iV1; 
-        TBuf<KImeiBufferSize> iImei;
-        CActiveSchedulerWait iAsw;
-    public:
-        virtual ~CTnmgetimei();
-        static CTnmgetimei* NewL();
-        static CTnmgetimei* NewLC();
-        TBuf<KImeiBufferSize> GetIMEI();
-
-        void DoCancel();
-
-        void RunL();
-
-    private:
-        CTnmgetimei(): CActive(EPriorityStandard), iTelephony(NULL)
-        {}
-        void ConstructL();
-
-    };
-
-#endif //_TNMGETIMEI_H_
-
--- a/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailcenrep.cpp	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailcenrep.cpp	Fri Mar 19 09:35:30 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/thumbnaildecodetask.cpp	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnaildecodetask.cpp	Fri Mar 19 09:35:30 2010 +0200
@@ -141,9 +141,9 @@
         return;
         }
       
-    if ( iMessage.Handle())
+    if ( ClientThreadAlive() )
        {
-       TRAP_IGNORE(iServer.AddBitmapToPoolL( iRequestId.iSession, aBitmap ));
+       TRAP_IGNORE(iServer.AddBitmapToPoolL( iRequestId.iSession, aBitmap, iRequestId ));
        const TSize bitmapSize = aBitmap->SizeInPixels();
        iBitmapHandle = aBitmap->Handle();
        aBitmap = NULL;
--- a/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailformatobserver.cpp	Tue Feb 02 00:23:15 2010 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,127 +0,0 @@
-/*
-* Copyright (c) 2006 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:  File System format monitor
-*
-*/
-
-#include "thumbnailformatobserver.h"
-#include "thumbnaillog.h"
- 
-#include <e32base.h>
-#include <f32file.h>
-
-
-// ======== MEMBER FUNCTIONS ========
-
-CThumbnailFormatObserver::CThumbnailFormatObserver ( CThumbnailServer* aServer): 
-     iServer( aServer )
-    {
-    TN_DEBUG1( "CThumbnailFormatObserver::CThumbnailFormatObserver()");
-    
-    }
-    
-    
-// ---------------------------------------------------------------------------
-// Second Phase Constructor
-// ---------------------------------------------------------------------------
-//
-void CThumbnailFormatObserver::ConstructL()
-    {
-    TN_DEBUG1("CThumbnailFormatObserver::ConstructL in");
-
-    iBackupSession = CBaBackupSessionWrapper::NewL();
-    iBackupSession->RegisterBackupOperationObserverL( *this );
-
-
-    TN_DEBUG1("CThumbnailFormatObserver::ConstructL out");
-    }
-
-
-// ---------------------------------------------------------------------------
-// Two-Phased Constructor
-// ---------------------------------------------------------------------------
-//
-CThumbnailFormatObserver* CThumbnailFormatObserver::NewL(CThumbnailServer* aServer )
-    {
-    CThumbnailFormatObserver* self = CThumbnailFormatObserver::NewLC( aServer );
-    CleanupStack::Pop( self );
-    return self;
-    }
-
-
-// ---------------------------------------------------------------------------
-// Two-Phased Constructor
-// ---------------------------------------------------------------------------
-//
-CThumbnailFormatObserver* CThumbnailFormatObserver::NewLC( CThumbnailServer* aServer )
-    {
-    CThumbnailFormatObserver* self = new( ELeave ) CThumbnailFormatObserver( aServer );
-    CleanupStack::PushL( self );
-    self->ConstructL();
-    return self;
-    }
-
-
-// ---------------------------------------------------------------------------
-// destructor
-// ---------------------------------------------------------------------------
-//
-CThumbnailFormatObserver::~CThumbnailFormatObserver()
-    {
-
-    if( iBackupSession )
-        {
-        iBackupSession->DeRegisterBackupOperationObserver( *this );
-        }
-    delete iBackupSession;
-    }
-
-// ---------------------------------------------------------------------------
-// Checks the current status
-// ---------------------------------------------------------------------------
-//
-void CThumbnailFormatObserver::PollStatus()
-    {
-    
-    TN_DEBUG1("CThumbnailFormatObserver::PollStatus()");
-    
-    TBool aFormatting = iBackupSession->IsBackupOperationRunning();
-    
-    if( aFormatting )
-        {        
-        TRAP_IGNORE(iServer->CloseRemovableDrivesL());   
-        }
-    }
-
-// ---------------------------------------------------------------------------
-// CThumbnailFormatObserver::HandleBackupOperationEventL
-// Handles a format operation
-// ---------------------------------------------------------------------------
-//
-void CThumbnailFormatObserver::HandleBackupOperationEventL(
-                  const TBackupOperationAttributes& aBackupOperationAttributes)
-    {
-    TN_DEBUG1("CThumbnailFormatObserver::HandleBackupOperationEventL in");
-
-    if( aBackupOperationAttributes.iOperation == EStart )
-        {
-        TRAP_IGNORE(iServer->CloseRemovableDrivesL());
-        }
-    else  // TOperationType::EEnd or TOperationType::EAbort
-        {
-        TRAP_IGNORE(iServer->OpenRemovableDrivesL());
-        }
-
-    TN_DEBUG1("CThumbnailFormatObserver::HandleBackupOperationEventL out");
-    }
--- a/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailgeneratetask.cpp	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailgeneratetask.cpp	Fri Mar 19 09:35:30 2010 +0200
@@ -20,7 +20,6 @@
 #include <fbs.h>
 
 #include <thumbnailmanager.h>
-
 #include "thumbnailgeneratetask.h"
 #include "thumbnailscaletask.h"
 #include "thumbnailprovider.h"
@@ -42,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);
@@ -158,17 +157,23 @@
         {
         iProvider->SetTargetSize( croppedTargetSize );
         }
-		
+	
+    TInt providerErr;
+    
     if ( !iBuffer )
         {
-        iProvider->GetThumbnailL( iServer.Fs(), iFile, iMimeType, iFlags,
-            iDisplayMode, iQualityPreference );
+        TRAP(providerErr, iProvider->GetThumbnailL( iServer.Fs(), iFile, iMimeType, iFlags,
+            iDisplayMode, iQualityPreference ) );
         }
     else
         {
-        iProvider->GetThumbnailL( iServer.Fs(), iBuffer, iMimeType, iFlags,
-            iDisplayMode, iQualityPreference );
+        TRAP( providerErr, iProvider->GetThumbnailL( iServer.Fs(), iBuffer, iMimeType, iFlags,
+            iDisplayMode, iQualityPreference ));
         }
+    
+    DoBlacklisting( providerErr, TSize(0,0) );
+    
+    User::LeaveIfError( providerErr );
     }
 
 
@@ -277,23 +282,9 @@
         {
         delete aBitmap;
         aBitmap = NULL;
-        // Create a temporary bitmap of size 1 for storing blacklisted thumbnail
-        // Because no actual bitmap data is generated, there is no reason to 
-        // add bitmap to server bitmap pool. Completion of client request with
-        // error code just results in applications showing their default bitmap. 
-        if( iFilename != KNullDesC || iTargetUri != KNullDesC )
-            {
-            if ( aError == KErrNotSupported ||
-                    aError == KErrCorrupt ||
-                    aError == KErrCompletion)
-                {
-                TRAPD( err, CreateBlackListedL( aOriginalSize ) );
-                if (err != KErrNone)
-                    {
-                    TN_DEBUG2( "CThumbnailGenerateTask::ThumbnailProviderReady() - blacklisting failed with code %d", err );
-                    }
-                }
-            }
+
+        DoBlacklisting( aError, aOriginalSize );
+            
         Complete( aError );
         }
     else
@@ -324,7 +315,7 @@
     __ASSERT_DEBUG(( aBitmap ), ThumbnailPanic( EThumbnailNullPointer ));
 
     CleanupStack::PushL( aBitmap );
-    iServer.AddBitmapToPoolL( iRequestId.iSession, aBitmap );
+    iServer.AddBitmapToPoolL( iRequestId.iSession, aBitmap, iRequestId );
 
     // Keep pointer so we can delete bitmap from pool
     iBitmap = aBitmap;
@@ -363,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;
@@ -420,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;
@@ -476,6 +467,7 @@
 //
 void CThumbnailGenerateTask::CreateBlackListedL( const TSize& aOriginalSize )
     {
+    TN_DEBUG1( "CThumbnailGenerateTask::CreateBlackListedL()");
     CFbsBitmap* tempBitmap = 0;
     tempBitmap = new (ELeave) CFbsBitmap();
     CleanupStack::PushL( tempBitmap );
@@ -486,16 +478,70 @@
     // consider blacklisting all sizes (hence the changes are needed in thumbnail fetching logic too).
     // However, decoding of source to thumnail could succeed in other sizes, which makes blacklisting
     // of requested size only meaningful. 
+    
     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 );
     }
+
+// ---------------------------------------------------------------------------
+// Checks is blacklisting needed
+// ---------------------------------------------------------------------------
+//
+void CThumbnailGenerateTask::DoBlacklisting( const TInt aError, const TSize& aOriginalSize )
+    {
+    TN_DEBUG1( "CThumbnailGenerateTask::DoBlacklisting()");
+    // Create a temporary bitmap of size 1 for storing blacklisted thumbnail
+    // Because no actual bitmap data is generated, there is no reason to 
+    // add bitmap to server bitmap pool. Completion of client request with
+    // error code just results in applications showing their default bitmap. 
+    if( aError != KErrNone && (iFilename != KNullDesC || iTargetUri != KNullDesC ))
+        {
+        if (aError == KErrNotFound ||
+            aError == KErrNotSupported ||
+            aError == KErrCorrupt ||
+            aError == KErrCompletion ||
+            aError == KErrUnderflow ||
+            aError == KErrNotReady)
+            {
+        
+        if(iMissingSizes)
+            {
+            TN_DEBUG2( "CThumbnailGenerateTask::DoBlacklisting() - blacklist missing sizes count = %d", iMissingSizes->Count() );
+
+            for ( TInt i( 0 ); i < iMissingSizes->Count(); i++ )
+                {
+                iThumbnailSize = (*iMissingSizes)[ i ].iType;
+                TRAPD( err, CreateBlackListedL( aOriginalSize ) );
+                if (err != KErrNone)
+                   {
+                   TN_DEBUG3( "CThumbnailGenerateTask::DoBlacklisting() - blacklisting missing size %d failed with code %d", iThumbnailSize, err );
+                   }
+                }
+            return;
+            }
+        else
+            {
+            TN_DEBUG1( "CThumbnailGenerateTask::DoBlacklisting() - blacklist single size" );
+            TRAPD( err, CreateBlackListedL( aOriginalSize ) );
+            if (err != KErrNone)
+                {
+                TN_DEBUG2( "CThumbnailGenerateTask::DoBlacklisting() - blacklisting failed with code %d", err );
+                }
+            return;
+            }
+        }
+    TN_DEBUG1( "CThumbnailGenerateTask::DoBlacklisting() - not blacklisted " );        
+    }
+}
+
+
--- a/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailmdsquerytask.cpp	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailmdsquerytask.cpp	Fri Mar 19 09:35:30 2010 +0200
@@ -87,83 +87,39 @@
             
             TN_DEBUG2( "CThumbnailMDSQueryTask::HandleQueryCompleted() - URI = %S", &object->Uri() );
                             
-            if( iUpdateToDb)
-                {
-                //update IDs to database by Path
-                if (iMessage.Handle())
-                    {
-                    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 (iMessage.Handle())
-                        {
-                        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
-            Complete( KThumbnailErrThumbnailNotFound );
-            ResetMessageData();
+            else
+                {
+                ReturnPath(object->Uri());
+                }
             }
         else
             {
-            TN_DEBUG1( "CThumbnailMDSQueryTask::HandleQueryCompleted() - Don't ever come here" );
-            Complete( KErrNotFound );
-            ResetMessageData();
+            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 ) );
-	                    }
-	               
-	            Complete( KThumbnailErrThumbnailNotFound );
-	            ResetMessageData();
-	            }
-	        else 
-	            {
-	            Complete( KErrNotFound );
-	            ResetMessageData();
-            	}
+        if(!iDelete)
+            {
+            if (ClientThreadAlive(EFalse))
+                {  
+                Complete( KErrNotFound );
+                ResetMessageData();
+                }
+            }
         }
    }
 
@@ -178,6 +134,15 @@
 
     CThumbnailTask::StartL();
 
+    // get client thread
+    TInt err = iMessage.Client( iClientThread );
+    if (err != KErrNone)
+        {
+        TN_DEBUG2( "CThumbnailTask(0x%08x)::ClientThreadAlive() - client thread not found", this);
+    
+        ResetMessageData();
+        }
+    
     // start query
     iQuery->FindL();
     }
@@ -209,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 );
     
@@ -232,20 +198,17 @@
 //
 void CThumbnailMDSQueryTask::ReturnPath(const TDesC& aUri)
     {
-    if ( iMessage.Handle())
+    if ( ClientThreadAlive(EFalse) )
         {
         // add path to message
-        if (iMessage.Handle())
+        TInt ret = iMessage.Read( 0, iRequestParams );      
+        if(ret == KErrNone)
             {
-            TInt ret = iMessage.Read( 0, iRequestParams );      
-            if(ret == KErrNone)
-                {
-                TThumbnailRequestParams& params = iRequestParams();
-                params.iFileName = aUri;
-                ret = iMessage.Write( 0, iRequestParams );
-                }
+            TThumbnailRequestParams& params = iRequestParams();
+            params.iFileName = aUri;
+            ret = iMessage.Write( 0, iRequestParams );
             }
-    
+            
         // complete the message with a code from which client side
         // knows to make a new request using the path
         Complete( KThumbnailErrThumbnailNotFound );
@@ -254,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	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailscaletask.cpp	Fri Mar 19 09:35:30 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 );
@@ -86,7 +86,7 @@
 //
 void CThumbnailScaleTask::ConstructL()
     {
-    iServer.AddBitmapToPoolL( NULL, iOwnBitmap );
+    iServer.AddBitmapToPoolL( iRequestId.iSession, iOwnBitmap, iRequestId );
 
     // Successfully added bitmap to pool, we are no longer responsible for
     // deleting it directly.
@@ -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,34 +346,35 @@
             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 );
             }
         }    
     
-    if ( iMessage.Handle() )
+    if ( ClientThreadAlive() )
         {
         TN_DEBUG1("CThumbnailScaleTask()::StoreAndCompleteL() scaled bitmap handle to params");
         
-    	TThumbnailRequestParams& params = iParamsBuf();
-		iMessage.ReadL( 0, iParamsBuf );
-		params.iBitmapHandle = iScaledBitmap->Handle();
-	   
+        TThumbnailRequestParams& params = iParamsBuf();
+        iMessage.ReadL( 0, iParamsBuf );
+                    
         // if need to add scaled bitmap to pool
         if (iBitmapToPool)
             {
             TN_DEBUG1("CThumbnailScaleTask()::StoreAndCompleteL() scaled bitmap to pool");
             
-            iServer.AddBitmapToPoolL( iRequestId.iSession, iScaledBitmap );
+            params.iBitmapHandle = iScaledBitmap->Handle();
+            
+            iServer.AddBitmapToPoolL( iRequestId.iSession, iScaledBitmap, iRequestId );
             iScaledBitmapHandle = params.iBitmapHandle;
             }    
 		
--- a/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailserver.cpp	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailserver.cpp	Fri Mar 19 09:35:30 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>
 
@@ -35,8 +35,7 @@
 #include "thumbnailpanic.h"
 #include "thumbnailcenrep.h"
 #include "thumbnailmemorycardobserver.h"
-#include "tnmgetimei.h"
-#include "thumbnailformatobserver.h"
+#include "tmgetimei.h"
 
 
 _LIT8( KThumbnailMimeWildCard, "*" );
@@ -55,7 +54,7 @@
 // ----------------------------------------------------------------------------------------
 // Total number of ranges
 // ----------------------------------------------------------------------------------------
-const TUint KThumbnailServerRangeCount = 17;
+const TUint KThumbnailServerRangeCount = 16;
  
 // ----------------------------------------------------------------------------------------
 // Definition of the ranges
@@ -67,7 +66,6 @@
     EReleaseBitmap,
     ECancelRequest,
     EChangePriority,
-    ECreateThumbnails,
     EDeleteThumbnails,
     EGetMimeTypeBufferSize,
     EGetMimeTypeList,
@@ -91,7 +89,6 @@
     CPolicyServer::ECustomCheck,    // EReleaseBitmap
     CPolicyServer::ECustomCheck,    // ECancelRequest
     CPolicyServer::ECustomCheck,    // EChangePriority
-    CPolicyServer::ECustomCheck,    // ECreateThumbnails
     CPolicyServer::ECustomCheck,    // EDeleteThumbnails
     CPolicyServer::ECustomCheck,    // EGetMimeTypeBufferSize
     CPolicyServer::ECustomCheck,    // EGetMimeTypeList
@@ -140,7 +137,6 @@
         case EReleaseBitmap:
         case ECancelRequest:
         case EChangePriority:
-        case ECreateThumbnails:
         case EDeleteThumbnails:
         case EGetMimeTypeBufferSize:
         case EGetMimeTypeList:
@@ -234,10 +230,10 @@
     REComSession::ListImplementationsL( TUid::Uid( THUMBNAIL_PROVIDER_IF_UID ),
         iPluginInfoArray );
     
-    CTnmgetimei * imeigetter = CTnmgetimei::NewLC();
+    CTMGetImei * imeiGetter = CTMGetImei::NewLC();
    
-    iImei = imeigetter->GetIMEI();
-    CleanupStack::PopAndDestroy(imeigetter);
+    iImei = imeiGetter->GetIMEI();
+    CleanupStack::PopAndDestroy(imeiGetter);
     
     iFs.CreatePrivatePath(EDriveC);
     iFs.SetSessionToPrivate(EDriveC);
@@ -248,13 +244,15 @@
             
     iMMCObserver = CThumbnailMemoryCardObserver::NewL( this, iFs );
     
-    iFormatObserver = CThumbnailFormatObserver::NewL( this );
+    iFormatObserver = CTMFormatObserver::NewL( *this );
     
     iFormatting = EFalse;
     
-    OpenStoresL();
+    //OpenStoresL();
     
     AddUnmountObserversL();
+    
+    iReconnect = CPeriodic::NewL(CActive::EPriorityIdle);
     }
 
 
@@ -271,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 );
@@ -319,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" );
+            }
+        } 
     }
 
 // -----------------------------------------------------------------------------
@@ -398,6 +411,33 @@
     iSessionCount--;
     
     iProcessor->RemoveTasks(aSession);
+    
+    TN_DEBUG2( "CThumbnailServer::DropSession() aSession = 0x%08x", aSession );        
+    
+    // clean-up bitmap pool
+    
+    THashMapIter < TInt, TThumbnailBitmapRef > bpiter( iBitmapPool );
+
+    // const pointer to a non-const object
+    const TThumbnailBitmapRef* ref = bpiter.NextValue();
+
+    while ( ref )
+        {
+        
+        TN_DEBUG2( "CThumbnailServer::DropSession() - ref->iSession = 0x%08x", ref->iSession );
+        
+        if ( ref->iSession == aSession )
+            {            
+            delete ref->iBitmap;            
+            bpiter.RemoveCurrent();
+                        
+            TN_DEBUG2( "CThumbnailServer::DropSession() - deleted bitmap, left=%d", 
+                                iBitmapPool.Count());
+            }
+        ref = bpiter.NextValue();
+        
+        }
+
     if ( iSessionCount <= 0 )
         {
         // rename thread
@@ -432,7 +472,7 @@
 // -----------------------------------------------------------------------------
 //
 void CThumbnailServer::AddBitmapToPoolL( CThumbnailServerSession* aSession,
-    CFbsBitmap* aBitmap )
+    CFbsBitmap* aBitmap, TThumbnailServerRequestId aRequestId )
     {
     if( !aBitmap )
         {
@@ -444,6 +484,8 @@
 
     TThumbnailBitmapRef* ptr = iBitmapPool.Find( aBitmap->Handle());
 
+    TN_DEBUG2( "CThumbnailServer::AddBitmapToPoolL() - id = %d", aRequestId.iRequestId );
+    
     if ( ptr )
         {
         ptr->iRefCount++;
@@ -453,7 +495,9 @@
         TThumbnailBitmapRef ref;
         ref.iBitmap = aBitmap;
         ref.iSession = aSession;
-        ref.iRefCount = 1; // magic: first reference
+        ref.iRefCount = 1; // magic: first reference        
+        ref.iRequestId = aRequestId.iRequestId;               
+        
         iBitmapPool.InsertL( aBitmap->Handle(), ref );
         }
     
@@ -469,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 );
@@ -480,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
         {
@@ -528,6 +572,7 @@
             delete ptr->iBitmap;
             ptr->iBitmap = NULL;
             iBitmapPool.Remove( aHandle );
+            TN_DEBUG2( "CThumbnailServer::DeleteBitmapFromPool -- items left %d", iBitmapPool.Count() );
             }
         else
             {
@@ -538,6 +583,7 @@
         }
     else
         {
+        //__ASSERT_DEBUG(( EFalse ), ThumbnailPanic( EThumbnailBitmapNotReleased ));
         TN_DEBUG2( "CThumbnailServer::DeleteBitmapFromPool(%d) -- not found!",
             aHandle );
         }
@@ -555,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()
 // -----------------------------------------------------------------------------
@@ -741,7 +752,35 @@
 //
 TInt CThumbnailServer::DequeTask( const TThumbnailServerRequestId& aRequestId )
     {
-    return iProcessor->RemoveTask( aRequestId );
+    
+    TInt error = iProcessor->RemoveTask( aRequestId );
+        
+    // clean-up bitmap pool        
+        
+    THashMapIter < TInt, TThumbnailBitmapRef > bpiter( iBitmapPool );
+
+    // const pointer to a non-const object
+    const TThumbnailBitmapRef* ref = bpiter.NextValue();
+
+    while ( ref )
+        {
+        
+        TN_DEBUG2( "CThumbnailServer::DequeTask() - ref->iRequestId = %d", ref->iRequestId );
+
+        if ( ref->iSession == aRequestId.iSession && 
+             ref->iRequestId == aRequestId.iRequestId )
+            {            
+            delete ref->iBitmap;            
+            bpiter.RemoveCurrent();                        
+                        
+            TN_DEBUG2( "CThumbnailServer::DequeTask() - deleted bitmap, left=%d", 
+                                iBitmapPool.Count());
+            }
+        ref = bpiter.NextValue();
+        
+        }
+
+    return error;
     }
 
 
@@ -849,60 +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);
-        
-        TRAP_IGNORE( store->FetchThumbnailL( aThumbnailId, aThumbnail, aData, aThumbnailSize, aOriginalSize ));
-        
-        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
@@ -963,9 +948,6 @@
                 // ignore errors
                 TRAP_IGNORE( StoreForDriveL( i ));
                 
-                // start also placeholder task
-                //AddPlaceholderTaskL(i);
-                
                 driveCountInt--;
                 }
             }            
@@ -999,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 );
     }
 
 // ---------------------------------------------------------------------------
@@ -1081,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
@@ -1147,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()");
@@ -1155,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");
     
@@ -1513,23 +1455,9 @@
     }
 
 // -----------------------------------------------------------------------------
-// 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
 // -----------------------------------------------------------------------------
 //
-
 void CThumbnailServer::CloseRemovableDrivesL()
     {
     TDriveList driveList;
@@ -1564,7 +1492,6 @@
 // Open Stores for removable drives
 // -----------------------------------------------------------------------------
 //
-
 void CThumbnailServer::OpenRemovableDrivesL()
     {
     TDriveList driveList;
@@ -1598,9 +1525,53 @@
 // Is formatting ongoing
 // -----------------------------------------------------------------------------
 //
-
 TBool CThumbnailServer::IsFormatting()
     {
     return iFormatting;
     }
 
+// ---------------------------------------------------------------------------
+// CThumbnailServer::FormatNotification
+// Handles a format operation
+// ---------------------------------------------------------------------------
+//
+void CThumbnailServer::FormatNotification( TBool aFormat )
+    {
+    TN_DEBUG2( "CThumbnailServer::FormatNotification(%d)", aFormat );
+    
+    if(aFormat)
+        {
+        TRAP_IGNORE( CloseRemovableDrivesL() );
+        }
+    else 
+        {
+        TRAP_IGNORE( OpenRemovableDrivesL() );
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// 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	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailserversession.cpp	Fri Mar 19 09:35:30 2010 +0200
@@ -102,11 +102,6 @@
                 err = ChangePriority( aMessage );
                 break;
                 }
-        case ECreateThumbnails:
-                {
-                CreateThumbnailsL( aMessage );
-                break;
-                }
         case EDeleteThumbnails:
                 {
                 DeleteThumbnailsL( aMessage );
@@ -243,17 +238,65 @@
     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)
         {
-        TN_DEBUG1( "CThumbnailServerSession::UpdateThumbnailsL() - finished" );
+        // source type
+        TDataType mimeType;
+        TInt sourceType = 0;
+        TInt err = Server()->MimeTypeFromFileExt( params.iFileName, mimeType );
+        
+        // get missing sizes
+        if ( err == KErrNone && ( params.iControlFlags & EThumbnailGeneratePersistentSizesOnly ) != 0 )
+            {
+            sourceType = Server()->SourceTypeFromMimeType( mimeType );
+            
+            missingSizes = new (ELeave) RArray < TThumbnailPersistentSize >;
+            CleanupClosePushL( *missingSizes );
         
-        aMessage.Complete( KErrNone );
+            Server()->GetMissingSizesL( params.iFileName, sourceType, *missingSizes, gridSizeOnly );
+                
+            if ( missingSizes->Count() == 0)
+                {
+                // all thumbs already exist
+                CleanupStack::PopAndDestroy( missingSizes );
+                delete missingSizes;
+                missingSizes = NULL;
+                }            
+            }
+        
+        if(!missingSizes)
+            {
+            TN_DEBUG1( "CThumbnailServerSession::UpdateThumbnailsL() - finished part 1" );
+            aMessage.Complete( KErrNone );
+            }
+        else
+            {
+            TN_DEBUG1( "CThumbnailServerSession::UpdateThumbnailsL() - some sizes missing..." ); 
+            }
         }
-    else
+
+    if (missingSizes || !finished)
         {
-        TN_DEBUG1( "CThumbnailServerSession::UpdateThumbnailsL() - need to recreate thumbs" );
+        TN_DEBUG1( "CThumbnailServerSession::UpdateThumbnailsL() - need to create (some) thumbs" );
+        
+        if(missingSizes)
+            {
+            CleanupStack::PopAndDestroy( missingSizes );
+            delete missingSizes;
+            missingSizes = NULL;
+            }
         
         if(Server()->StoreForPathL(params.iFileName)->IsDiskFull())
             {
@@ -263,6 +306,10 @@
         // need to create new thumbs
         aMessage.Complete( KThumbnailErrThumbnailNotFound );
         }
+    else
+        {
+        TN_DEBUG1( "CThumbnailServerSession::UpdateThumbnailsL() - finished part 2" );
+        }
     
     iMessage = RMessage2();
     }
@@ -289,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
@@ -344,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" );
@@ -392,6 +398,7 @@
     // CreateThumbnails
     if (params.iControlFlags == EThumbnailGeneratePersistentSizesOnly)
         {
+        TN_DEBUG1( "CThumbnailServerSession::RequestThumbByFileHandleAsyncL() - EThumbnailGeneratePersistentSizesOnly" );
         CleanupClosePushL( file );
         CreateGenerateTaskFromFileHandleL( &file );
         CleanupStack::Pop( &file );         
@@ -401,7 +408,15 @@
         {
         TRAPD( err, FetchThumbnailL());
         
-        if ( !err && iBitmap )
+        if( err == KErrCompletion )
+            {
+            // If thumbnail of requested size is blacklisted, fetching is left with KErrCompletion
+            TN_DEBUG1( 
+                "CThumbnailServerSession::RequestThumbByFileHandleAsyncL() - thumbnail blacklisted" );
+            aMessage.Complete( err );
+            iMessage = RMessage2();
+            }
+        else if ( !err && iBitmap )
             {
             TN_DEBUG1( "CThumbnailServerSession::RequestThumbByFileHandleAsyncL() - found existing thumbnail - bitmap " );
 
@@ -414,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)
@@ -516,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();
 	        }
@@ -542,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
-	        
 	        }   
 	   }
     
@@ -627,7 +626,7 @@
     CFbsBitmap* bitmap = new( ELeave )CFbsBitmap();
     CleanupStack::PushL( bitmap );
     User::LeaveIfError( bitmap->Duplicate( bitmapHandle ) );
-    Server()->AddBitmapToPoolL( reqId.iSession, bitmap );
+    Server()->AddBitmapToPoolL( reqId.iSession, bitmap, reqId );
     CleanupStack::Pop( bitmap );
     iBitmapHandle = bitmap->Handle();
     
@@ -637,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 )
@@ -647,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)
             {
@@ -678,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 );
             
@@ -693,8 +689,6 @@
                 iMessage = RMessage2();
                 }
             }
-        
-        TN_DEBUG3("CThumbnailServerSession::RequestSetThumbnailByBitmapL() ID = %d, missingIDs = %d", params.iThumbnailId, missingIDs);
         }
     else
         {
@@ -714,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()
@@ -748,8 +725,6 @@
         {
         User::Leave( KErrDiskFull );
         }
-      
-    TBool missingIDs = EFalse;
     
     RArray < TThumbnailPersistentSize >* missingSizes = NULL;
     
@@ -760,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)
             {
@@ -820,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 )
@@ -897,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)
             {
@@ -931,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 )
@@ -977,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)
@@ -1006,36 +960,52 @@
     TThumbnailRequestParams& params = iRequestParams();
     
     // in import case store bitmap
-    if (params.iTargetUri != KNullDesC)
+    if ( params.iTargetUri != KNullDesC && params.iFileName != KNullDesC &&
+         params.iFileName.CompareF(params.iTargetUri) != 0 )
         {
         Server()->StoreThumbnailL( params.iTargetUri, iBitmap, iOriginalSize,
-                                   params.iFlags& CThumbnailManager::ECropToAspectRatio, params.iThumbnailSize, params.iThumbnailId );
+                                   params.iFlags& CThumbnailManager::ECropToAspectRatio,
+                                   params.iThumbnailSize, params.iModified,
+                                   EFalse, EFalse);
         }
     
-    // No need to scale, return iBitmap directly
-    Server()->AddBitmapToPoolL( this, iBitmap );
-    CFbsBitmap* bitmap = iBitmap;
-    iBitmap = NULL; // owned by server now
-    
-    params.iBitmapHandle = bitmap->Handle();
-    const TSize bitmapSize = bitmap->SizeInPixels();
+    if ( ClientThreadAlive(iMessage) )
+        {        
+        // No need to scale, return iBitmap directly
+        
+        TThumbnailServerRequestId &reqId = (TThumbnailServerRequestId&)params.iRequestId;
+        // No need to scale, return iBitmap directly
+        Server()->AddBitmapToPoolL( this, iBitmap, reqId );
+                
+        CFbsBitmap* bitmap = iBitmap;
+        
+        TN_DEBUG2("CThumbnailServerSession::ProcessBitmapL(), iBitmap handle= 0x%08x", bitmap->Handle());
+        
+        iBitmap = NULL; // owned by server now
+        
+        params.iBitmapHandle = bitmap->Handle();
+        const TSize bitmapSize = bitmap->SizeInPixels();
+        
+        if ( params.iQualityPreference == CThumbnailManager
+            ::EOptimizeForQualityWithPreview && bitmapSize.iWidth <
+            params.iSize.iWidth && bitmapSize.iHeight < params.iSize.iHeight &&
+            bitmapSize.iWidth < iOriginalSize.iWidth && bitmapSize.iHeight <
+            iOriginalSize.iHeight )
+            {
+            // This is a non-scaled preview bitmap
+            params.iControlFlags = EThumbnailPreviewThumbnail;
+            }
 
-    if ( params.iQualityPreference == CThumbnailManager
-        ::EOptimizeForQualityWithPreview && bitmapSize.iWidth <
-        params.iSize.iWidth && bitmapSize.iHeight < params.iSize.iHeight &&
-        bitmapSize.iWidth < iOriginalSize.iWidth && bitmapSize.iHeight <
-        iOriginalSize.iHeight )
-        {
-        // This is a non-scaled preview bitmap
-        params.iControlFlags = EThumbnailPreviewThumbnail;
-        }
-
-    if ( iMessage.Handle() )
-        {
         iMessage.WriteL( 0, iRequestParams );
+        
         iMessage.Complete( KErrNone );
         iMessage = RMessage2();
         }            
+    else
+        {
+        delete iBitmap;
+        iBitmap = NULL;
+        }
     }
 
 // -----------------------------------------------------------------------------
@@ -1122,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();
     }
@@ -1259,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 
@@ -1346,4 +1325,51 @@
     return e32Err;
     }
 
+// ---------------------------------------------------------------------------
+// CThumbnailServerSession::ClientThreadAlive()
+// Checks if client thread is still alive and RMessage2 handle valid.
+// ---------------------------------------------------------------------------
+//
+TBool CThumbnailServerSession::ClientThreadAlive(RMessage2& aMessage)
+    {
+    if ( aMessage.Handle())
+        {
+        RThread clientThread;
+    
+        // get client thread
+        TInt err = aMessage.Client( clientThread );
+        if (err != KErrNone)
+            {
+            TN_DEBUG1( "CThumbnailServerSession::ClientThreadAlive() - client thread not found");
+        
+            aMessage = RMessage2();
+            
+            return EFalse;
+            }
+    
+        // check if client thread alive
+        TExitType exitType = clientThread.ExitType();
+        
+        clientThread.Close();
+        
+        if( exitType != EExitPending )
+            {
+            TN_DEBUG1( "CThumbnailServerSession::ClientThreadAlive() - client thread died");
+        
+            aMessage = RMessage2();
+            
+            return EFalse;
+            }
+        else
+            {
+            // all OK
+            return ETrue;
+            }
+        }
+    else
+        {
+        return EFalse;
+        }
+    }
+
 // End of file
--- a/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailstore.cpp	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailstore.cpp	Fri Mar 19 09:35:30 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())
         {
@@ -194,119 +216,258 @@
     pathPtr.Append( driveChar );
     pathPtr.Append( KThumbnailDatabaseName );
     
+	//start disk space monitor
     iDiskFullNotifier = CThumbnailStoreDiskSpaceNotifierAO::NewL( *this, 
                                             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();
-            
-            //Remove blacklist markings
-            TRAP_IGNORE( RemoveDbFlagL( KThumbnailDbFlagBlacklisted ) );
-            }
-        
-        //check is MMC known
-        if(CheckMediaIDL() != KErrNone )
-            {
-            ResetThumbnailIDs();
-            
-            //Remove blacklist markings
-            TRAP_IGNORE( RemoveDbFlagL( KThumbnailDbFlagBlacklisted ) );
-            }
+        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.
@@ -314,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" );
 
@@ -365,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 );
@@ -390,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() ));
@@ -413,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 );
     
@@ -451,24 +618,34 @@
 //
 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 )
     {
-    TN_DEBUG1( "CThumbnailStore::StoreThumbnailL( CFbsBitmap* ) in" );
+    TSize thumbSize = aThumbnail->SizeInPixels();
+    TN_DEBUG4( "CThumbnailStore::StoreThumbnailL( CFbsBitmap ) aThumbnailSize = %d, aThumbnailSize(%d,%d) IN", aThumbnailSize, thumbSize.iWidth, thumbSize.iHeight );
 
     __ASSERT_DEBUG(( aThumbnail ), ThumbnailPanic( EThumbnailNullPointer ));
+    
+    // don't store custom/unknown sizes or zero sizes
+    if(aThumbnailSize == ECustomThumbnailSize || aThumbnailSize == EUnknownThumbnailSize 
+            || thumbSize.iWidth <= 0 || thumbSize.iHeight <= 0 )
+        {
+        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);
     
-    TSize thumbSize = aThumbnail->SizeInPixels();
     for ( TInt i = iPersistentSizes.Count(); --i >= 0; )
         {
         TThumbnailPersistentSize & persistentSize = iPersistentSizes[i];
         
-        // don't store duplicates or custom/unknown sizes
-        if ( !exists && (aThumbnailSize != ECustomThumbnailSize && 
-                         aThumbnailSize != EUnknownThumbnailSize &&
-                         thumbSize.iWidth > 0 && thumbSize.iHeight > 0 ))
+        // don't store duplicates or zero sizes
+        if ( !exists )
             {
             TInt flags = 0;
             if ( persistentSize.iCrop )
@@ -511,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;
@@ -531,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 );
                 }
@@ -541,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()" );
     
@@ -565,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 );
@@ -588,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 ));
@@ -616,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();
     
@@ -660,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;
@@ -675,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++ )
                 {
@@ -719,6 +901,7 @@
         // all found
         if (missingSizeCount == 0)
             {
+            CleanupStack::PopAndDestroy( path );
             return;
             }
         else if (round == 1)
@@ -728,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.
@@ -946,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 );
     
@@ -961,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 );
@@ -988,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 );
@@ -1006,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 );
@@ -1015,7 +1005,7 @@
                 // Close db to get deletion of thumbnails executed.
                 stmt.Close();
                 CleanupStack::PopAndDestroy( &stmt );
-                DeleteThumbnailsL( aPath );
+                DeleteThumbnailsL( *path );
                 User::Leave( KErrNotFound );
                 }
             else
@@ -1057,7 +1047,8 @@
         
     stmt.Close();
     CleanupStack::PopAndDestroy( &stmt );
-
+    CleanupStack::PopAndDestroy( path );
+    
     User::LeaveIfError( found );
     }
 
@@ -1065,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()
 // ---------------------------------------------------------------------------
@@ -1381,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);
@@ -1410,558 +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();
-
-     //if not found from temp table, look from real table
-     if(rowStatus != KSqlAtRow)
-         {
-         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();
-         }
-     
-     TBool modified = EFalse;
-     
-     if(rowStatus == KSqlAtRow)
-         {
-         TInt64 oldModified = stmt.ColumnInt64( column );
-         
-         if (oldModified < aModified)
-             {
-             TN_DEBUG1( "CThumbnailStore::CheckModifiedL() -- timestamp is newer than original" );
-             modified = ETrue;
-             }
-         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" );
-             }
-         }
-     
-    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()
 // -----------------------------------------------------------------------------
@@ -1981,6 +1354,8 @@
        {  
        stmt.Close();
        CleanupStack::PopAndDestroy( &stmt ); 
+
+       TN_DEBUG1( "CThumbnailStore::CheckImeiL() failed" );
        return KErrNotSupported;
        }
               
@@ -1995,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;  
       }
     }
@@ -2026,6 +1411,7 @@
        {  
        stmt.Close();
        CleanupStack::PopAndDestroy( &stmt ); 
+       TN_DEBUG1( "CThumbnailStore::CheckVersionL() unknown version" );
        return KErrNotSupported;
        }
               
@@ -2040,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;  
@@ -2116,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;
     }
 
 
@@ -2132,7 +1546,7 @@
 // UpdateImeiL()
 // -----------------------------------------------------------------------------
 //
-void CThumbnailStore::UpdateImeiL()
+TInt CThumbnailStore::UpdateImeiL()
     {
     TN_DEBUG1( "CThumbnailStore::UpdateImeiL()" );
     RSqlStatement stmt;
@@ -2147,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;
     }
 
 // -----------------------------------------------------------------------------
@@ -2180,7 +1600,7 @@
         }
     else
         {
-        iAutoFlushTimer->Start( KAutoFlushTimeout, KAutoFlushTimeout, 
+        iAutoFlushTimer->Start( KAutoFlushTimeout * 1000000, KAutoFlushTimeout * 1000000, 
                                 TCallBack(AutoFlushTimerCallBack, this));
         }
     }
@@ -2198,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()
 // ---------------------------------------------------------------------------
@@ -2212,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()");
@@ -2228,6 +1751,7 @@
         {
         stmt.Close();
         CleanupStack::PopAndDestroy( &stmt );
+        TN_DEBUG1( "CThumbnailStore::CheckRowIDs() failed 1 %d");
         return KErrNotSupported;
         }
     rowStatus = stmt.Next();
@@ -2236,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 );
@@ -2246,6 +1779,7 @@
         {
         stmt.Close();
         CleanupStack::PopAndDestroy( &stmt );
+        TN_DEBUG1( "CThumbnailStore::CheckRowIDs() failed 2");
         return KErrNotSupported;
         }
     rowStatus = stmt.Next();
@@ -2257,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)
         {
@@ -2269,111 +1812,326 @@
         }
     }
 
-void CThumbnailStore::CheckModifiedByIdL( TUint32 aId, TBool aTempTable,
-    TBool& aModified )
+TBool CThumbnailStore::CheckModifiedByPathL( const TDesC& aPath, const TInt64 aModified, TBool& modifiedChanged )
     {
-    TN_DEBUG1( "CThumbnailStore::CheckModifiedByIdL()");
+    TN_DEBUG2( "CThumbnailStore::CheckModifiedByPathL() %S", &aPath);
+    
+    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 ));
+    
+   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();
+           }
+       }
+    
+   stmt.Close();
+   CleanupStack::PopAndDestroy( &stmt ); 
+   
+   CleanupStack::PopAndDestroy( path );
+   
+   return ret;
+}
+	
+// -----------------------------------------------------------------------------
+// PrepareBlacklistedItemsForRetryL()
+// -----------------------------------------------------------------------------
+//
+void CThumbnailStore::PrepareBlacklistedItemsForRetryL()
+    {
+    TN_DEBUG1( "CThumbnailStore::PrepareBlacklistedItemsForRetry()" );
     
     RSqlStatement stmt;
     CleanupClosePushL( stmt );
-    TInt column( 0 );
-    
-    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;
-                }
-            }
-        }
+
+    User::LeaveIfError( stmt.Prepare( iDatabase, KThumbnailTouchBlacklistedRows ));
     
-    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 paramIndex = stmt.ParameterIndex( KThumbnailSqlParamFlag );
+    User::LeaveIfError( paramIndex );
+    User::LeaveIfError( stmt.BindInt( paramIndex, KThumbnailDbFlagBlacklisted ));
+    TInt err = stmt.Exec();
+   
+    TN_DEBUG2( "CThumbnailStore::PrepareBlacklistedItemsForRetryL() - main table, err=%d", err );
     
-    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 );
     }
 
 // -----------------------------------------------------------------------------
-// RemoveDbFlagL()
+// DeleteMarkedL()
 // -----------------------------------------------------------------------------
 //
-void CThumbnailStore::RemoveDbFlagL(TThumbnailDbFlags aFlag)
+TInt CThumbnailStore::DeleteMarkedL()
     {
-    TN_DEBUG1( "CThumbnailStore::RemoveBlacklistedFlag()" );
+#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 );
-
-    User::LeaveIfError( stmt.Prepare( iDatabase, KThumbnailRemoveBlacklistedFlag ));
+    
+    // get rows
+    User::LeaveIfError( stmt.Prepare( iDatabase, KThumbnailSelectAllPaths ));
     
-    TInt paramIndex = stmt.ParameterIndex( KThumbnailSqlParamFlag );
+    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, aFlag ));
+    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;
+    }
 
-    TInt err = stmt.Exec();
-   
-    TN_DEBUG2( "CThumbnailStore::RemoveBlacklistedFlag() - main table, err=%d", err );
+// -----------------------------------------------------------------------------
+// StripDriveLetter
+// -----------------------------------------------------------------------------
+//
+void CThumbnailStore::StripDriveLetterL( TDes& aPath )
+    {
+    TInt pos = aPath.Find(KDrv);
     
-    CleanupStack::PopAndDestroy( &stmt );
+    // if URI contains drive letter
+    if ( pos == 1 )
+        {
+        aPath.Delete(0,pos+1);
+        }
     }
 
 void CThumbnailStore::HandleDiskSpaceNotificationL( TBool aDiskFull )
@@ -2382,13 +2140,13 @@
     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()
@@ -2396,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)
     {
@@ -2437,7 +2235,6 @@
     return (TDriveNumber)driveNumber;
     }
 
-
 CThumbnailStoreDiskSpaceNotifierAO::~CThumbnailStoreDiskSpaceNotifierAO()
     {
     TN_DEBUG1( "CThumbnailStoreDiskSpaceNotifierAO::~CThumbnailStoreDiskSpaceNotifierAO()");
@@ -2455,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:
@@ -2509,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;
@@ -2523,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;
@@ -2538,6 +2355,7 @@
 void CThumbnailStoreDiskSpaceNotifierAO::DoCancel()
     {
     TN_DEBUG1( "CThumbnailStoreDiskSpaceNotifierAO::DoCancel()");
+    
     if( IsActive() )
         {   
         iFileServerSession.NotifyDiskSpaceCancel();
@@ -2561,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/thumbnailserver/src/thumbnailtask.cpp	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailtask.cpp	Fri Mar 19 09:35:30 2010 +0200
@@ -51,6 +51,8 @@
     {
     Cancel();
     CancelMessage();
+    
+    iClientThread.Close();
     }
 
 
@@ -225,4 +227,49 @@
         }
     }
 
+// ---------------------------------------------------------------------------
+// CThumbnailTask::ClientThreadAlive()
+// Checks if client thread is still alive and RMessage2 handle valid.
+// ---------------------------------------------------------------------------
+//
+TBool CThumbnailTask::ClientThreadAlive(const TBool aGetThread)
+    {
+    if ( iMessage.Handle())
+        {
+        if (aGetThread)
+            {
+            // get client thread
+            TInt err = iMessage.Client( iClientThread );
+            if (err != KErrNone)
+                {
+                TN_DEBUG2( "CThumbnailTask(0x%08x)::ClientThreadAlive() - client thread not found", this);
+            
+                ResetMessageData();
+                
+                return EFalse;
+                }
+            }
+    
+        // check if client thread alive
+        TExitType exitType = iClientThread.ExitType();
+        if( exitType != EExitPending )
+            {
+            TN_DEBUG2( "CThumbnailTask(0x%08x)::ClientThreadAlive() - client thread died", this);
+        
+            ResetMessageData();
+            
+            return EFalse;
+            }
+        else
+            {
+            // all OK
+            return ETrue;
+            }
+        }
+    else
+        {
+        return EFalse;
+        }
+    }
+
 // End of file
--- a/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailtaskprocessor.cpp	Tue Feb 02 00:23:15 2010 +0200
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailtaskprocessor.cpp	Fri Mar 19 09:35:30 2010 +0200
@@ -330,25 +330,6 @@
     TN_DEBUG2( "CThumbnailTaskProcessor::TASKPROCESSOR-COUNTER---------- in, Tasks = %d", iTasks.Count() );
 #endif
     
-    /* 
-    // remove completed tasks and run priorised task
-    for ( TInt i = 0; i < iTasks.Count(); i++ )
-        {
-        CThumbnailTask* task = iTasks[i];
-        if ( task->State() == CThumbnailTask::EComplete )
-            {
-            // delete completed task
-            delete task;
-            iTasks.Remove( i );
-            
-            // correct the index so that no tasks are skipped
-            i--;
-            if(i <= -1)
-                {
-                i = -1;
-                }
-            }*/
-    
     // remove completed tasks and run priorised task
     for ( TInt i = iTasks.Count(); --i >= 0; )
         {
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/tmgetimei.cpp	Fri Mar 19 09:35:30 2010 +0200
@@ -0,0 +1,73 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "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:  Helper class to get IMEI number.
+*
+*/
+
+
+#include "tmgetimei.h"
+#include "thumbnailmanagerconstants.h"
+
+CTMGetImei* CTMGetImei::NewL()
+    {
+    CTMGetImei *self = CTMGetImei::NewLC();
+    CleanupStack::Pop();
+    return self;
+    }
+
+CTMGetImei* CTMGetImei::NewLC()
+    {
+    CTMGetImei *self = new (ELeave) CTMGetImei();
+    CleanupStack::PushL(self);
+    self->ConstructL();
+    return self;
+    }
+
+void CTMGetImei::ConstructL()
+   {
+   iTelephony = CTelephony::NewL();
+   CActiveScheduler::Add(this);
+   }
+
+CTMGetImei::~CTMGetImei()
+    {
+    Cancel();
+
+    delete iTelephony;
+    }
+
+TBuf<KImeiBufferSize> CTMGetImei::GetIMEI()
+    {    
+    CTelephony::TPhoneIdV1Pckg phoneIdPckg( iV1 );  
+    
+    iTelephony->GetPhoneId( iStatus, phoneIdPckg );
+    SetActive();
+    iAsw.Start();
+    Deque();
+    return iImei;       
+    }
+
+void CTMGetImei::DoCancel()
+    {
+    iTelephony->CancelAsync(CTelephony::EGetPhoneIdCancel);
+    }
+   
+void CTMGetImei::RunL()
+    {
+    if(iStatus == KErrNone)
+        {
+        iImei = iV1.iSerialNumber;
+        }
+    iAsw.AsyncStop();
+    }
--- a/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/tmshutdownobserver.cpp	Tue Feb 02 00:23:15 2010 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,119 +0,0 @@
-/*
-* 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:  Processor 
-*
-*/
-
-
-#include <e32base.h>
-
-#include "tmshutdownobserver.h"
-#include "thumbnailmanagerconstants.h"
-
-// ---------------------------------------------------------------------------
-// CTMShutdownObserver::NewL()
-// ---------------------------------------------------------------------------
-//
-CTMShutdownObserver* CTMShutdownObserver::NewL( MTMShutdownObserver& aObserver,
-                                                const TUid& aKeyCategory,
-                                                const TInt aPropertyKey,
-                                                TBool aDefineKey)
-    { 
-    CTMShutdownObserver* self = new( ELeave )CTMShutdownObserver( aObserver, 
-                                                                  aKeyCategory,
-                                                                  aPropertyKey,
-                                                                  aDefineKey);
-    CleanupStack::PushL( self );
-    self->ConstructL();
-    CleanupStack::Pop( self );
-    return self;
-    }
-
-// ---------------------------------------------------------------------------
-// CTMShutdownObserver::CTMShutdownObserver()
-// ---------------------------------------------------------------------------
-//
-CTMShutdownObserver::CTMShutdownObserver( MTMShutdownObserver& aObserver,
-                                          const TUid& aKeyCategory,
-                                          const TInt aPropertyKey,
-                                          TBool aDefineKey)
-    : CActive( CActive::EPriorityStandard ), iObserver( aObserver ),
-      iKeyCategory( aKeyCategory ), iPropertyKey(aPropertyKey), iDefineKey( aDefineKey )
-    {   
-    CActiveScheduler::Add( this );
-    }
-
-// ---------------------------------------------------------------------------
-// CTMShutdownObserver::ConstructL()
-// ---------------------------------------------------------------------------
-//
-void CTMShutdownObserver::ConstructL()
-    { 
-    // define P&S property types
-    if (iDefineKey)
-        {
-        RProperty::Define(iKeyCategory,iPropertyKey,
-                          RProperty::EInt,KAllowAllPolicy,KPowerMgmtPolicy);
-        }
-    
-    // attach to the property
-    TInt err = iProperty.Attach(iKeyCategory,iPropertyKey,EOwnerThread);
-    User::LeaveIfError(err);
-    
-    // wait for the previously attached property to be updated
-    iProperty.Subscribe(iStatus);
-    SetActive();
-    }
-
-// ---------------------------------------------------------------------------
-// CTMShutdownObserver::~CTMShutdownObserver()
-// ---------------------------------------------------------------------------
-//
-CTMShutdownObserver::~CTMShutdownObserver()
-    {
-    Cancel();
-    iProperty.Close();
-    }
-
-// ---------------------------------------------------------------------------
-// CTMShutdownObserver::RunL()
-// ---------------------------------------------------------------------------
-//
-void CTMShutdownObserver::RunL()
-    {
-    // resubscribe before processing new value to prevent missing updates
-    iProperty.Subscribe(iStatus);
-    SetActive();
-    
-    // retrieve the value
-    TInt value = 0;
-    iProperty.Get(value);
-
-    // observer callback
-    if (value)
-        {
-        iObserver.ShutdownNotification();
-        }
-    }
-
-// ---------------------------------------------------------------------------
-// CTMShutdownObserver::DoCancel()
-// ---------------------------------------------------------------------------
-//
-void CTMShutdownObserver::DoCancel()
-    {
-    iProperty.Cancel();
-    }
-
-// End of file
--- a/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/tnmgetimei.cc	Tue Feb 02 00:23:15 2010 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,75 +0,0 @@
-/*
-* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
-* All rights reserved.
-* This component and the accompanying materials are made available
-* under the terms of "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:  Helper class to get IMEI number.
-*
-*/
-
-
-#include "tnmgetimei.h"
-#include "thumbnailmanagerconstants.h"
-
-CTnmgetimei* CTnmgetimei::NewL()
-    {
-    CTnmgetimei *self = CTnmgetimei::NewLC();
-    CleanupStack::Pop();
-    return self;
-    }
-
-CTnmgetimei* CTnmgetimei::NewLC()
-    {
-    CTnmgetimei *self = new (ELeave) CTnmgetimei();
-    CleanupStack::PushL(self);
-    self->ConstructL();
-    return self;
-    }
-
-void CTnmgetimei::ConstructL()
-   {
-   iTelephony = CTelephony::NewL();
-   CActiveScheduler::Add(this);
-   }
-
-CTnmgetimei::~CTnmgetimei()
-    {
-    Cancel();
-
-    delete iTelephony;
-    }
-
-TBuf<KImeiBufferSize> CTnmgetimei::GetIMEI()
-    {   
-    
-    CTelephony::TPhoneIdV1Pckg phoneIdPckg( iV1 );  
-    
-    iTelephony->GetPhoneId( iStatus, phoneIdPckg );
-    SetActive();
-    iAsw.Start();
-    Deque();
-    return iImei;
-        
-    }
-
-void CTnmgetimei::DoCancel()
-    {
-    iTelephony->CancelAsync(CTelephony::EGetPhoneIdCancel);
-    }
-   
-void CTnmgetimei::RunL()
-    {
-    if(iStatus == KErrNone)
-        {
-        iImei = iV1.iSerialNumber;
-        }
-    iAsw.AsyncStop();
-    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/imagehandlingutilities/thumbnailmanager/tmcommon/inc/tmactivitymanager.h	Fri Mar 19 09:35:30 2010 +0200
@@ -0,0 +1,92 @@
+/*
+* 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:  Activity Manager
+ *
+*/
+
+#include <e32base.h>
+#include <hwrmlight.h>
+
+#ifndef TMACTIVITYMANAGER_H
+#define TMACTIVITYMANAGER_H
+
+
+class MTMActivityManagerObserver
+
+{
+public :
+    virtual void ActivityChanged(const TBool aActive) = 0;
+};
+
+
+class CTMActivityManager : public CActive,
+                           public MHWRMLightObserver
+
+{
+public:
+
+    /**
+     * Two-phased constructor.
+     *
+     * @since S60 v5.0
+     * @return Instance of CThumbAGProcessor.
+     */
+    static CTMActivityManager* NewL(MTMActivityManagerObserver* aObserver, TInt aTimeout = 60);
+
+    /**
+     * Destructor
+     *
+     * @since S60 v5.0
+     */
+    virtual ~CTMActivityManager();
+    void SetTimeout(TInt aTimeout);
+    void Start();
+    void Reset();
+    void Stop();
+    TBool IsInactive();
+
+
+protected: // from CActive
+    void DoCancel();
+    void RunL();
+    TInt RunError(TInt aError);
+
+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 };
+
+protected:
+    RTimer iTimer;
+    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/tmformatobserver.h	Fri Mar 19 09:35:30 2010 +0200
@@ -0,0 +1,104 @@
+/*
+* Copyright (c) 2006 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:  Monitors File system for Format events
+*
+*/
+
+
+#ifndef CTMFORMATOBSERVER_H
+#define CTMFORMATOBSERVER_H
+
+#include <babackup.h>
+#include "f32file.h"
+
+
+/**
+ * Observer interface
+ */
+class MTMFormatObserver
+    {
+public:
+
+    virtual void FormatNotification( TBool aFormat ) = 0;
+    };
+
+/**
+ *  File System monitor class to monitor for format events
+ *
+ *  @lib thumbnailsserver.exe
+ *  @since S60 3.0
+ */
+class CTMFormatObserver: public CBase,
+                         public MBackupOperationObserver
+    {
+
+public:
+
+    /**
+    * Two-phase constructor
+    * @param aObserver observer to the monitor
+    */
+    static CTMFormatObserver* NewL( MTMFormatObserver& aObserver );
+
+    /**
+    * Two-phase constructor
+    * @param aObserver observer to the monitor
+    */
+    static CTMFormatObserver* NewLC( MTMFormatObserver& aObserver );
+
+    /**
+    * Destructor
+    */
+    virtual ~CTMFormatObserver();
+
+public: // New functions
+
+    /**
+    * Polls for the current monitor status
+    * If an event is happening, it will callback the observer of the event
+    */
+    void PollStatus();
+
+protected: // Base Class
+
+    /*
+    * From MBackupOperationObserver
+    * Notifies this class of the backup event.
+    * MMC App will signal a start / end.
+    */
+    void HandleBackupOperationEventL(const TBackupOperationAttributes& aBackupOperationAttributes);
+
+private:
+
+    /**
+    *  C++ constructor
+    *  aObserver observer to this event
+    */
+    CTMFormatObserver ( MTMFormatObserver& aObserver );
+
+    /*
+    * Second phased constructor
+    */
+    void ConstructL();
+
+private: // data
+
+    // not own
+    MTMFormatObserver& iObserver; 
+    
+    CBaBackupSessionWrapper* iBackupSession;
+    
+    };
+
+#endif // CTMFORMATOBSERVER_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/imagehandlingutilities/thumbnailmanager/tmcommon/inc/tmrpropertyobserver.h	Fri Mar 19 09:35:30 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
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/imagehandlingutilities/thumbnailmanager/tmcommon/inc/tmshutdownobserver.h	Fri Mar 19 09:35:30 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 Shutdown Observer
+ *
+*/
+
+
+#ifndef TMSHUTDOWNOBSERVER_H
+#define TMSHUTDOWNOBSERVER_H
+
+#include <e32base.h>
+#include <w32std.h>
+#include <e32property.h> 
+
+
+/**
+ * Observer interface for signaling the need for shutdown
+ */
+class MTMShutdownObserver
+    {
+public:
+
+    virtual void ShutdownNotification() = 0;
+    };
+
+/**
+ *  Active object for observing P&S keys
+ *
+ *  @since S60 v5.0
+ */
+class CTMShutdownObserver: public CActive
+    {
+public:
+
+    /**
+     * Two-phased constructor.
+     *
+     * @since S60 v5.0
+     * @return Instance of CTMShutdownObserver.
+     */
+    static CTMShutdownObserver* NewL( MTMShutdownObserver& aObserver, const TUid& aKeyCategory,
+                                      const TInt aPropertyKey, TBool aDefineKey);
+
+    /**
+     * Destructor
+     *
+     * @since S60 v5.0
+     */
+    virtual ~CTMShutdownObserver();
+    
+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 CTMShutdownObserver.
+     */
+    CTMShutdownObserver( MTMShutdownObserver& aObserver, const TUid& aKeyCategory,
+                         const TInt iPropertyKey, TBool aDefineKey);
+
+    /**
+     * Symbian 2nd phase constructor can leave.
+     *
+     * @since S60 v5.0
+     */
+    void ConstructL();
+
+private:
+    
+    // not own
+    MTMShutdownObserver& iObserver;
+    
+    const TUid& iKeyCategory;
+    RProperty iProperty;
+    TInt iPropertyKey;
+    
+    TBool iDefineKey;
+};
+
+#endif // TMSHUTDOWNOBSERVER_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/imagehandlingutilities/thumbnailmanager/tmcommon/src/tmactivitymanager.cpp	Fri Mar 19 09:35:30 2010 +0200
@@ -0,0 +1,269 @@
+/*
+* 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:  Activity Manager 
+*
+*/
+
+#include "tmactivitymanager.h"
+#include "thumbnaillog.h"
+
+// ---------------------------------------------------------------------------
+// CTMActivityManager::NewL()
+// ---------------------------------------------------------------------------
+//
+CTMActivityManager* CTMActivityManager::NewL(MTMActivityManagerObserver* aObserver, TInt aTimeout)
+    {
+    TN_DEBUG1( "CTMActivityManager::NewL()");
+    CTMActivityManager* self = new (ELeave) CTMActivityManager(aObserver, aTimeout);
+    CleanupStack::PushL(self);
+    self->ConstructL();
+    CleanupStack::Pop(self);
+    return self;
+    }
+ 
+// ---------------------------------------------------------------------------
+// CTMActivityManager::CTMActivityManager()
+// ---------------------------------------------------------------------------
+//
+CTMActivityManager::CTMActivityManager(MTMActivityManagerObserver* aObserver, TInt aTimeout)
+: CActive(CActive::EPriorityHigh), iObserver(aObserver), iTimeout(aTimeout), iPreviousStatus(KErrNotFound)
+    {
+    TN_DEBUG1( "CTMActivityManager::CTMActivityManager()");
+    CActiveScheduler::Add(this);
+    }
+
+// ---------------------------------------------------------------------------
+// CTMActivityManager::~CTMActivityManager()
+// ---------------------------------------------------------------------------
+//
+CTMActivityManager::~CTMActivityManager()
+    {
+    TN_DEBUG1( "CTMActivityManager::~CTMActivityManager()");
+    delete iLight;
+    iLight = NULL;
+    Cancel();
+    iTimer.Close();
+    }
+ 
+// ---------------------------------------------------------------------------
+// CTMActivityManager::ConstructL()
+// ---------------------------------------------------------------------------
+//
+void CTMActivityManager::ConstructL()
+    {
+    TN_DEBUG1( "CTMActivityManager::ConstructL()");
+    iTimer.CreateLocal();
+    }
+
+// ---------------------------------------------------------------------------
+// CTMActivityManager::SetTimeout()
+// ---------------------------------------------------------------------------
+//
+void CTMActivityManager::SetTimeout(TInt aTimeout)
+    {
+    TN_DEBUG1( "CTMActivityManager::SetTimeout()");
+    iTimeout = aTimeout;
+    Reset();
+    }
+
+// ---------------------------------------------------------------------------
+// CTMActivityManager::Reset()
+// ---------------------------------------------------------------------------
+//
+void CTMActivityManager::Reset()
+    {
+    TN_DEBUG1( "CTMActivityManager::Reset()");
+    delete iLight;
+    iLight = NULL;
+    Cancel();
+    Start();
+    }
+ 
+// ---------------------------------------------------------------------------
+// CTMActivityManager::DoCancel()
+// ---------------------------------------------------------------------------
+void CTMActivityManager::DoCancel()
+    {
+    TN_DEBUG1( "CTMActivityManager::DoCancel()");
+    iTimer.Cancel();
+    iWatch = ENone;
+    }
+
+// ---------------------------------------------------------------------------
+// CTMActivityManager::Start()
+// ---------------------------------------------------------------------------
+//
+void CTMActivityManager::Start()
+    {
+    TN_DEBUG1( "CTMActivityManager::Start()");
+    
+    iFirstRound = ETrue;
+    
+    if(!iLight)
+        {
+        TRAP_IGNORE(iLight = CHWRMLight::NewL(this));
+        }
+    
+    if( !IsActive() )
+        {
+        SetActive();
+        TRequestStatus* statusPtr = &iStatus;
+        User::RequestComplete( statusPtr, KErrNone );
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// CTMActivityManager::RunL()
+// ---------------------------------------------------------------------------
+//
+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)
+            {
+            TInt inactivity = User::InactivityTime().Int();
+            if (inactivity >= iTimeout)
+                {
+                TN_DEBUG1( "CTMActivityManager::RunL() inactive");
+                NotifyObserver();
+
+            if (!IsActive()) //observer might have called a Reset()
+                {
+                iTimer.Inactivity(iStatus,0);
+                iWatch = EWaitingForActivity;
+                }
+            }
+            else
+                {
+                iTimer.Inactivity(iStatus,iTimeout);
+                }
+            }
+        else if (iWatch == EWaitingForActivity)
+            {
+                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()
+            {
+            SetActive();
+            }
+        }
+    else
+        {
+        iWatch = ENone;
+        }
+        TN_DEBUG1( "CTMActivityManager::RunL() end");
+    }
+
+// ---------------------------------------------------------------------------
+// CTMActivityManager::RunError()
+// ---------------------------------------------------------------------------
+//
+TInt CTMActivityManager::RunError(TInt aError)
+    {
+    TN_DEBUG2( "CTMActivityManager::RunError() %d", aError);
+    
+    if (aError != KErrNone)
+        {
+        Reset();
+        }
+    
+    // nothing to do
+    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/tmformatobserver.cpp	Fri Mar 19 09:35:30 2010 +0200
@@ -0,0 +1,121 @@
+/*
+* Copyright (c) 2006 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:  File System format monitor
+*
+*/
+
+#include "tmformatobserver.h"
+#include "thumbnaillog.h"
+ 
+#include <e32base.h>
+#include <f32file.h>
+
+
+// ======== MEMBER FUNCTIONS ========
+
+CTMFormatObserver::CTMFormatObserver ( MTMFormatObserver& aObserver ): 
+    iObserver( aObserver )
+    {
+    TN_DEBUG1( "CTMFormatObserver::CTMFormatObserver()");
+    }
+    
+    
+// ---------------------------------------------------------------------------
+// Second Phase Constructor
+// ---------------------------------------------------------------------------
+//
+void CTMFormatObserver::ConstructL()
+    {
+    TN_DEBUG1("CTMFormatObserver::ConstructL");
+
+    iBackupSession = CBaBackupSessionWrapper::NewL();
+    iBackupSession->RegisterBackupOperationObserverL( *this );
+    }
+
+
+// ---------------------------------------------------------------------------
+// Two-Phased Constructor
+// ---------------------------------------------------------------------------
+//
+CTMFormatObserver* CTMFormatObserver::NewL( MTMFormatObserver& aObserver )
+    {
+    CTMFormatObserver* self = CTMFormatObserver::NewLC( aObserver );
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+
+// ---------------------------------------------------------------------------
+// Two-Phased Constructor
+// ---------------------------------------------------------------------------
+//
+CTMFormatObserver* CTMFormatObserver::NewLC( MTMFormatObserver& aObserver )
+    {
+    CTMFormatObserver* self = new( ELeave ) CTMFormatObserver( aObserver );
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    return self;
+    }
+
+
+// ---------------------------------------------------------------------------
+// destructor
+// ---------------------------------------------------------------------------
+//
+CTMFormatObserver::~CTMFormatObserver()
+    {
+    if( iBackupSession )
+        {
+        iBackupSession->DeRegisterBackupOperationObserver( *this );
+        }
+    
+    delete iBackupSession;
+    }
+
+// ---------------------------------------------------------------------------
+// Checks the current status
+// ---------------------------------------------------------------------------
+//
+void CTMFormatObserver::PollStatus()
+    { 
+    TN_DEBUG1("CTMFormatObserver::PollStatus()");
+    
+    TBool formatting = iBackupSession->IsBackupOperationRunning();
+    
+    if( formatting )
+        {     
+        iObserver.FormatNotification(ETrue); 
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// CThumbnailFormatObserver::HandleBackupOperationEventL
+// Handles a format operation
+// ---------------------------------------------------------------------------
+//
+void CTMFormatObserver::HandleBackupOperationEventL(
+                  const TBackupOperationAttributes& aBackupOperationAttributes)
+    {
+    TN_DEBUG1("CTMFormatObserver::HandleBackupOperationEventL");
+
+    if( aBackupOperationAttributes.iOperation == EStart )
+        {
+        iObserver.FormatNotification(ETrue);
+        }
+    else // TOperationType::EEnd or TOperationType::EAbort
+        {
+        iObserver.FormatNotification(EFalse);
+        }
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/imagehandlingutilities/thumbnailmanager/tmcommon/src/tmshutdownobserver.cpp	Fri Mar 19 09:35:30 2010 +0200
@@ -0,0 +1,119 @@
+/*
+* 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:  Processor 
+*
+*/
+
+
+#include <e32base.h>
+
+#include "tmshutdownobserver.h"
+#include "thumbnailmanagerconstants.h"
+
+// ---------------------------------------------------------------------------
+// CTMShutdownObserver::NewL()
+// ---------------------------------------------------------------------------
+//
+CTMShutdownObserver* CTMShutdownObserver::NewL( MTMShutdownObserver& aObserver,
+                                                const TUid& aKeyCategory,
+                                                const TInt aPropertyKey,
+                                                TBool aDefineKey)
+    { 
+    CTMShutdownObserver* self = new( ELeave )CTMShutdownObserver( aObserver, 
+                                                                  aKeyCategory,
+                                                                  aPropertyKey,
+                                                                  aDefineKey);
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// CTMShutdownObserver::CTMShutdownObserver()
+// ---------------------------------------------------------------------------
+//
+CTMShutdownObserver::CTMShutdownObserver( MTMShutdownObserver& aObserver,
+                                          const TUid& aKeyCategory,
+                                          const TInt aPropertyKey,
+                                          TBool aDefineKey)
+    : CActive( CActive::EPriorityStandard ), iObserver( aObserver ),
+      iKeyCategory( aKeyCategory ), iPropertyKey(aPropertyKey), iDefineKey( aDefineKey )
+    {   
+    CActiveScheduler::Add( this );
+    }
+
+// ---------------------------------------------------------------------------
+// CTMShutdownObserver::ConstructL()
+// ---------------------------------------------------------------------------
+//
+void CTMShutdownObserver::ConstructL()
+    { 
+    // define P&S property types
+    if (iDefineKey)
+        {
+        RProperty::Define(iKeyCategory,iPropertyKey,
+                          RProperty::EInt,KAllowAllPolicy,KPowerMgmtPolicy);
+        }
+    
+    // attach to the property
+    TInt err = iProperty.Attach(iKeyCategory,iPropertyKey,EOwnerThread);
+    User::LeaveIfError(err);
+    
+    // wait for the previously attached property to be updated
+    iProperty.Subscribe(iStatus);
+    SetActive();
+    }
+
+// ---------------------------------------------------------------------------
+// CTMShutdownObserver::~CTMShutdownObserver()
+// ---------------------------------------------------------------------------
+//
+CTMShutdownObserver::~CTMShutdownObserver()
+    {
+    Cancel();
+    iProperty.Close();
+    }
+
+// ---------------------------------------------------------------------------
+// CTMShutdownObserver::RunL()
+// ---------------------------------------------------------------------------
+//
+void CTMShutdownObserver::RunL()
+    {
+    // resubscribe before processing new value to prevent missing updates
+    iProperty.Subscribe(iStatus);
+    SetActive();
+    
+    // retrieve the value
+    TInt value = 0;
+    iProperty.Get(value);
+
+    // observer callback
+    if (value)
+        {
+        iObserver.ShutdownNotification();
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// CTMShutdownObserver::DoCancel()
+// ---------------------------------------------------------------------------
+//
+void CTMShutdownObserver::DoCancel()
+    {
+    iProperty.Cancel();
+    }
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/imagehandlingutilities/thumbnailmanager/tmcommon/src/tmsrproptertyobserver.cpp	Fri Mar 19 09:35:30 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
--- a/layers.sysdef.xml	Tue Feb 02 00:23:15 2010 +0200
+++ b/layers.sysdef.xml	Fri Mar 19 09:35:30 2010 +0200
@@ -1,13 +1,14 @@
 <?xml version="1.0"?>
-<!DOCTYPE SystemDefinition SYSTEM "sysdef_1_4_0.dtd" [
+<!DOCTYPE SystemDefinition SYSTEM "sysdef_1_5_1.dtd" [
   <!ENTITY layer_real_source_path "sf/mw/imghandling" >
 ]>
 
-<SystemDefinition name="imghandling" schema="1.4.0">
+<SystemDefinition name="imghandling" schema="1.5.1">
   <systemModel>
     <layer name="mw_layer">
       <module name="imghandling">
         <unit unitID="imm.imghandling" mrp="" bldFile="&layer_real_source_path;/group" name="imghandling" />
+        <unit unitID="imm.thumbnailmanagerqt" name="thumbnailmanagerqt" bldFile="&layer_real_source_path;/imagehandlingutilities/thumbnailmanager/thumbnailmanagerqt" proFile="thumbnailmanagerqt.pro" qmakeArgs="-r" mrp=""/>
       </module>
     </layer>
 
--- a/sysdef_1_4_0.dtd	Tue Feb 02 00:23:15 2010 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,86 +0,0 @@
- <!ELEMENT SystemDefinition (systemModel?, build?)>
- <!ATTLIST SystemDefinition
-  name CDATA #REQUIRED
-  schema CDATA #REQUIRED>
- <!ELEMENT systemModel (layer+)>
- <!ELEMENT layer (logicalset* | module*)*>
- <!ATTLIST layer
-  name CDATA #REQUIRED
-  levels CDATA #IMPLIED
-  span CDATA #IMPLIED>
- <!ELEMENT logicalset (logicalsubset* | module* | unit* | package* | prebuilt*)*>
- <!ATTLIST logicalset name CDATA #REQUIRED>
- <!ELEMENT logicalsubset (module* | unit* | package* | prebuilt*)*>
- <!ATTLIST logicalsubset name CDATA #REQUIRED>
- <!ELEMENT module (component* | unit* | package* | prebuilt*)*>
- <!ATTLIST module
-  name CDATA #REQUIRED
-  level CDATA #IMPLIED>
- <!ELEMENT component (unit* | package* | prebuilt*)*>
- <!ATTLIST component name CDATA #REQUIRED>
- <!ELEMENT unit EMPTY>
- <!ATTLIST unit
-  unitID ID #REQUIRED
-  name CDATA #REQUIRED
-  mrp CDATA #REQUIRED
-  filter CDATA #IMPLIED
-  bldFile CDATA #REQUIRED
-  priority CDATA #IMPLIED
-  contract CDATA #IMPLIED>
- <!ELEMENT package EMPTY>
- <!ATTLIST package
-  name CDATA #REQUIRED
-  mrp CDATA #REQUIRED
-  filter CDATA #IMPLIED
-  contract CDATA #IMPLIED>
- <!ELEMENT prebuilt EMPTY>
- <!ATTLIST prebuilt
-  name CDATA #REQUIRED
-  version CDATA #REQUIRED
-  late (Y|N) #IMPLIED
-  filter CDATA #IMPLIED
-  contract CDATA #IMPLIED>
- <!ELEMENT build (option* | target+ | targetList+ | unitList+ | configuration+)*>
- <!ELEMENT unitList (unitRef+)>
- <!ATTLIST unitList
-  name ID #REQUIRED
-  description CDATA #REQUIRED>
- <!ELEMENT unitRef EMPTY>
- <!ATTLIST unitRef unit IDREF #REQUIRED>
- <!ELEMENT targetList EMPTY>
- <!ATTLIST targetList
-  name ID #REQUIRED
-  description CDATA #REQUIRED
-  target IDREFS #REQUIRED>
- <!ELEMENT target EMPTY>
- <!ATTLIST target
-  name ID #REQUIRED
-  abldTarget CDATA #REQUIRED
-  description CDATA #REQUIRED>
- <!ELEMENT option EMPTY>
- <!ATTLIST option
-  name ID #REQUIRED
-  abldOption CDATA #REQUIRED
-  description CDATA #REQUIRED
-  enable (Y | N | y | n) #REQUIRED>
- <!ELEMENT configuration (unitListRef+ | layerRef+ | task+)*>
- <!ATTLIST configuration
-  name ID #REQUIRED
-  description CDATA #REQUIRED
-  filter CDATA #REQUIRED>
- <!ELEMENT task ( unitListRef* , (buildLayer | specialInstructions))>
- <!ELEMENT unitListRef EMPTY>
- <!ATTLIST unitListRef unitList IDREF #REQUIRED>
- <!ELEMENT layerRef EMPTY>
- <!ATTLIST layerRef layerName CDATA #REQUIRED>
- <!ELEMENT buildLayer EMPTY>
- <!ATTLIST buildLayer
-  command CDATA #REQUIRED
-  targetList IDREFS #IMPLIED
-  unitParallel (Y | N | y | n) #REQUIRED
-  targetParallel (Y | N | y | n) #IMPLIED>
- <!ELEMENT specialInstructions EMPTY>
- <!ATTLIST specialInstructions
-  name CDATA #REQUIRED
-  cwd CDATA #REQUIRED
-  command CDATA #REQUIRED>  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/sysdef_1_5_1.dtd	Fri Mar 19 09:35:30 2010 +0200
@@ -0,0 +1,88 @@
+ <!ELEMENT SystemDefinition (systemModel?, build?)>
+ <!ATTLIST SystemDefinition
+  name CDATA #REQUIRED
+  schema CDATA #REQUIRED>
+ <!ELEMENT systemModel (layer+)>
+ <!ELEMENT layer (logicalset* | module*)*>
+ <!ATTLIST layer
+  name CDATA #REQUIRED
+  levels CDATA #IMPLIED
+  span CDATA #IMPLIED>
+ <!ELEMENT logicalset (logicalsubset* | module* | unit* | package* | prebuilt*)*>
+ <!ATTLIST logicalset name CDATA #REQUIRED>
+ <!ELEMENT logicalsubset (module* | unit* | package* | prebuilt*)*>
+ <!ATTLIST logicalsubset name CDATA #REQUIRED>
+ <!ELEMENT module (component* | unit* | package* | prebuilt*)*>
+ <!ATTLIST module
+  name CDATA #REQUIRED
+  level CDATA #IMPLIED>
+ <!ELEMENT component (unit* | package* | prebuilt*)*>
+ <!ATTLIST component name CDATA #REQUIRED>
+ <!ELEMENT unit EMPTY>
+ <!ATTLIST unit
+  unitID ID #REQUIRED
+  name CDATA #REQUIRED
+  mrp CDATA #REQUIRED
+  filter CDATA #IMPLIED
+  bldFile CDATA #REQUIRED
+  priority CDATA #IMPLIED
+  contract CDATA #IMPLIED
+  proFile CDATA #IMPLIED
+  qmakeArgs CDATA #IMPLIED>
+ <!ELEMENT package EMPTY>
+ <!ATTLIST package
+  name CDATA #REQUIRED
+  mrp CDATA #REQUIRED
+  filter CDATA #IMPLIED
+  contract CDATA #IMPLIED>
+ <!ELEMENT prebuilt EMPTY>
+ <!ATTLIST prebuilt
+  name CDATA #REQUIRED
+  version CDATA #REQUIRED
+  late (Y|N) #IMPLIED
+  filter CDATA #IMPLIED
+  contract CDATA #IMPLIED>
+ <!ELEMENT build (option* | target+ | targetList+ | unitList+ | configuration+)*>
+ <!ELEMENT unitList (unitRef+)>
+ <!ATTLIST unitList
+  name ID #REQUIRED
+  description CDATA #REQUIRED>
+ <!ELEMENT unitRef EMPTY>
+ <!ATTLIST unitRef unit IDREF #REQUIRED>
+ <!ELEMENT targetList EMPTY>
+ <!ATTLIST targetList
+  name ID #REQUIRED
+  description CDATA #REQUIRED
+  target IDREFS #REQUIRED>
+ <!ELEMENT target EMPTY>
+ <!ATTLIST target
+  name ID #REQUIRED
+  abldTarget CDATA #REQUIRED
+  description CDATA #REQUIRED>
+ <!ELEMENT option EMPTY>
+ <!ATTLIST option
+  name ID #REQUIRED
+  abldOption CDATA #REQUIRED
+  description CDATA #REQUIRED
+  enable (Y | N | y | n) #REQUIRED>
+ <!ELEMENT configuration (unitListRef+ | layerRef+ | task+)*>
+ <!ATTLIST configuration
+  name ID #REQUIRED
+  description CDATA #REQUIRED
+  filter CDATA #REQUIRED>
+ <!ELEMENT task ( unitListRef* , (buildLayer | specialInstructions))>
+ <!ELEMENT unitListRef EMPTY>
+ <!ATTLIST unitListRef unitList IDREF #REQUIRED>
+ <!ELEMENT layerRef EMPTY>
+ <!ATTLIST layerRef layerName CDATA #REQUIRED>
+ <!ELEMENT buildLayer EMPTY>
+ <!ATTLIST buildLayer
+  command CDATA #REQUIRED
+  targetList IDREFS #IMPLIED
+  unitParallel (Y | N | y | n) #REQUIRED
+  targetParallel (Y | N | y | n) #IMPLIED>
+ <!ELEMENT specialInstructions EMPTY>
+ <!ATTLIST specialInstructions
+  name CDATA #REQUIRED
+  cwd CDATA #REQUIRED
+  command CDATA #REQUIRED>