Revision: 201023
authorDremov Kirill (Nokia-D-MSW/Tampere) <kirill.dremov@nokia.com>
Wed, 23 Jun 2010 18:33:48 +0300
changeset 29 4bdfb6b5c9b4
parent 25 cb86b71cae0a
child 30 b67379558a75
Revision: 201023 Kit: 2010125
imagehandlinglib/Group/IHL.mmp
imagehandlingutilities/thumbnailmanager/conf/102830B0.txt
imagehandlingutilities/thumbnailmanager/conf/thumbnailmanager.confml
imagehandlingutilities/thumbnailmanager/inc/thumbnailmanagerconstants.h
imagehandlingutilities/thumbnailmanager/plugins/audio/src/thumbnailaudioprovider.cpp
imagehandlingutilities/thumbnailmanager/plugins/audio/src/thumbnailimagedecoderv3.cpp
imagehandlingutilities/thumbnailmanager/thumbagdaemon/group/thumbagdaemon.mmp
imagehandlingutilities/thumbnailmanager/thumbagdaemon/inc/thumbagaudioobserver.h
imagehandlingutilities/thumbnailmanager/thumbagdaemon/inc/thumbagcameraobserver.h
imagehandlingutilities/thumbnailmanager/thumbagdaemon/inc/thumbagdaemon.h
imagehandlingutilities/thumbnailmanager/thumbagdaemon/inc/thumbagimageobserver.h
imagehandlingutilities/thumbnailmanager/thumbagdaemon/inc/thumbagprocessor.h
imagehandlingutilities/thumbnailmanager/thumbagdaemon/inc/thumbagvideoobserver.h
imagehandlingutilities/thumbnailmanager/thumbagdaemon/src/thumbagaudioobserver.cpp
imagehandlingutilities/thumbnailmanager/thumbagdaemon/src/thumbagcameraobserver.cpp
imagehandlingutilities/thumbnailmanager/thumbagdaemon/src/thumbagdaemon.cpp
imagehandlingutilities/thumbnailmanager/thumbagdaemon/src/thumbagimageobserver.cpp
imagehandlingutilities/thumbnailmanager/thumbagdaemon/src/thumbagprocessor.cpp
imagehandlingutilities/thumbnailmanager/thumbagdaemon/src/thumbagvideoobserver.cpp
imagehandlingutilities/thumbnailmanager/thumbnailclient/inc/thumbnailrequestactive.h
imagehandlingutilities/thumbnailmanager/thumbnailclient/src/thumbnailmanagerimpl.cpp
imagehandlingutilities/thumbnailmanager/thumbnailclient/src/thumbnailrequestactive.cpp
imagehandlingutilities/thumbnailmanager/thumbnailclient/src/thumbnailsession.cpp
imagehandlingutilities/thumbnailmanager/thumbnailserver/group/thumbnailserver.mmp
imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/thumbnailserver.h
imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailfetchedchecker.cpp
imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailscaletask.cpp
imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailserver.cpp
imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailserversession.cpp
imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailstore.cpp
imagehandlingutilities/thumbnailmanager/tmcommon/src/tmactivitymanager.cpp
imagehandlingutilities/thumbnailmanager/tmcommon/src/tmformatobserver.cpp
imagehandlingutilities/thumbnailmanager/tmcommon/src/tmshutdownobserver.cpp
imagehandlingutilities/thumbnailmanager/tmiadrestart/src/tmiadrestart.cpp
--- a/imagehandlinglib/Group/IHL.mmp	Fri Jun 11 13:58:45 2010 +0300
+++ b/imagehandlinglib/Group/IHL.mmp	Wed Jun 23 18:33:48 2010 +0300
@@ -49,7 +49,7 @@
 
 // Default system include paths for middleware layer modules.
 MW_LAYER_SYSTEMINCLUDE
-SYSTEMINCLUDE   /epoc32/include/icl // Needs to be removed after ICL has made SF structural changes.
+SYSTEMINCLUDE   /epoc32/include/icl 
 
 
 LIBRARY			euser.lib
Binary file imagehandlingutilities/thumbnailmanager/conf/102830B0.txt has changed
Binary file imagehandlingutilities/thumbnailmanager/conf/thumbnailmanager.confml has changed
--- a/imagehandlingutilities/thumbnailmanager/inc/thumbnailmanagerconstants.h	Fri Jun 11 13:58:45 2010 +0300
+++ b/imagehandlingutilities/thumbnailmanager/inc/thumbnailmanagerconstants.h	Wed Jun 23 18:33:48 2010 +0300
@@ -22,7 +22,7 @@
 #include <e32base.h>
 #include <gdi.h>
 #include <etel3rdparty.h>
-
+#include <mdccommon.h>
 #include <apmstd.h>
 
 #include "thumbnailmanager.h" // TThumbnailFlags
@@ -64,15 +64,22 @@
 //how many items daemon will query at once from MDS
 const TUint KMaxQueryItems = 100;
 // max items for PH & AllItems query
-const TUint KMaxQueryItems2 = 100;
+const TUint KMaxQueryBatchSize = 100;
 
 // maximum number of active client side queue requests
 const TUint KMaxClientRequests = 2;
 
+#ifdef __RETRY_ON_SERVERCRASH
+// maximum number of request retry
+const TUint KMaxRequestRetryCount = 2;
+#endif
+
 // maximum number of active daemon requests
 const TUint KMaxDaemonRequests = 2;
 
-const TUint KMdEReconnect = 100000; //100 ms
+const TUint KMdEReconnect = 1*1000*1000; //1 second
+
+const TUint KUnmountTimerTimeout = 5*1000*1000; //5 seconds
 
 const TUint KClientRequestTimeout = 60000000; //60 sec
 const TUint KClientRequestStartErrorTimeout = 100000; //100 ms
@@ -83,9 +90,12 @@
 
 const TInt KThumbnailErrThumbnailNotFound = -62000;
 
-//give MDS 1000 msec time to settle before starting generating TNs
+//give MDS some to settle before starting generating TNs
 const TInt KHarvestingCompleteTimeout = 10000000; //10 sec
 
+//after MMC mount wait while before count is calculated
+const TInt KMountTimeout = 5*1000*1000; //5 sec
+
 const TInt KPSKeyTimeout = 10000000; //10 sec
 //Store's auto flush timeout
 const TInt KAutoFlushTimeout = 65; //65 sec
@@ -487,75 +497,6 @@
     EThumbnailFormatJpeg
     };
 
-struct TThumbnailDatabaseData
-    {
-public:
-    /**
-    * Full path to object to which the imported thumb is to be linked.
-    */
-    TPath iPath;
-    /**
-    * Thumbnail ID
-    */      
-    TInt iTnId;
-    /**
-    * Requested thumbnail size new requests.
-    */
-    TInt iSize;
-    /**
-    * type of data
-    */ 
-    TInt iFormat;
-    /**
-    * Path for the thumbnails
-    */  
-    TPath iTnPath;
-    /**
-    * Data if bitmap
-    */  
-    CFbsBitmap* iBlob;
-    /**
-    * Data if jpeg
-    */
-    TDesC8* iData;
-   /**
-    * Width of thumbnail
-    */  
-    TInt iWidth;
-    /**
-    * Height of thumbnail
-    */  
-    TInt iHeight;
-    /**
-    * Original width of thumbnail
-    */  
-    TInt iOrigWidth;
-    /**
-    * Original height of thumbnail
-    */  
-    TInt iOrigHeight;
-    /**
-    * flags
-    */  
-    TInt iFlags;
-    /**
-    * videoposition
-    */
-    TInt iVideoPosition;
-    /**
-    * thumb oritentation
-    */  
-    TInt iOrientation;
-    /**
-    * Thumb created from associated path
-    */  
-    TInt iThumbFromPath;
-    /**
-    * last modified
-    */
-    TInt64 iModified;
-    
-    };
 
 /**
  *  MDS query modes used during thumbnail generation
--- a/imagehandlingutilities/thumbnailmanager/plugins/audio/src/thumbnailaudioprovider.cpp	Fri Jun 11 13:58:45 2010 +0300
+++ b/imagehandlingutilities/thumbnailmanager/plugins/audio/src/thumbnailaudioprovider.cpp	Wed Jun 23 18:33:48 2010 +0300
@@ -95,6 +95,8 @@
     TPtrC8 ptr = metaCont.Field8( EMetaDataJpeg );
     HBufC8* data = ptr.AllocL();
     
+    CleanupStack::PopAndDestroy(&wantedFields);
+    CleanupStack::PopAndDestroy(metaDataUtil);
     CleanupStack::PushL( data );
     
     if(data->Length() == 0)
@@ -111,12 +113,18 @@
     iFlags = aFlags;
 	//set default mode displaymode from global constants
     iDisplayMode = KStoreDisplayMode;
-    
-    iImageDecoderv3->CreateL( data, *iObserver, iFlags, iMimeType, iTargetSize );
-    
-    CleanupStack::Pop( data );
-    CleanupStack::PopAndDestroy(&wantedFields);
-    CleanupStack::PopAndDestroy(metaDataUtil);
+    TRAPD( err, iImageDecoderv3->CreateL( data, *iObserver, iFlags, iMimeType, iTargetSize ) );
+    if (err == KErrNone)
+        {
+        CleanupStack::Pop( data );
+        }
+    else
+        {
+        // this is because data buffer is already released in CreateDecoderL
+        // and we must prevent automatic PopAndDestroy
+        CleanupStack::Pop( data );
+        User::Leave(err);
+        } 
     
     iOriginalSize = iImageDecoderv3->OriginalSize();
     iImageDecoderv3->DecodeL( iDisplayMode );
--- a/imagehandlingutilities/thumbnailmanager/plugins/audio/src/thumbnailimagedecoderv3.cpp	Fri Jun 11 13:58:45 2010 +0300
+++ b/imagehandlingutilities/thumbnailmanager/plugins/audio/src/thumbnailimagedecoderv3.cpp	Wed Jun 23 18:33:48 2010 +0300
@@ -137,8 +137,7 @@
     TInt err = iBitmap->Create( loadSize, aDisplayMode );
     if (err != KErrNone)
         {
-        delete iBitmap;
-        iBitmap = NULL;
+        Release();
         User::Leave(err);
         }
     
@@ -240,9 +239,7 @@
             TRAPD( decErr, iDecoder = CImageDecoder::DataNewL( iFs, *iBuffer, options ) );
             if ( decErr != KErrNone )
                 {
-                delete iBuffer;
-                iBuffer = NULL;
-                
+                Release();
                 TN_DEBUG2( "CThumbnailImageDecoderv3::CreateDecoderL() - CImageDecoder error %d", decErr );
                 
                 User::Leave( decErr );
@@ -282,6 +279,7 @@
     //no sense to try other codecs if image is corrupted
     if( aError == KErrCorrupt || aError == KErrUnderflow)
         {
+        Release();
         User::Leave( aError );
         }
     }
--- a/imagehandlingutilities/thumbnailmanager/thumbagdaemon/group/thumbagdaemon.mmp	Fri Jun 11 13:58:45 2010 +0300
+++ b/imagehandlingutilities/thumbnailmanager/thumbagdaemon/group/thumbagdaemon.mmp	Wed Jun 23 18:33:48 2010 +0300
@@ -49,6 +49,12 @@
 SOURCE			tmformatobserver.cpp 
 SOURCE			tmsrproptertyobserver.cpp
 
+SOURCEPATH              ../src
+SOURCE 			thumbagimageobserver.cpp 
+SOURCE			thumbagcameraobserver.cpp
+SOURCE			thumbagaudioobserver.cpp 
+SOURCE			thumbagvideoobserver.cpp
+
 // Default system include paths for middleware layer modules.
 MW_LAYER_SYSTEMINCLUDE
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/imagehandlingutilities/thumbnailmanager/thumbagdaemon/inc/thumbagaudioobserver.h	Wed Jun 23 18:33:48 2010 +0300
@@ -0,0 +1,148 @@
+/*
+* 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:  Thumbnail Auto Generate Daemon
+ *
+*/
+
+
+#ifndef THUMBAGAUDIOOBSERVER_H
+#define THUMBAGAUDIOOBSERVER_H
+
+#include <e32base.h>
+#include <w32std.h>
+
+#include <mdesession.h>
+
+#include "thumbagprocessor.h"
+#include "tmshutdownobserver.h"
+#include "thumbnaillog.h"
+
+
+/**
+ *  ThumbAG daemon.
+ *
+ *  @since S60 v5.0
+ */
+NONSHARABLE_CLASS( CThumbAGAudioObserver ): public CBase, 
+                                     public MMdESessionObserver,
+                                     public MMdEObjectObserver,
+                                     public MTMShutdownObserver
+    {
+public:
+
+    /**
+     * Two-phased constructor
+     *
+     * @since S60 v5.0
+     * @return New CThumbAGAudioObserver server.
+     */
+    static CThumbAGAudioObserver* NewLC(CThumbAGProcessor* aProcessor);
+
+    /**
+     * Two-phased constructor
+     *
+     * @since S60 v5.0
+     * @return New CThumbAGAudioObserver server.
+     */
+    static CThumbAGAudioObserver* NewL(CThumbAGProcessor* aProcessor);
+    
+    /**
+     * Destructor
+     *
+     * @since S60 v5.0
+     */
+    virtual ~CThumbAGAudioObserver();
+
+
+public:
+    
+    // from MMdESessionObserver
+    void HandleSessionOpened( CMdESession& aSession, TInt aError );
+    void HandleSessionError( CMdESession& aSession, TInt aError );
+    
+    // from MMdEObjectObserver
+    void HandleObjectNotification(CMdESession& aSession, 
+                                  TObserverNotificationType aType,
+                                  const RArray<TItemId>& aObjectIdArray);
+        
+    // from MTMShutdownObserver
+    void ShutdownNotification();
+    
+protected:
+    
+    /**
+     * AddObserversL
+     *
+     * @since S60 v5.0
+     */
+    void AddObserversL();    
+    
+    
+private:
+
+    /**
+     * C++ default constructor
+     *
+     * @since S60 v5.0
+     * @return New CThumbAGAudioObserver instance.
+     */
+    CThumbAGAudioObserver(CThumbAGProcessor* aProcessor);
+
+    /**
+     * Symbian 2nd phase constructor can leave.
+     *
+     * @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);
+    
+    void Shutdown();
+
+private:
+	
+    // own
+    CTMShutdownObserver* iShutdownObserver;
+    CTMShutdownObserver* iMDSShutdownObserver;
+    CMdESession* iMdESession;
+    
+    //not owned
+    CThumbAGProcessor* iProcessor;
+    
+    TBool iShutdown;
+ 
+    // reconnect timer
+    CPeriodic* iReconnect;
+    
+    TBool iSessionError;
+    
+#ifdef _DEBUG
+    TUint32 iAddCounter;
+    TUint32 iModCounter;
+#endif
+};
+
+#endif // THUMBAGDAEMON_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/imagehandlingutilities/thumbnailmanager/thumbagdaemon/inc/thumbagcameraobserver.h	Wed Jun 23 18:33:48 2010 +0300
@@ -0,0 +1,145 @@
+/*
+* 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:  Thumbnail Auto Generate Daemon
+ *
+*/
+
+
+#ifndef THUMBAGCAMERAOBSERVER_H
+#define THUMBAGCAMERAOBSERVER_H
+
+#include <e32base.h>
+#include <w32std.h>
+
+#include <mdesession.h>
+
+#include "thumbagprocessor.h"
+#include "tmshutdownobserver.h"
+#include "thumbnaillog.h"
+
+
+/**
+ *  ThumbAG daemon.
+ *
+ *  @since S60 v5.0
+ */
+NONSHARABLE_CLASS( CThumbAGCameraObserver ): public CBase, 
+                                     public MMdESessionObserver,
+                                     public MMdEObjectObserver,
+                                     public MTMShutdownObserver
+    {
+public:
+
+    /**
+     * Two-phased constructor
+     *
+     * @since S60 v5.0
+     * @return New CThumbAGCameraObserver server.
+     */
+    static CThumbAGCameraObserver* NewLC(CThumbAGProcessor* aProcessor);
+
+    /**
+     * Two-phased constructor
+     *
+     * @since S60 v5.0
+     * @return New CThumbAGCameraObserver server.
+     */
+    static CThumbAGCameraObserver* NewL(CThumbAGProcessor* aProcessor);
+    
+    /**
+     * Destructor
+     *
+     * @since S60 v5.0
+     */
+    virtual ~CThumbAGCameraObserver();
+
+
+public:
+    
+    // from MMdESessionObserver
+    void HandleSessionOpened( CMdESession& aSession, TInt aError );
+    void HandleSessionError( CMdESession& aSession, TInt aError );
+    
+    // from MMdEObjectObserver
+    void HandleObjectNotification(CMdESession& aSession, 
+                                  TObserverNotificationType aType,
+                                  const RArray<TItemId>& aObjectIdArray);
+        
+    // from MTMShutdownObserver
+    void ShutdownNotification();
+    
+protected:
+    
+    /**
+     * AddObserversL
+     *
+     * @since S60 v5.0
+     */
+    void AddObserversL();    
+    
+    
+private:
+
+    /**
+     * C++ default constructor
+     *
+     * @since S60 v5.0
+     * @return New CThumbAGCameraObserver instance.
+     */
+    CThumbAGCameraObserver(CThumbAGProcessor* aProcessor);
+
+    /**
+     * Symbian 2nd phase constructor can leave.
+     *
+     * @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:
+	
+    // own
+    CTMShutdownObserver* iShutdownObserver;
+    CTMShutdownObserver* iMDSShutdownObserver;
+    CMdESession* iMdESession;
+    //not owned
+    CThumbAGProcessor* iProcessor;
+    
+    TBool iShutdown;
+ 
+    // reconnect timer
+    CPeriodic* iReconnect;
+    
+    TBool iSessionError;
+    
+#ifdef _DEBUG
+    TUint32 iAddCounter;
+    TUint32 iModCounter;
+#endif
+};
+
+#endif // THUMBAGDAEMON_H
--- a/imagehandlingutilities/thumbnailmanager/thumbagdaemon/inc/thumbagdaemon.h	Fri Jun 11 13:58:45 2010 +0300
+++ b/imagehandlingutilities/thumbnailmanager/thumbagdaemon/inc/thumbagdaemon.h	Wed Jun 23 18:33:48 2010 +0300
@@ -27,6 +27,10 @@
 #include "thumbagprocessor.h"
 #include "tmshutdownobserver.h"
 #include "thumbnaillog.h"
+#include "thumbagimageobserver.h"
+#include "thumbagcameraobserver.h"
+#include "thumbagaudioobserver.h"
+#include "thumbagvideoobserver.h"
 
 
 /**
@@ -177,9 +181,14 @@
     
 #ifdef _DEBUG
     TUint32 iAddCounter;
-    TUint32 iModCounter;
     TUint32 iDelCounter;
 #endif
+    
+    //observers
+    CThumbAGImageObserver* iImageObserver;
+    CThumbAGCameraObserver* iCameraObserver;
+    CThumbAGAudioObserver* iAudioObserver;
+    CThumbAGVideoObserver* iVideoObserver;
 };
 
 #endif // THUMBAGDAEMON_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/imagehandlingutilities/thumbnailmanager/thumbagdaemon/inc/thumbagimageobserver.h	Wed Jun 23 18:33:48 2010 +0300
@@ -0,0 +1,144 @@
+/*
+* 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:  Thumbnail Auto Generate Daemon
+ *
+*/
+
+
+#ifndef THUMBAGIMAGEOBSERVER_H
+#define THUMBAGIMAGEOBSERVER_H
+
+#include <e32base.h>
+#include <w32std.h>
+
+#include <mdesession.h>
+
+#include "thumbagprocessor.h"
+#include "thumbnaillog.h"
+#include "tmshutdownobserver.h"
+
+/**
+ *  ThumbAG daemon.
+ *
+ *  @since S60 v5.0
+ */
+NONSHARABLE_CLASS( CThumbAGImageObserver ): public CBase, 
+                                     public MMdESessionObserver,
+                                     public MMdEObjectObserver,
+                                     public MTMShutdownObserver
+    {
+public:
+
+    /**
+     * Two-phased constructor
+     *
+     * @since S60 v5.0
+     * @return New CThumbAGImageObserver server.
+     */
+    static CThumbAGImageObserver* NewLC(CThumbAGProcessor* aProcessor);
+
+    /**
+     * Two-phased constructor
+     *
+     * @since S60 v5.0
+     * @return New CThumbAGImageObserver server.
+     */
+    static CThumbAGImageObserver* NewL(CThumbAGProcessor* aProcessor);
+    
+    /**
+     * Destructor
+     *
+     * @since S60 v5.0
+     */
+    virtual ~CThumbAGImageObserver();
+
+
+public:
+    
+    // from MMdESessionObserver
+    void HandleSessionOpened( CMdESession& aSession, TInt aError );
+    void HandleSessionError( CMdESession& aSession, TInt aError );
+    
+    // from MMdEObjectObserver
+    void HandleObjectNotification(CMdESession& aSession, 
+                                  TObserverNotificationType aType,
+                                  const RArray<TItemId>& aObjectIdArray);
+    
+    // from MTMShutdownObserver
+    void ShutdownNotification();
+    
+protected:
+    
+    /**
+     * AddObserversL
+     *
+     * @since S60 v5.0
+     */
+    void AddObserversL();    
+    
+    
+private:
+
+    /**
+     * C++ default constructor
+     *
+     * @since S60 v5.0
+     * @return New CThumbAGImageObserver instance.
+     */
+    CThumbAGImageObserver(CThumbAGProcessor* aProcessor);
+
+    /**
+     * Symbian 2nd phase constructor can leave.
+     *
+     * @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:
+	
+    // own
+    CTMShutdownObserver* iShutdownObserver;
+    CTMShutdownObserver* iMDSShutdownObserver;
+    CMdESession* iMdESession;
+    //not owned
+    CThumbAGProcessor* iProcessor;
+    
+    TBool iShutdown;
+ 
+    // reconnect timer
+    CPeriodic* iReconnect;
+    
+    TBool iSessionError;
+    
+#ifdef _DEBUG
+    TUint32 iAddCounter;
+    TUint32 iModCounter;
+#endif
+};
+
+#endif // THUMBAGDAEMON_H
--- a/imagehandlingutilities/thumbnailmanager/thumbagdaemon/inc/thumbagprocessor.h	Fri Jun 11 13:58:45 2010 +0300
+++ b/imagehandlingutilities/thumbnailmanager/thumbagdaemon/inc/thumbagprocessor.h	Wed Jun 23 18:33:48 2010 +0300
@@ -32,10 +32,46 @@
 #include "tmactivitymanager.h"
 #include "tmformatobserver.h"
 #include "tmrpropertyobserver.h"
+#include "thumbnailmanagerconstants.h"
 
 //FORWARD DECLARATIONS
 class MMPXCollectionUtility;
 
+
+enum TThumbnailGenerationItemType
+      {
+      EGenerationItemTypeUnknown,
+      EGenerationItemTypeNotFound,
+      EGenerationItemTypeCamera,
+      EGenerationItemTypeAny,
+      EGenerationItemTypeAudio,
+      EGenerationItemTypeVideo,
+      EGenerationItemTypeImage,
+      EGenerationItemTypeItemCount
+      };
+
+  enum TThumbnailGenerationItemAction
+      {
+      EGenerationItemActionAdd,
+      EGenerationItemActionDelete,
+      EGenerationItemActionModify,
+      EGenerationItemAction2ndAdd,
+      EGenerationItemActionResolveType,
+      EGenerationItemActionCount
+      };
+
+  struct TThumbnailGenerationItem
+      {
+      inline TThumbnailGenerationItem(): iItemId( KErrNotFound ), iItemType(EGenerationItemTypeUnknown), iItemAction(EGenerationItemActionAdd), iPlaceholder(EFalse), iUri(NULL){}
+      inline ~TThumbnailGenerationItem(){delete iUri; iUri = NULL;}
+      
+      TItemId iItemId;
+      TThumbnailGenerationItemType iItemType;
+      TThumbnailGenerationItemAction iItemAction;
+      TBool iPlaceholder;
+      HBufC* iUri;
+      };
+
 /**
  *  Processor object for handling thumb generation
  *
@@ -119,17 +155,18 @@
      * @since S60 v5.0
      * @param aMdESession MdE Session
      */
-    void SetMdESession( CMdESession* aMdESession );    
+    void SetMdESessionL( CMdESession* aMdESession );    
     
     /**
      * Adds new IDs to queue
      *
      * @since S60 v5.0
      * @param aType TObserverNotificationType
+	 * @param TThumbnailGenerationItemType
      * @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, const RPointerArray<HBufC>& aObjectUriArray, TBool aPresent );
+    void AddToQueueL( TObserverNotificationType aType, TThumbnailGenerationItemType aItemType, const RArray<TItemId>& aIDArray, const RPointerArray<HBufC>& aObjectUriArray, TBool aPresent );
     
     /**
      * Calls Thumbnail Manager to create thumbnails
@@ -148,6 +185,9 @@
     void RemoveFromQueues( const RArray<TItemId>& aIDArray, const TBool aRemoveFromDelete = EFalse);
     
     void SetForceRun( const TBool aForceRun );
+	
+	//prepare processor for shutdown
+	void Shutdown();
     
 protected:
     
@@ -157,9 +197,9 @@
      * QueryL
      *
      * @since S60 v5.0
-     * @param aIDArray Item IDs to query
+     * @param TThumbnailGenerationItemAction
      */
-    void QueryL( RArray<TItemId>& aIDArray );
+    void QueryL( TThumbnailGenerationItemAction aType);
     
 	 /**
      * QueryPlaceholdersL
@@ -257,14 +297,58 @@
      * @since S60 v5.0
  	 * @param aDefine (re)define PS key before setting value
      */
-    void UpdatePSValues(const TBool aDefine = EFalse);
+    void UpdatePSValues(const TBool aDefine, const TBool aForce);
        
     /**
      * Comparison function for logaritmic use of queue arrays
      * 
+     * @since S60 S^3
+     */
+    static TInt Compare(const TThumbnailGenerationItem& aLeft, const TThumbnailGenerationItem& aRight);
+	
+	 /**
+     * Comparison function for logaritmic use of queue arrays
+     * 
+     * @since S60 S^3
+     */
+    static TInt CompareId(const TItemId& aLeft, const TItemId& aRight);
+    
+	/**
+     * Recalculate item counts
+     * 
+     * @since S60 S^3
+     */
+    void UpdateItemCounts();
+	
+    /**
+     * Callback for mount timeout
+     *
      * @since S60 v5.0
      */
-    static TInt Compare(const TItemId& aLeft, const TItemId& aRight);
+    static TInt MountTimerCallBack(TAny* aAny);
+    
+	 /**
+     * Set item's action from type
+     *
+     * @since S^3
+     */
+    void SetGenerationItemAction( TThumbnailGenerationItem& aGenerationItem, const TThumbnailGenerationItemType aItemType );
+	
+     /**
+     * Set item type property from TDedIf
+     * @param aGenerationItem TThumbnailGenerationItem
+     * @param aItemType TThumbnailGenerationItemType
+     * @since S^3
+     */
+    void SetGenerationItemType( TThumbnailGenerationItem& aGenerationItem, const TDefId aDefId );
+ 
+     /**
+     * Append item to processing queue or update existing
+     * @param aGenerationItem modified TThumbnailGenerationItem
+     * @param aDefId items MDS object definition ID
+     * @since S^3
+     */
+    void AppendProcessingQueue(TThumbnailGenerationItem& item );
         
 private:
     
@@ -278,20 +362,19 @@
     CMdEObjectQuery* iQueryAllItems;
     CMdEObjectQuery* iQueryPlaceholders;
     
-    RArray<TItemId> iAddQueue;
-    RArray<TItemId> iModifyQueue;
-    RPointerArray<HBufC> iRemoveQueue;
+    RArray<TThumbnailGenerationItem> iGenerationQueue;
+    //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;
     
 	//background generation state
 	// EFalse = 1st round, create only grid size thumbnail for images and videos
 	// ETrue = 2nds round, create all missing sizes for all media items
     TBool i2ndRound;    
+	
+	// query state
+	// EFalse = normal mode
+	// ETrue = querying unknown items
+    TBool iUnknown;
     
 	//MDS query issues
     TBool iQueryActive;
@@ -300,7 +383,7 @@
     
 	//Processing MDS itens which are modified
     TBool iModify;
-    TInt iProcessingCount;
+    TUint iProcessingCount;
 
     //MDS harvester's overall state
     TBool iHarvesting;
@@ -315,6 +398,7 @@
     TBool iMMCHarvestingTemp;
     
     CPeriodic* iPeriodicTimer;
+    CPeriodic* iMountTimer;
 
 	//MDS Harvester client
     RHarvesterClient iHarvesterClient;
@@ -325,7 +409,7 @@
     //2nd phase init after MDE session is open
     TBool iInit2;
     
-    // auto create
+    // auto create values from centrep
     TBool iAutoImage;
     TBool iAutoVideo;
     TBool iAutoAudio;
@@ -335,14 +419,16 @@
     // controlled by Photos application to run TN generation on foreground
     TBool iForegroundRun;
 	//request pending in TNM side
-    TBool iActive;
    
     CTMFormatObserver* iFormatObserver;
    
+   //formating started
     TBool iFormatting;
+	//TNM server session died
     TBool iSessionDied;
    
-    TInt iActiveCount;
+   //pending request count
+    TUint iActiveCount;
     
     MMPXCollectionUtility* iCollectionUtility; // own
     
@@ -352,6 +438,7 @@
     //overall status of device
     TBool iIdle;
     
+	//monitors device activity
     CTMActivityManager* iActivityManager;
     
 	//Observer foreground generation 
@@ -362,6 +449,30 @@
     TBool iPreviousDaemonProcessing; 
 	//set ETrue when QueryAllItems needs to be run after placeholder query
     TBool iDoQueryAllItems;
-};
+    
+    TBool iShutdown;
+	
+	//item counts
+    TUint32 iModifyItemCount;
+    TUint32 iImageItemCount;
+    TUint32 iVideoItemCount;
+    TUint32 iAudioItemCount;
+    TUint32 iDeleteItemCount;
+    TUint32 iAddItemCount;
+    TUint32 iCameraItemCount;
+    TUint32 iUnknownItemCount;
+    TUint32 i2ndAddItemCount;
+    TUint32 iPlaceholderItemCount;
+    
+    //for book keeping previous items left count got from MDS harvester
+    TUint32 iMMCHarvestingItemsLeftTemp;
+    TUint32 iPHHarvestingItemsLeftTemp;
+    
+	//MdE object definitons used in query
+    CMdEObjectDef* iImageObjectDef;
+    CMdEObjectDef* iVideoObjectDef;
+    CMdEObjectDef* iAudioObjectDef;
+    TBool iHarvesterActivated;
+  };
 
 #endif // THUMBAGPROCESSOR_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/imagehandlingutilities/thumbnailmanager/thumbagdaemon/inc/thumbagvideoobserver.h	Wed Jun 23 18:33:48 2010 +0300
@@ -0,0 +1,145 @@
+/*
+* 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:  Thumbnail Auto Generate Daemon
+ *
+*/
+
+
+#ifndef THUMBAGVIDEOBSERVER_H
+#define THUMBAGVIDEOBSERVER_H
+
+#include <e32base.h>
+#include <w32std.h>
+
+#include <mdesession.h>
+
+#include "thumbagprocessor.h"
+#include "thumbnaillog.h"
+#include "tmshutdownobserver.h"
+
+
+/**
+ *  ThumbAG daemon.
+ *
+ *  @since S60 v5.0
+ */
+NONSHARABLE_CLASS( CThumbAGVideoObserver ): public CBase, 
+                                     public MMdESessionObserver,
+                                     public MMdEObjectObserver,
+                                     public MTMShutdownObserver
+    {
+public:
+
+    /**
+     * Two-phased constructor
+     *
+     * @since S60 v5.0
+     * @return New CThumbAGVideoObserver server.
+     */
+    static CThumbAGVideoObserver* NewLC(CThumbAGProcessor* aProcessor);
+
+    /**
+     * Two-phased constructor
+     *
+     * @since S60 v5.0
+     * @return New CThumbAGVideoObserver server.
+     */
+    static CThumbAGVideoObserver* NewL(CThumbAGProcessor* aProcessor);
+    
+    /**
+     * Destructor
+     *
+     * @since S60 v5.0
+     */
+    virtual ~CThumbAGVideoObserver();
+
+
+public:
+    
+    // from MMdESessionObserver
+    void HandleSessionOpened( CMdESession& aSession, TInt aError );
+    void HandleSessionError( CMdESession& aSession, TInt aError );
+    
+    // from MMdEObjectObserver
+    void HandleObjectNotification(CMdESession& aSession, 
+                                  TObserverNotificationType aType,
+                                  const RArray<TItemId>& aObjectIdArray);
+        
+    // from MTMShutdownObserver
+    void ShutdownNotification();
+    
+protected:
+    
+    /**
+     * AddObserversL
+     *
+     * @since S60 v5.0
+     */
+    void AddObserversL();    
+    
+    
+private:
+
+    /**
+     * C++ default constructor
+     *
+     * @since S60 v5.0
+     * @return New CThumbAGVideoObserver instance.
+     */
+    CThumbAGVideoObserver(CThumbAGProcessor* aProcessor);
+
+    /**
+     * Symbian 2nd phase constructor can leave.
+     *
+     * @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:
+	
+    // own
+    CTMShutdownObserver* iShutdownObserver;
+    CTMShutdownObserver* iMDSShutdownObserver;
+    CMdESession* iMdESession;
+    //not owned
+    CThumbAGProcessor* iProcessor;
+    
+    TBool iShutdown;
+ 
+    // reconnect timer
+    CPeriodic* iReconnect;
+    
+    TBool iSessionError;
+    
+#ifdef _DEBUG
+    TUint32 iAddCounter;
+    TUint32 iModCounter;
+#endif
+};
+
+#endif // THUMBAGDAEMON_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/imagehandlingutilities/thumbnailmanager/thumbagdaemon/src/thumbagaudioobserver.cpp	Wed Jun 23 18:33:48 2010 +0300
@@ -0,0 +1,348 @@
+/*
+* 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:  Thumbnail Auto Generate Daemon 
+*
+*/
+
+
+#include <e32svr.h>
+#include <centralrepository.h>
+
+#include <mdesession.h>
+#include <mdeconstants.h>
+#include <mdequery.h>
+#include <mdeobject.h>
+
+#include "thumbagaudioobserver.h"
+#include "thumbnaillog.h"
+#include "thumbnailmanagerconstants.h"
+#include "thumbnailmanagerprivatecrkeys.h"
+
+
+// ---------------------------------------------------------------------------
+// NewLC
+// ---------------------------------------------------------------------------
+//
+CThumbAGAudioObserver* CThumbAGAudioObserver::NewLC(CThumbAGProcessor* aProcessor)
+    {
+    TN_DEBUG1( "CThumbAGAudioObserver::NewLC() - begin" );
+    
+	CThumbAGAudioObserver* self = new (ELeave) CThumbAGAudioObserver(aProcessor);
+	CleanupStack::PushL( self );
+	self->ConstructL();
+	return self;
+	}
+	
+// ---------------------------------------------------------------------------
+// NewL
+// ---------------------------------------------------------------------------
+//
+CThumbAGAudioObserver* CThumbAGAudioObserver::NewL(CThumbAGProcessor* aProcessor)
+	{
+	TN_DEBUG1( "CThumbAGAudioObserver::NewL() - begin" );
+    
+	CThumbAGAudioObserver* self = CThumbAGAudioObserver::NewLC(aProcessor);
+	CleanupStack::Pop( self );
+	return self;
+	}
+
+// ---------------------------------------------------------------------------
+// CThumbAGAudioObserver
+// ---------------------------------------------------------------------------
+//
+CThumbAGAudioObserver::CThumbAGAudioObserver(CThumbAGProcessor* aProcessor)
+ 	: iShutdownObserver(NULL), iMDSShutdownObserver(NULL), iMdESession(NULL), iProcessor(aProcessor)
+ 	{
+ 	// No implementation required
+ 	}
+
+// ---------------------------------------------------------------------------
+// ConstructL
+// ---------------------------------------------------------------------------
+//
+void CThumbAGAudioObserver::ConstructL()
+	{
+	TN_DEBUG1( "CThumbAGAudioObserver::ConstructL() - begin" );
+	
+#ifdef _DEBUG
+    iAddCounter = 0;
+    iModCounter = 0;
+#endif
+    
+    InitializeL();
+    	
+	TN_DEBUG1( "CThumbAGAudioObserver::ConstructL() - end" );
+	}
+
+// ---------------------------------------------------------------------------
+// ~CThumbAGAudioObserver
+// ---------------------------------------------------------------------------
+//
+void CThumbAGAudioObserver::InitializeL()
+    {
+    TN_DEBUG1( "CThumbAGAudioObserver::InitializeL() - begin" );
+    
+   
+        TN_DEBUG1( "CThumbAGAudioObserver::InitializeL() - create observers" );
+        
+        // create shutdown observer
+        if(iMDSShutdownObserver)
+            {
+            delete iMDSShutdownObserver;
+            iMDSShutdownObserver = NULL;
+            }     
+        iMDSShutdownObserver = CTMShutdownObserver::NewL( *this, KMdSPSShutdown, KMdSShutdown, EFalse );
+
+        if(iShutdownObserver)
+            {
+            delete iShutdownObserver;
+            iShutdownObserver = NULL;
+            }
+        iShutdownObserver = CTMShutdownObserver::NewL( *this, KTAGDPSNotification, KShutdown, ETrue );  
+        iShutdown = EFalse;
+        
+        // MDS session reconnect timer
+        if (!iReconnect)
+            {
+            iReconnect = CPeriodic::NewL(CActive::EPriorityIdle);
+            }
+        
+        TN_DEBUG1( "CThumbAGAudioObserver::InitializeL() - connect to MDS" );
+        
+        if(iMdESession)
+            {
+            TRAP_IGNORE( iMdESession->RemoveObjectObserverL( *this ) );
+            TRAP_IGNORE( iMdESession->RemoveObjectObserverL( *this ) );
+        
+            // connect to MDS
+            delete iMdESession;
+            iMdESession = NULL;
+            }
+
+        iMdESession = CMdESession::NewL( *this );
+        iSessionError = EFalse;
+      
+        TN_DEBUG1( "CThumbAGAudioObserver::InitializeL() - end" );
+    }
+
+// ---------------------------------------------------------------------------
+// ~CThumbAGAudioObserver
+// ---------------------------------------------------------------------------
+//
+CThumbAGAudioObserver::~CThumbAGAudioObserver()
+    {
+    TN_DEBUG1( "CThumbAGAudioObserver::~CThumbAGAudioObserver() - begin" );
+    
+    iShutdown = ETrue;    
+    
+    Shutdown();
+    
+    TN_DEBUG1( "CThumbAGAudioObserver::~CThumbAGAudioObserver() - end" );
+    }
+
+void CThumbAGAudioObserver::Shutdown()
+    {
+    TN_DEBUG1( "CThumbAGAudioObserver::Shutdown()" );
+    
+    delete iMDSShutdownObserver;
+    iMDSShutdownObserver = NULL;
+    delete iShutdownObserver;
+    iShutdownObserver = NULL;
+    
+    if(iReconnect)
+        {
+        iReconnect->Cancel();
+        delete iReconnect;
+        iReconnect = NULL;
+        }
+    
+    if (iMdESession)
+        {
+        // 2 observers
+        TRAP_IGNORE( iMdESession->RemoveObjectObserverL( *this ) );
+        TRAP_IGNORE( iMdESession->RemoveObjectObserverL( *this ) );
+                
+        delete iMdESession;
+        iMdESession = NULL;
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CThumbAGAudioObserver::HandleSessionOpened
+// -----------------------------------------------------------------------------
+//
+void CThumbAGAudioObserver::HandleSessionOpened( CMdESession& /* aSession */, TInt aError )
+    {
+    TN_DEBUG1( "CThumbAGAudioObserver::HandleSessionOpened");
+    
+    if (aError == KErrNone)
+        {
+        TRAPD( err, AddObserversL() );
+        if (err != KErrNone)
+            {
+            TN_DEBUG2( "CThumbAGAudioObserver::HandleSessionOpened, AddObserversL error == %d", err );
+            }
+        }
+    else
+        {
+        TN_DEBUG2( "CThumbAGAudioObserver::HandleSessionOpened error == %d", aError );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CThumbAGAudioObserver::HandleSessionError
+// -----------------------------------------------------------------------------
+//
+void CThumbAGAudioObserver::HandleSessionError( CMdESession& /*aSession*/, TInt aError )
+    {
+    TN_DEBUG2( "CThumbAGAudioObserver::HandleSessionError == %d", aError );
+    if (aError != KErrNone && !iSessionError)
+        {
+        iSessionError = ETrue;
+    
+        if (!iShutdown)
+            {
+            if (!iReconnect->IsActive())
+                {
+                iReconnect->Start( KMdEReconnect, KMdEReconnect, 
+                                   TCallBack(ReconnectCallBack, this));
+                
+                TN_DEBUG1( "CThumbAGAudioObserver::HandleSessionError() - reconnect timer started" );
+                }
+            }
+
+        }   
+    }
+
+// -----------------------------------------------------------------------------
+// CThumbAGAudioObserver::HandleObjectNotification
+// -----------------------------------------------------------------------------
+//
+void CThumbAGAudioObserver::HandleObjectNotification( CMdESession& /*aSession*/, 
+                                               TObserverNotificationType aType,
+                                               const RArray<TItemId>& aObjectIdArray )
+    {
+    TN_DEBUG1( "CThumbAGAudioObserver::HandleObjectNotification() - begin" );
+
+    // no processor or shutting down
+    if ( iShutdown || !iProcessor)
+        {
+        return;
+        }
+    
+#ifdef _DEBUG
+    if (aType == ENotifyAdd)
+        {
+        TN_DEBUG2( "CThumbAGAudioObserver::HandleObjectNotification() - ENotifyAdd %d", aObjectIdArray.Count() );
+        iAddCounter = aObjectIdArray.Count();
+        }
+    else if (aType == ENotifyModify)
+        {
+        TN_DEBUG2( "CThumbAGAudioObserver::HandleObjectNotification() - ENotifyModify %d", aObjectIdArray.Count() );
+        iModCounter = aObjectIdArray.Count();
+        }
+#endif
+    
+    if ( (aType == ENotifyAdd || aType == ENotifyModify ) && (aObjectIdArray.Count() > 0) )
+        {
+        TN_DEBUG1( "CThumbAGAudioObserver::HandleObjectNotification() - AddToQueueL" );
+
+        // Add event to processing queue by type and enable force run        
+        RPointerArray<HBufC> dummyArray;
+        TRAPD(err, iProcessor->AddToQueueL(aType, EGenerationItemTypeAudio, aObjectIdArray, dummyArray, EFalse));
+        if (err != KErrNone)
+            {
+            TN_DEBUG1( "CThumbAGAudioObserver::HandleObjectNotification() - error adding to queue" );
+            }
+        }
+    else
+        {
+        TN_DEBUG1( "CThumbAGAudioObserver::HandleObjectNotification() - bad notification" );
+        }
+    
+#ifdef _DEBUG
+    TN_DEBUG3( "CThumbAGImageObserver::IN-COUNTERS---------- Add = %d Modify = %d", iAddCounter, iModCounter );
+    iModCounter = 0;
+    iAddCounter = 0;
+#endif
+
+    TN_DEBUG1( "CThumbAGAudioObserver::HandleObjectNotification() - end" );
+    }
+
+// -----------------------------------------------------------------------------
+// CThumbAGAudioObserver::ShutdownNotification
+// -----------------------------------------------------------------------------
+//
+void CThumbAGAudioObserver::ShutdownNotification()
+    {
+    TN_DEBUG1( "CThumbAGAudioObserver::ShutdownNotification()" );
+    
+    if (!iShutdown)
+        {
+        TN_DEBUG1( "CThumbAGAudioObserver::ShutdownNotification() shutdown" );
+        iShutdown = ETrue;
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// CThumbAGAudioObserver::AddObserversL
+// ---------------------------------------------------------------------------
+//
+void CThumbAGAudioObserver::AddObserversL()
+    {
+    TN_DEBUG1( "CThumbAGAudioObserver::AddObserversL() - begin" );
+    
+    CMdENamespaceDef& defaultNamespace = iMdESession->GetDefaultNamespaceDefL();
+    CMdEObjectDef& audioDef = defaultNamespace.GetObjectDefL( MdeConstants::Audio::KAudioObject );
+    
+    // set observing conditions
+    CMdELogicCondition* addCondition = CMdELogicCondition::NewLC( ELogicConditionOperatorAnd );
+    addCondition->AddObjectConditionL( audioDef );
+    CleanupStack::Pop( addCondition );  
+    
+    CMdELogicCondition* modifyCondition = CMdELogicCondition::NewLC( ELogicConditionOperatorAnd );
+    modifyCondition->AddObjectConditionL( audioDef );
+    CleanupStack::Pop( modifyCondition );
+    
+    // add observer
+    iMdESession->AddObjectObserverL( *this, addCondition, ENotifyAdd ); 
+
+   // modify observer
+   iMdESession->AddObjectObserverL( *this, modifyCondition, ENotifyModify );
+     
+    TN_DEBUG1( "CThumbAGAudioObserver::AddObserversL() - end" );
+    }
+
+// ---------------------------------------------------------------------------
+// CThumbAGAudioObserver::ReconnectCallBack()
+// ---------------------------------------------------------------------------
+//
+TInt CThumbAGAudioObserver::ReconnectCallBack(TAny* aAny)
+    {
+    TN_DEBUG1( "CThumbAGAudioObserver::ReconnectCallBack() - reinitialize");
+    
+    CThumbAGAudioObserver* self = static_cast<CThumbAGAudioObserver*>( aAny );
+    
+    self->iReconnect->Cancel();
+    
+    // reconnect to MDS
+    TRAP_IGNORE( self->InitializeL() );
+    
+    TN_DEBUG1( "CThumbAGAudioObserver::ReconnectCallBack() - done");
+    
+    return KErrNone;
+    }
+
+
+// End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/imagehandlingutilities/thumbnailmanager/thumbagdaemon/src/thumbagcameraobserver.cpp	Wed Jun 23 18:33:48 2010 +0300
@@ -0,0 +1,340 @@
+/*
+* 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:  Thumbnail Auto Generate Daemon 
+*
+*/
+
+
+#include <e32svr.h>
+#include <centralrepository.h>
+
+#include <mdesession.h>
+#include <mdeconstants.h>
+#include <mdequery.h>
+#include <mdeobject.h>
+
+#include "thumbagcameraobserver.h"
+#include "thumbnaillog.h"
+#include "thumbnailmanagerconstants.h"
+#include "thumbnailmanagerprivatecrkeys.h"
+
+
+// ---------------------------------------------------------------------------
+// NewLC
+// ---------------------------------------------------------------------------
+//
+CThumbAGCameraObserver* CThumbAGCameraObserver::NewLC(CThumbAGProcessor* aProcessor)
+    {
+    TN_DEBUG1( "CThumbAGCameraObserver::NewLC() - begin" );
+    
+	CThumbAGCameraObserver* self = new (ELeave) CThumbAGCameraObserver(aProcessor);
+	CleanupStack::PushL( self );
+	self->ConstructL();
+	return self;
+	}
+	
+// ---------------------------------------------------------------------------
+// NewL
+// ---------------------------------------------------------------------------
+//
+CThumbAGCameraObserver* CThumbAGCameraObserver::NewL(CThumbAGProcessor* aProcessor)
+	{
+	TN_DEBUG1( "CThumbAGCameraObserver::NewL() - begin" );
+    
+	CThumbAGCameraObserver* self = CThumbAGCameraObserver::NewLC(aProcessor);
+	CleanupStack::Pop( self );
+	return self;
+	}
+
+// ---------------------------------------------------------------------------
+// CThumbAGCameraObserver
+// ---------------------------------------------------------------------------
+//
+CThumbAGCameraObserver::CThumbAGCameraObserver(CThumbAGProcessor* aProcessor)
+ 	: iShutdownObserver(NULL), iMDSShutdownObserver(NULL), iMdESession(NULL), iProcessor(aProcessor)
+ 	{
+ 	// No implementation required
+ 	}
+
+// ---------------------------------------------------------------------------
+// ConstructL
+// ---------------------------------------------------------------------------
+//
+void CThumbAGCameraObserver::ConstructL()
+	{
+	TN_DEBUG1( "CThumbAGCameraObserver::ConstructL() - begin" );
+	
+#ifdef _DEBUG
+    iAddCounter = 0;
+    iModCounter = 0;
+#endif
+    
+    InitializeL();
+    	
+	TN_DEBUG1( "CThumbAGCameraObserver::ConstructL() - end" );
+	}
+
+// ---------------------------------------------------------------------------
+// ~CThumbAGCameraObserver
+// ---------------------------------------------------------------------------
+//
+void CThumbAGCameraObserver::InitializeL()
+    {
+    TN_DEBUG1( "CThumbAGCameraObserver::InitializeL() - begin" );
+    
+   
+        TN_DEBUG1( "CThumbAGCameraObserver::InitializeL() - create observers" );
+        
+        // create shutdown observer
+        if(iMDSShutdownObserver)
+            {
+            delete iMDSShutdownObserver;
+            iMDSShutdownObserver = NULL;
+            }     
+        iMDSShutdownObserver = CTMShutdownObserver::NewL( *this, KMdSPSShutdown, KMdSShutdown, EFalse );
+
+        if(iShutdownObserver)
+            {
+            delete iShutdownObserver;
+            iShutdownObserver = NULL;
+            }
+        iShutdownObserver = CTMShutdownObserver::NewL( *this, KTAGDPSNotification, KShutdown, ETrue );  
+        iShutdown = EFalse;
+        
+        // MDS session reconnect timer
+        if (!iReconnect)
+            {
+            iReconnect = CPeriodic::NewL(CActive::EPriorityIdle);
+            }
+        
+        TN_DEBUG1( "CThumbAGCameraObserver::InitializeL() - connect to MDS" );
+        
+        if(iMdESession)
+            {
+            TRAP_IGNORE( iMdESession->RemoveObjectObserverL( *this ) );
+            TRAP_IGNORE( iMdESession->RemoveObjectObserverL( *this ) );
+        
+            // connect to MDS
+            delete iMdESession;
+            iMdESession = NULL;
+            }
+
+        iMdESession = CMdESession::NewL( *this );
+        iSessionError = EFalse;
+      
+        TN_DEBUG1( "CThumbAGCameraObserver::InitializeL() - end" );
+    }
+
+// ---------------------------------------------------------------------------
+// ~CThumbAGCameraObserver
+// ---------------------------------------------------------------------------
+//
+CThumbAGCameraObserver::~CThumbAGCameraObserver()
+    {
+    TN_DEBUG1( "CThumbAGCameraObserver::~CThumbAGCameraObserver() - begin" );
+    
+    iShutdown = ETrue;    
+    
+    delete iMDSShutdownObserver;
+    delete iShutdownObserver;
+    
+    if(iReconnect)
+        {
+        iReconnect->Cancel();
+        delete iReconnect;
+        iReconnect = NULL;
+        }
+    
+    if (iMdESession)
+        {
+        // 2 observers
+        TRAP_IGNORE( iMdESession->RemoveObjectObserverL( *this ) );
+        TRAP_IGNORE( iMdESession->RemoveObjectObserverL( *this ) );
+                
+        delete iMdESession;
+        iMdESession = NULL;
+        }
+    
+    TN_DEBUG1( "CThumbAGCameraObserver::~CThumbAGCameraObserver() - end" );
+    }
+
+// -----------------------------------------------------------------------------
+// CThumbAGCameraObserver::HandleSessionOpened
+// -----------------------------------------------------------------------------
+//
+void CThumbAGCameraObserver::HandleSessionOpened( CMdESession& /* aSession */, TInt aError )
+    {
+    TN_DEBUG1( "CThumbAGCameraObserver::HandleSessionOpened");
+    
+    if (aError == KErrNone)
+        {
+        TRAPD( err, AddObserversL() );
+        if (err != KErrNone)
+            {
+            TN_DEBUG2( "CThumbAGCameraObserver::HandleSessionOpened, AddObserversL error == %d", err );
+            }
+        }
+    else
+        {
+        TN_DEBUG2( "CThumbAGCameraObserver::HandleSessionOpened error == %d", aError );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CThumbAGCameraObserver::HandleSessionError
+// -----------------------------------------------------------------------------
+//
+void CThumbAGCameraObserver::HandleSessionError( CMdESession& /*aSession*/, TInt aError )
+    {
+    TN_DEBUG2( "CThumbAGCameraObserver::HandleSessionError == %d", aError );
+    if (aError != KErrNone && !iSessionError)
+        {
+        iSessionError = ETrue;
+    
+        if (!iShutdown)
+            {
+            if (!iReconnect->IsActive())
+                {
+                iReconnect->Start( KMdEReconnect, KMdEReconnect, 
+                                   TCallBack(ReconnectCallBack, this));
+                
+                TN_DEBUG1( "CThumbAGCameraObserver::HandleSessionError() - reconnect timer started" );
+                }
+            }
+
+        }   
+    }
+
+// -----------------------------------------------------------------------------
+// CThumbAGCameraObserver::HandleObjectNotification
+// -----------------------------------------------------------------------------
+//
+void CThumbAGCameraObserver::HandleObjectNotification( CMdESession& /*aSession*/, 
+                                               TObserverNotificationType aType,
+                                               const RArray<TItemId>& aObjectIdArray )
+    {
+    TN_DEBUG1( "CThumbAGCameraObserver::HandleObjectNotification() - begin" );
+
+    // no processor or shutting down
+    if ( iShutdown || !iProcessor)
+        {
+        return;
+        }
+    
+#ifdef _DEBUG
+    if (aType == ENotifyAdd)
+        {
+        TN_DEBUG2( "CThumbAGCameraObserver::HandleObjectNotification() - ENotifyAdd %d", aObjectIdArray.Count() );
+        iAddCounter = aObjectIdArray.Count();
+        }
+    else if (aType == ENotifyModify)
+        {
+        TN_DEBUG2( "CThumbAGCameraObserver::HandleObjectNotification() - ENotifyModify %d", aObjectIdArray.Count() );
+        iModCounter = aObjectIdArray.Count();
+        }
+#endif
+    
+    if ( (aType == ENotifyAdd || aType == ENotifyModify ) && (aObjectIdArray.Count() > 0) )
+        {
+        TN_DEBUG1( "CThumbAGCameraObserver::HandleObjectNotification() - AddToQueueL" );
+
+        // Add event to processing queue by type and enable force run        
+        RPointerArray<HBufC> dummyArray;
+        TRAPD(err, iProcessor->AddToQueueL(aType, EGenerationItemTypeCamera, aObjectIdArray, dummyArray, EFalse));
+        if (err != KErrNone)
+            {
+            TN_DEBUG1( "CThumbAGCameraObserver::HandleObjectNotification() - error adding to queue" );
+            }
+        }
+    else
+        {
+        TN_DEBUG1( "CThumbAGCameraObserver::HandleObjectNotification() - bad notification" );
+        }
+    
+#ifdef _DEBUG
+    TN_DEBUG3( "CThumbAGImageObserver::IN-COUNTERS---------- Add = %d Modify = %d", iAddCounter, iModCounter );
+    iModCounter = 0;
+    iAddCounter = 0;
+#endif
+
+    TN_DEBUG1( "CThumbAGCameraObserver::HandleObjectNotification() - end" );
+    }
+
+// -----------------------------------------------------------------------------
+// CThumbAGCameraObserver::ShutdownNotification
+// -----------------------------------------------------------------------------
+//
+void CThumbAGCameraObserver::ShutdownNotification()
+    {
+    TN_DEBUG1( "CThumbAGCameraObserver::ShutdownNotification()" );
+    
+    if (!iShutdown)
+        {
+        TN_DEBUG1( "CThumbAGCameraObserver::ShutdownNotification() shutdown" );
+        iShutdown = ETrue;
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// CThumbAGCameraObserver::AddObserversL
+// ---------------------------------------------------------------------------
+//
+void CThumbAGCameraObserver::AddObserversL()
+    {
+    TN_DEBUG1( "CThumbAGCameraObserver::AddObserversL() - begin" );
+    
+    CMdENamespaceDef& defaultNamespace = iMdESession->GetDefaultNamespaceDefL();
+    CMdEObjectDef& objectDef = defaultNamespace.GetObjectDefL( MdeConstants::Object::KBaseObject );
+    CMdEPropertyDef& originPropDef = objectDef.GetPropertyDefL( MdeConstants::Object::KOriginProperty );
+    
+    // set observing conditions
+    CMdELogicCondition* addCondition = CMdELogicCondition::NewLC( ELogicConditionOperatorAnd );
+    addCondition->AddPropertyConditionL( originPropDef, TMdEUintEqual(MdeConstants::Object::ECamera));
+    CleanupStack::Pop( addCondition );  
+    
+    CMdELogicCondition* modifyCondition = CMdELogicCondition::NewLC( ELogicConditionOperatorAnd );
+    modifyCondition->AddPropertyConditionL( originPropDef, TMdEUintEqual(MdeConstants::Object::ECamera));
+    CleanupStack::Pop( modifyCondition );
+    
+    // add observer
+    iMdESession->AddObjectObserverL( *this, addCondition, ENotifyAdd ); 
+
+   // modify observer
+   iMdESession->AddObjectObserverL( *this, modifyCondition, ENotifyModify );
+     
+    TN_DEBUG1( "CThumbAGCameraObserver::AddObserversL() - end" );
+    }
+
+// ---------------------------------------------------------------------------
+// CThumbAGCameraObserver::ReconnectCallBack()
+// ---------------------------------------------------------------------------
+//
+TInt CThumbAGCameraObserver::ReconnectCallBack(TAny* aAny)
+    {
+    TN_DEBUG1( "CThumbAGCameraObserver::ReconnectCallBack() - reinitialize");
+    
+    CThumbAGCameraObserver* self = static_cast<CThumbAGCameraObserver*>( aAny );
+    
+    self->iReconnect->Cancel();
+    
+    // reconnect to MDS
+    TRAP_IGNORE( self->InitializeL() );
+    
+    TN_DEBUG1( "CThumbAGCameraObserver::ReconnectCallBack() - done");
+    
+    return KErrNone;
+    }
+
+
+// End of file
--- a/imagehandlingutilities/thumbnailmanager/thumbagdaemon/src/thumbagdaemon.cpp	Fri Jun 11 13:58:45 2010 +0300
+++ b/imagehandlingutilities/thumbnailmanager/thumbagdaemon/src/thumbagdaemon.cpp	Wed Jun 23 18:33:48 2010 +0300
@@ -80,7 +80,6 @@
 	
 #ifdef _DEBUG
     iAddCounter = 0;
-    iModCounter = 0;
     iDelCounter = 0;
 #endif
     
@@ -120,6 +119,7 @@
         // create processor
         if(iProcessor)
             {
+            iProcessor->Shutdown();
             delete iProcessor;
             iProcessor = NULL; 
             }
@@ -136,9 +136,7 @@
         
         if(iMdESession)
             {
-            TRAP_IGNORE( iMdESession->RemoveObjectObserverL( *this ) );
-            TRAP_IGNORE( iMdESession->RemoveObjectObserverL( *this ) );
-            TRAP_IGNORE( iMdESession->RemoveObjectObserverL( *this ) );
+            TRAP_IGNORE( iMdESession->RemoveObjectObserverWithUriL( *this ) );
             TRAP_IGNORE( iMdESession->RemoveObjectPresentObserverL( * this  ));
         
             // connect to MDS
@@ -148,6 +146,22 @@
 
         iMdESession = CMdESession::NewL( *this );
         iSessionError = EFalse;
+        
+        delete iImageObserver;
+        iImageObserver = NULL;
+        iImageObserver = CThumbAGImageObserver::NewL(iProcessor);
+       
+        delete iCameraObserver;
+        iCameraObserver = NULL;
+        iCameraObserver = CThumbAGCameraObserver::NewL(iProcessor);
+        
+        delete iAudioObserver;
+        iAudioObserver = NULL;
+        iAudioObserver = CThumbAGAudioObserver::NewL(iProcessor);
+        
+        delete iVideoObserver;
+        iVideoObserver = NULL;
+        iVideoObserver = CThumbAGVideoObserver::NewL(iProcessor);
         }
     else
         {
@@ -165,7 +179,19 @@
     {
     TN_DEBUG1( "CThumbAGDaemon::~CThumbAGDaemon() - begin" );
     
-    iShutdown = ETrue;    
+    iShutdown = ETrue;
+    
+    delete iImageObserver;
+    iImageObserver = NULL;
+    
+    delete iCameraObserver;
+    iCameraObserver = NULL;
+    
+    delete iVideoObserver;
+    iVideoObserver = NULL;
+    
+    delete iAudioObserver;
+    iAudioObserver = NULL;
     
     delete iMDSShutdownObserver;
     delete iShutdownObserver;
@@ -179,15 +205,13 @@
     
     if (iProcessor)
         {
+        iProcessor->Shutdown();
         delete iProcessor;
         iProcessor = NULL;
         }
     
     if (iMdESession)
         {
-        // 2 observers
-        TRAP_IGNORE( iMdESession->RemoveObjectObserverL( *this ) );
-        
 #ifdef MDS_URI_OBSERVER
         // remove observer with uri
         TRAP_IGNORE( iMdESession->RemoveObjectObserverWithUriL( *this ) );
@@ -260,9 +284,9 @@
     
     if (aError == KErrNone)
         {
-        iProcessor->SetMdESession(iMdESession);
+        TRAPD(err, iProcessor->SetMdESessionL(iMdESession));
         
-        TRAPD( err, AddObserversL() );
+        TRAP( err, AddObserversL() );
         if (err != KErrNone)
             {
             TN_DEBUG2( "CThumbAGDaemon::HandleSessionOpened, AddObserversL error == %d", err );
@@ -281,26 +305,36 @@
 void CThumbAGDaemon::HandleSessionError( CMdESession& /*aSession*/, TInt aError )
     {
     TN_DEBUG2( "CThumbAGDaemon::HandleSessionError == %d", aError );
-    if (aError != KErrNone && !iSessionError)
+    if (aError != KErrNone && !iShutdown && !iSessionError)
         {
         iSessionError = ETrue;
     
+	    delete iImageObserver;
+	    iImageObserver = NULL;
+    
+	    delete iCameraObserver;
+	    iCameraObserver = NULL;
+    
+	    delete iVideoObserver;
+	    iVideoObserver = NULL;
+    
+	    delete iAudioObserver;
+	    iAudioObserver = NULL;
+		
         // kill processor right away, because it also has MdESession
         if(iProcessor)
             {
+			iProcessor->Shutdown();
             delete iProcessor;
             iProcessor = NULL; 
             }
     
-        if (!iShutdown)
+        if (!iReconnect->IsActive())
             {
-            if (!iReconnect->IsActive())
-                {
-                iReconnect->Start( KMdEReconnect, KMdEReconnect, 
-                                   TCallBack(ReconnectCallBack, this));
-                
-                TN_DEBUG1( "CThumbAGDaemon::HandleSessionError() - reconnect timer started" );
-                }
+            iReconnect->Start( KMdEReconnect, KMdEReconnect, 
+                               TCallBack(ReconnectCallBack, this));
+            
+            TN_DEBUG1( "CThumbAGDaemon::HandleSessionError() - reconnect timer started" );
             }
 
         }   
@@ -319,12 +353,18 @@
     {
     TN_DEBUG1( "CThumbAGDaemon::HandleUriObjectNotification() - begin" );
     
+    if(!iProcessor || iShutdown)
+        {
+        return;
+        }
+    
     if(aType == ENotifyRemove)
         {
         TN_DEBUG1( "CThumbAGDaemon::HandleUriObjectNotification() - removed");
         TInt err(0);
-        TRAP(err, iProcessor->AddToQueueL(aType, aObjectIdArray, aObjectUriArray, EFalse));
+        TRAP(err, iProcessor->AddToQueueL(aType, EGenerationItemTypeAny, aObjectIdArray, aObjectUriArray, EFalse));
         __ASSERT_DEBUG((err==KErrNone), User::Panic(_L("CThumbAGDaemon::HandleUriObjectNotification()"), err));
+
         err = KErrNone;
         }
     TN_DEBUG1( "CThumbAGDaemon::HandleUriObjectNotification() - end" );
@@ -348,37 +388,23 @@
         }
     
 #ifdef _DEBUG
-    if (aType == ENotifyAdd)
-        {
-        TN_DEBUG2( "CThumbAGDaemon::HandleObjectNotification() - ENotifyAdd %d", aObjectIdArray.Count() );
-        iAddCounter = aObjectIdArray.Count();
-        }
-    else if (aType == ENotifyModify)
-        {
-        TN_DEBUG2( "CThumbAGDaemon::HandleObjectNotification() - ENotifyModify %d", aObjectIdArray.Count() );
-        iModCounter = aObjectIdArray.Count();
-        }
-    else if (aType == ENotifyRemove)
+    if (aType == ENotifyRemove)
         {
         TN_DEBUG2( "CThumbAGDaemon::HandleObjectNotification() - ENotifyRemove %d", aObjectIdArray.Count() );
         iDelCounter = aObjectIdArray.Count();
         }
 #endif
     
-    if ( (aType == ENotifyAdd || aType == ENotifyModify || aType == ENotifyRemove) &&
-         (aObjectIdArray.Count() > 0) )
+    if ( aType == ENotifyRemove && aObjectIdArray.Count() > 0 )
         {
         TN_DEBUG1( "CThumbAGDaemon::HandleObjectNotification() - AddToQueueL" );
 		
         // If delete event, remove IDs from Modify and Add queues
-        if ( aType == ENotifyRemove )
-            {
-            iProcessor->RemoveFromQueues( aObjectIdArray, EFalse);
-            }
+        iProcessor->RemoveFromQueues( aObjectIdArray, EFalse);
         
         // Add event to processing queue by type and enable force run        
         RPointerArray<HBufC> dummyArray;
-        TRAPD(err, iProcessor->AddToQueueL(aType, aObjectIdArray, dummyArray, EFalse));
+        TRAPD(err, iProcessor->AddToQueueL(aType, EGenerationItemTypeAny, aObjectIdArray, dummyArray, EFalse));
         if (err != KErrNone)
             {
             TN_DEBUG1( "CThumbAGDaemon::HandleObjectNotification() - error adding to queue" );
@@ -390,12 +416,8 @@
         }
     
 #ifdef _DEBUG
-    TN_DEBUG4( "CThumbAGDaemon::IN-COUNTERS---------- Add = %d Modify = %d Delete = %d", 
-               iAddCounter, iModCounter, iDelCounter );
-    iModCounter = 0;
+    TN_DEBUG2( "CThumbAGDaemon::IN-COUNTERS---------- Delete = %d", iDelCounter );
     iDelCounter = 0;
-    iAddCounter = 0;
-    
 #endif
 
     TN_DEBUG1( "CThumbAGDaemon::HandleObjectNotification() - end" );
@@ -425,10 +447,9 @@
             {
 		    // do not force run of these items
             RPointerArray<HBufC> dummyArray;
-            TRAP(err, iProcessor->AddToQueueL(ENotifyAdd, aObjectIdArray, dummyArray, ETrue));
+            TRAP(err, iProcessor->AddToQueueL(ENotifyAdd, EGenerationItemTypeUnknown, aObjectIdArray, dummyArray, ETrue));
            
-            TN_DEBUG2( "CThumbAGDaemon::HandleObjectPresentNotification() - ENotifyAdd %d", aObjectIdArray.Count() );     
-           
+            TN_DEBUG2( "CThumbAGDaemon::HandleObjectPresentNotification() - ENotifyAdd unknown items %d", aObjectIdArray.Count() );     
            #ifdef _DEBUG
            iAddCounter = aObjectIdArray.Count();
            if (err != KErrNone)
@@ -460,11 +481,9 @@
         }
     
     #ifdef _DEBUG
-    TN_DEBUG4( "CThumbAGDaemon::IN-COUNTERS---------- Add = %d Modify = %d Delete = %d", 
-               iAddCounter, iModCounter, iDelCounter );
-    iModCounter = 0;
+    TN_DEBUG3( "CThumbAGDaemon::IN-COUNTERS---------- Add = %d Delete = %d", iAddCounter, iDelCounter );
     iDelCounter = 0;
-    iAddCounter = 0;
+	iAddCounter = 0;
     #endif
     
     TN_DEBUG1( "CThumbAGDaemon::HandleObjectPresentNotification() - end" );
@@ -493,31 +512,6 @@
     {
     TN_DEBUG1( "CThumbAGDaemon::AddObserversL() - begin" );
     
-    CMdENamespaceDef& defaultNamespace = iMdESession->GetDefaultNamespaceDefL();
-    CMdEObjectDef& imageDef = defaultNamespace.GetObjectDefL( MdeConstants::Image::KImageObject );
-    CMdEObjectDef& videoDef = defaultNamespace.GetObjectDefL( MdeConstants::Video::KVideoObject );
-    CMdEObjectDef& audioDef = defaultNamespace.GetObjectDefL( MdeConstants::Audio::KAudioObject );
-    
-    // set observing conditions
-    CMdELogicCondition* addCondition = CMdELogicCondition::NewLC( ELogicConditionOperatorOr );
-    addCondition->AddObjectConditionL( imageDef );
-    addCondition->AddObjectConditionL( videoDef );
-    addCondition->AddObjectConditionL( audioDef );
-    CleanupStack::Pop( addCondition );  
-    
-    CMdELogicCondition* modifyCondition = CMdELogicCondition::NewLC( ELogicConditionOperatorOr );
-    modifyCondition->AddObjectConditionL( imageDef );
-    modifyCondition->AddObjectConditionL( videoDef );
-    modifyCondition->AddObjectConditionL( audioDef );
-    CleanupStack::Pop( modifyCondition );
-    
-    // add observer
-    iMdESession->AddObjectObserverL( *this, addCondition, ENotifyAdd ); 
-
-   // modify observer
-#ifdef MDS_MODIFY_OBSERVER
-   iMdESession->AddObjectObserverL( *this, modifyCondition, ENotifyModify );
-#endif
  
 #ifdef MDS_URI_OBSERVER
     // remove observer with uri
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/imagehandlingutilities/thumbnailmanager/thumbagdaemon/src/thumbagimageobserver.cpp	Wed Jun 23 18:33:48 2010 +0300
@@ -0,0 +1,345 @@
+/*
+* 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:  Thumbnail Auto Generate Daemon 
+*
+*/
+
+
+#include <e32svr.h>
+#include <centralrepository.h>
+
+#include <mdesession.h>
+#include <mdeconstants.h>
+#include <mdequery.h>
+#include <mdeobject.h>
+
+#include "thumbagimageobserver.h"
+#include "thumbnaillog.h"
+#include "thumbnailmanagerconstants.h"
+#include "thumbnailmanagerprivatecrkeys.h"
+
+
+// ---------------------------------------------------------------------------
+// NewLC
+// ---------------------------------------------------------------------------
+//
+CThumbAGImageObserver* CThumbAGImageObserver::NewLC(CThumbAGProcessor* aProcessor)
+    {
+    TN_DEBUG1( "CThumbAGImageObserver::NewLC() - begin" );
+    
+	CThumbAGImageObserver* self = new (ELeave) CThumbAGImageObserver(aProcessor);
+	CleanupStack::PushL( self );
+	self->ConstructL();
+	return self;
+	}
+	
+// ---------------------------------------------------------------------------
+// NewL
+// ---------------------------------------------------------------------------
+//
+CThumbAGImageObserver* CThumbAGImageObserver::NewL(CThumbAGProcessor* aProcessor)
+	{
+	TN_DEBUG1( "CThumbAGImageObserver::NewL() - begin" );
+    
+	CThumbAGImageObserver* self = CThumbAGImageObserver::NewLC(aProcessor);
+	CleanupStack::Pop( self );
+	return self;
+	}
+
+// ---------------------------------------------------------------------------
+// CThumbAGImageObserver
+// ---------------------------------------------------------------------------
+//
+CThumbAGImageObserver::CThumbAGImageObserver(CThumbAGProcessor* aProcessor)
+ 	: iShutdownObserver(NULL), iMdESession(NULL), iProcessor(aProcessor)
+ 	{
+ 	// No implementation required
+ 	}
+
+// ---------------------------------------------------------------------------
+// ConstructL
+// ---------------------------------------------------------------------------
+//
+void CThumbAGImageObserver::ConstructL()
+	{
+	TN_DEBUG1( "CThumbAGImageObserver::ConstructL() - begin" );
+	
+#ifdef _DEBUG
+    iAddCounter = 0;
+    iModCounter = 0;
+#endif
+    
+    InitializeL();
+    	
+	TN_DEBUG1( "CThumbAGImageObserver::ConstructL() - end" );
+	}
+
+// ---------------------------------------------------------------------------
+// ~CThumbAGImageObserver
+// ---------------------------------------------------------------------------
+//
+void CThumbAGImageObserver::InitializeL()
+    {
+    TN_DEBUG1( "CThumbAGImageObserver::InitializeL() - begin" );
+    
+   
+        TN_DEBUG1( "CThumbAGImageObserver::InitializeL() - create observers" );
+        
+        // create shutdown observer
+        if(iMDSShutdownObserver)
+            {
+            delete iMDSShutdownObserver;
+            iMDSShutdownObserver = NULL;
+            }     
+        iMDSShutdownObserver = CTMShutdownObserver::NewL( *this, KMdSPSShutdown, KMdSShutdown, EFalse );
+
+        if(iShutdownObserver)
+            {
+            delete iShutdownObserver;
+            iShutdownObserver = NULL;
+            }
+        iShutdownObserver = CTMShutdownObserver::NewL( *this, KTAGDPSNotification, KShutdown, ETrue );  
+        iShutdown = EFalse;
+        
+        // MDS session reconnect timer
+        if (!iReconnect)
+            {
+            iReconnect = CPeriodic::NewL(CActive::EPriorityIdle);
+            }
+        
+        TN_DEBUG1( "CThumbAGImageObserver::InitializeL() - connect to MDS" );
+        
+        if(iMdESession)
+            {
+            TRAP_IGNORE( iMdESession->RemoveObjectObserverL( *this ) );
+            TRAP_IGNORE( iMdESession->RemoveObjectObserverL( *this ) );
+        
+            // connect to MDS
+            delete iMdESession;
+            iMdESession = NULL;
+            }
+
+        iMdESession = CMdESession::NewL( *this );
+        iSessionError = EFalse;
+      
+        TN_DEBUG1( "CThumbAGImageObserver::InitializeL() - end" );
+    }
+
+// ---------------------------------------------------------------------------
+// ~CThumbAGImageObserver
+// ---------------------------------------------------------------------------
+//
+CThumbAGImageObserver::~CThumbAGImageObserver()
+    {
+    TN_DEBUG1( "CThumbAGImageObserver::~CThumbAGImageObserver() - begin" );
+    
+    iShutdown = ETrue;    
+    
+    delete iMDSShutdownObserver;
+    delete iShutdownObserver;
+    
+    if(iReconnect)
+        {
+        iReconnect->Cancel();
+        delete iReconnect;
+        iReconnect = NULL;
+        }
+    
+    if (iMdESession)
+        {
+        // 2 observers
+        TRAP_IGNORE( iMdESession->RemoveObjectObserverL( *this ) );
+        TRAP_IGNORE( iMdESession->RemoveObjectObserverL( *this ) );
+                
+        delete iMdESession;
+        iMdESession = NULL;
+        }
+    
+    TN_DEBUG1( "CThumbAGImageObserver::~CThumbAGImageObserver() - end" );
+    }
+
+// -----------------------------------------------------------------------------
+// CThumbAGImageObserver::HandleSessionOpened
+// -----------------------------------------------------------------------------
+//
+void CThumbAGImageObserver::HandleSessionOpened( CMdESession& /* aSession */, TInt aError )
+    {
+    TN_DEBUG1( "CThumbAGImageObserver::HandleSessionOpened");
+    
+    if (aError == KErrNone)
+        {
+        TRAPD( err, AddObserversL() );
+        if (err != KErrNone)
+            {
+            TN_DEBUG2( "CThumbAGImageObserver::HandleSessionOpened, AddObserversL error == %d", err );
+            }
+        }
+    else
+        {
+        TN_DEBUG2( "CThumbAGImageObserver::HandleSessionOpened error == %d", aError );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CThumbAGImageObserver::HandleSessionError
+// -----------------------------------------------------------------------------
+//
+void CThumbAGImageObserver::HandleSessionError( CMdESession& /*aSession*/, TInt aError )
+    {
+    TN_DEBUG2( "CThumbAGImageObserver::HandleSessionError == %d", aError );
+    if (aError != KErrNone && !iSessionError)
+        {
+        iSessionError = ETrue;
+    
+        if (!iShutdown)
+            {
+            if (!iReconnect->IsActive())
+                {
+                iReconnect->Start( KMdEReconnect, KMdEReconnect, 
+                                   TCallBack(ReconnectCallBack, this));
+                
+                TN_DEBUG1( "CThumbAGImageObserver::HandleSessionError() - reconnect timer started" );
+                }
+            }
+
+        }   
+    }
+
+// -----------------------------------------------------------------------------
+// CThumbAGImageObserver::HandleObjectNotification
+// -----------------------------------------------------------------------------
+//
+void CThumbAGImageObserver::HandleObjectNotification( CMdESession& /*aSession*/, 
+                                               TObserverNotificationType aType,
+                                               const RArray<TItemId>& aObjectIdArray )
+    {
+    TN_DEBUG1( "CThumbAGImageObserver::HandleObjectNotification() - begin" );
+
+    // no processor or shutting down
+    if (iShutdown || !iProcessor)
+        {
+        return;
+        }
+    
+#ifdef _DEBUG
+    if (aType == ENotifyAdd)
+        {
+        TN_DEBUG2( "CThumbAGImageObserver::HandleObjectNotification() - ENotifyAdd %d", aObjectIdArray.Count() );
+        iAddCounter = aObjectIdArray.Count();
+        }
+    else if (aType == ENotifyModify)
+        {
+        TN_DEBUG2( "CThumbAGImageObserver::HandleObjectNotification() - ENotifyModify %d", aObjectIdArray.Count() );
+        iModCounter = aObjectIdArray.Count();
+        }
+#endif
+    
+    if ( (aType == ENotifyAdd || aType == ENotifyModify) && aObjectIdArray.Count() > 0 )
+        {
+        TN_DEBUG1( "CThumbAGImageObserver::HandleObjectNotification() - AddToQueueL" );
+		
+        // Add event to processing queue by type and enable force run        
+        RPointerArray<HBufC> dummyArray;
+        TRAPD(err, iProcessor->AddToQueueL(aType, EGenerationItemTypeImage, aObjectIdArray, dummyArray, EFalse));
+        if (err != KErrNone)
+            {
+            TN_DEBUG1( "CThumbAGImageObserver::HandleObjectNotification() - error adding to queue" );
+            }
+        }
+    else
+        {
+        TN_DEBUG1( "CThumbAGImageObserver::HandleObjectNotification() - bad notification" );
+        }
+    
+#ifdef _DEBUG
+    TN_DEBUG3( "CThumbAGImageObserver::IN-COUNTERS---------- Add = %d Modify = %d", iAddCounter, iModCounter );
+    iModCounter = 0;
+    iAddCounter = 0;
+    
+#endif
+
+    TN_DEBUG1( "CThumbAGImageObserver::HandleObjectNotification() - end" );
+    }
+
+// ---------------------------------------------------------------------------
+// CThumbAGImageObserver::AddObserversL
+// ---------------------------------------------------------------------------
+//
+void CThumbAGImageObserver::AddObserversL()
+    {
+    TN_DEBUG1( "CThumbAGImageObserver::AddObserversL() - begin" );
+    
+    CMdENamespaceDef& defaultNamespace = iMdESession->GetDefaultNamespaceDefL();
+    CMdEObjectDef& objectDef = defaultNamespace.GetObjectDefL( MdeConstants::Object::KBaseObject );
+    CMdEPropertyDef& originPropDef = objectDef.GetPropertyDefL( MdeConstants::Object::KOriginProperty );
+    CMdEObjectDef& imageDef = defaultNamespace.GetObjectDefL( MdeConstants::Image::KImageObject );
+    
+    // set observing conditions
+    CMdELogicCondition* addCondition = CMdELogicCondition::NewLC( ELogicConditionOperatorAnd );
+    addCondition->AddObjectConditionL( imageDef );
+    addCondition->AddPropertyConditionL( originPropDef, TMdEUintNotEqual(MdeConstants::Object::ECamera));
+    CleanupStack::Pop( addCondition );  
+    
+    CMdELogicCondition* modifyCondition = CMdELogicCondition::NewLC( ELogicConditionOperatorAnd );
+    modifyCondition->AddObjectConditionL( imageDef );
+    addCondition->AddPropertyConditionL( originPropDef, TMdEUintNotEqual(MdeConstants::Object::ECamera));
+    CleanupStack::Pop( modifyCondition );
+   
+    // add observers
+    iMdESession->AddObjectObserverL( *this, addCondition, ENotifyAdd ); 
+
+    // modify observer
+    iMdESession->AddObjectObserverL( *this, modifyCondition, ENotifyModify );
+     
+    TN_DEBUG1( "CThumbAGImageObserver::AddObserversL() - end" );
+    }
+
+
+// -----------------------------------------------------------------------------
+// CThumbAGCameraObserver::ShutdownNotification
+// -----------------------------------------------------------------------------
+//
+void CThumbAGImageObserver::ShutdownNotification()
+    {
+    TN_DEBUG1( "CThumbAGImageObserver::ShutdownNotification()" );
+    
+    if (!iShutdown)
+        {
+        TN_DEBUG1( "CThumbAGImageObserver::ShutdownNotification() shutdown" );
+        iShutdown = ETrue;
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// CThumbAGImageObserver::ReconnectCallBack()
+// ---------------------------------------------------------------------------
+//
+TInt CThumbAGImageObserver::ReconnectCallBack(TAny* aAny)
+    {
+    TN_DEBUG1( "CThumbAGImageObserver::ReconnectCallBack() - reinitialize");
+    
+    CThumbAGImageObserver* self = static_cast<CThumbAGImageObserver*>( aAny );
+    
+    self->iReconnect->Cancel();
+    
+    // reconnect to MDS
+    TRAP_IGNORE( self->InitializeL() );
+    
+    TN_DEBUG1( "CThumbAGImageObserver::ReconnectCallBack() - done");
+    
+    return KErrNone;
+    }
+
+
+// End of file
--- a/imagehandlingutilities/thumbnailmanager/thumbagdaemon/src/thumbagprocessor.cpp	Fri Jun 11 13:58:45 2010 +0300
+++ b/imagehandlingutilities/thumbnailmanager/thumbagdaemon/src/thumbagprocessor.cpp	Wed Jun 23 18:33:48 2010 +0300
@@ -50,7 +50,8 @@
 // CThumbAGProcessor::CThumbAGProcessor()
 // ---------------------------------------------------------------------------
 //
-CThumbAGProcessor::CThumbAGProcessor(): CActive( CActive::EPriorityStandard )
+CThumbAGProcessor::CThumbAGProcessor(): CActive( CActive::EPriorityStandard ), iMMCHarvestingItemsLeftTemp(0), 
+        iPHHarvestingItemsLeftTemp(0)
     {
     TN_DEBUG1( "CThumbAGProcessor::CThumbAGProcessor() - begin" );
     
@@ -65,6 +66,8 @@
     {
     TN_DEBUG1( "CThumbAGProcessor::ConstructL() - begin" );
     
+    iShutdown = EFalse;
+    
     iTMSession = CThumbnailManager::NewL( *this );
     iTMSession->SetRequestObserver(*this);
     
@@ -82,8 +85,9 @@
     
     iPeriodicTimer = CPeriodic::NewL(CActive::EPriorityIdle);
     
+    iMountTimer = CPeriodic::NewL(CActive::EPriorityUserInput);
+    
     SetForceRun( EFalse );    
-    iActive = EFalse;
     
     iFormatObserver = CTMFormatObserver::NewL( *this );
        
@@ -94,7 +98,7 @@
     
     iActivityManager = CTMActivityManager::NewL( this, KBackgroundGenerationIdle);
 
-    UpdatePSValues(ETrue);
+    UpdatePSValues(ETrue, ETrue);
     
     RProperty::Define(KTAGDPSNotification, KMPXHarvesting, RProperty::EInt);
     
@@ -112,12 +116,29 @@
     {
     TN_DEBUG1( "CThumbAGProcessor::~CThumbAGProcessor() - begin" );
     
+    Shutdown();
+    
     Cancel();
     
+    if (iTMSession)
+        {
+        iTMSession->RemoveRequestObserver();
+        delete iTMSession;
+        iTMSession = NULL;
+        }
+    
+    if(iMountTimer)
+        {
+        iMountTimer->Cancel();
+        delete iMountTimer;
+        iMountTimer = NULL;
+        }
+    
     if(iPeriodicTimer)
         {
         iPeriodicTimer->Cancel();
         delete iPeriodicTimer;
+        iPeriodicTimer = NULL;
         }
     
     if(iActivityManager)
@@ -172,25 +193,32 @@
         iCollectionUtility->Close();
         iCollectionUtility = NULL;
         }
-
-    iAddQueue.Close();
-    iModifyQueue.Close();
-    iRemoveQueue.ResetAndDestroy();
-    iQueryQueue.Close();
-    iPlaceholderQueue.Close();
-	  
-    i2ndRoundGenerateQueue.Close();
     
-    if (iTMSession)
+    for(TInt i=0;i<iGenerationQueue.Count();i++)
         {
-        iTMSession->RemoveRequestObserver();
-        delete iTMSession;
-        iTMSession = NULL;
+        delete iGenerationQueue[i].iUri;
+        iGenerationQueue[i].iUri = NULL;
         }
     
+    iGenerationQueue.Reset();
+    iGenerationQueue.Close();
+    
+    iQueryQueue.Close();
+    
     TN_DEBUG1( "CThumbAGProcessor::~CThumbAGProcessor() - end" );
     }
 
+// ---------------------------------------------------------------------------
+// CThumbAGProcessor::Shutdown()
+// ---------------------------------------------------------------------------
+//
+void CThumbAGProcessor::Shutdown()
+    {
+    TN_DEBUG1( "CThumbAGProcessor::Shutdown()" );
+    iShutdown = ETrue;
+    UpdatePSValues(EFalse, EFalse);
+    }
+
 // -----------------------------------------------------------------------------
 // CThumbAGProcessor::HandleQueryNewResults()
 // -----------------------------------------------------------------------------
@@ -200,6 +228,12 @@
                                                const TInt aNewItemCount )
     {
     // PH & AllItems query results are handled here
+    
+    if(iShutdown)
+        {
+        return;
+        }
+    
     if (aNewItemCount > 0)
         {
         if(&aQuery == iQueryPlaceholders)
@@ -222,13 +256,19 @@
                     }
                
                 // ignore if fails
-                iPlaceholderQueue.InsertInOrder(object->Id(), Compare);               
+                TThumbnailGenerationItem item;
+                item.iItemId = object->Id();
+                item.iPlaceholder = ETrue;
+                
+                SetGenerationItemType( item, object->Def().Id());
+                
+                AppendProcessingQueue( item );
                 }  
             }
         else if(&aQuery == iQueryAllItems)
             {
             TN_DEBUG2( "CThumbAGProcessor::HandleQueryNewResults - QueryAllItems, %d new", aNewItemCount);
-    
+            
             for(TInt i = aFirstNewItemIndex; i < iQueryAllItems->Count(); i++)
                 {    
                 const CMdEObject* object = &iQueryAllItems->Result(i);
@@ -237,13 +277,17 @@
                     {
                     continue;
                     }
-               
-                if (iAddQueue.FindInOrder(object->Id(), Compare) == KErrNotFound && 
-                    iModifyQueue.FindInOrder(object->Id(), Compare) == KErrNotFound )
-                    {
-                    // ignore if fails
-                    iAddQueue.InsertInOrder(object->Id(), Compare);
-                    }
+
+                TThumbnailGenerationItem item;
+                item.iItemId = object->Id();
+                
+                SetGenerationItemType(item, object->Def().Id());
+                
+                TInt itemIndex = iGenerationQueue.FindInOrder(item, Compare);
+                
+                item.iPlaceholder = object->Placeholder(); 
+                
+                AppendProcessingQueue( item );
                 }
             }    
         }
@@ -261,12 +305,15 @@
     {
     TN_DEBUG3( "CThumbAGProcessor::HandleQueryCompleted, aError == %d Count== %d", aError, aQuery.Count());
     
+    if(iShutdown)
+        {
+        return;
+        }
+    
     if(&aQuery == iQueryPlaceholders)
         {
         TN_DEBUG1( "CThumbAGProcessor::HandleQueryCompleted - iQueryPlaceholders completed");
         
-        iPlaceholderQueue.Reset();
-        
         //free query
         delete iQueryPlaceholders;
         iQueryPlaceholders = NULL;
@@ -304,60 +351,123 @@
             {
             iProcessingCount = iQuery->Count();
 			
-            if(iProcessingCount != iQueryQueue.Count())
+            if(iProcessingCount != iQueryQueue.Count() )
                 {
                 TN_DEBUG1( "CThumbAGProcessor::HandleQueryCompleted() some result items missing");
                 
                 RArray<TItemId> queryQueueDelta;
                 
-                TInt itemIndex(KErrNotFound);
-                
-                //search delta items which were queried, but not found
-                 for(TInt queryItem =0; queryItem < iQueryQueue.Count();queryItem++)
-                     {
-                     TBool found(EFalse);
-                     for(TInt queryResult = 0; queryResult < iQuery->Count(); queryResult++)
-                        {    
-                        const CMdEObject* object = &iQuery->Result(queryResult);
-                        
-                        if( iQueryQueue[queryItem] == object->Id())
+                    //search delta items which were queried, but not found
+                     for(TInt queryItem =0; queryItem < iQueryQueue.Count();queryItem++)
+                         {
+                         TBool found(EFalse);
+                         for(TInt queryResult = 0; queryResult < iQuery->Count(); queryResult++)
+                            {    
+                            const CMdEObject* object = &iQuery->Result(queryResult);
+                            
+                            if( iQueryQueue[queryItem] == object->Id())
+                                {
+                                found = ETrue;
+                                break;
+                                }
+                            }
+                             
+                         if(!found)
+                             {
+                             TN_DEBUG2( "CThumbAGProcessor::HandleQueryCompleted() %d missing from query results", iQueryQueue[queryItem] );
+                             
+                             // ignore if fails
+                             queryQueueDelta.InsertInOrder(iQueryQueue[queryItem], CompareId);
+                             }
+                         }
+                     
+                     TN_DEBUG2( "CThumbAGProcessor::HandleQueryCompleted() missing items found %d", queryQueueDelta.Count()); 
+                     //cleanup from previous queue it item is not found from MDS
+                     while(queryQueueDelta.Count())
+                         {
+                         TThumbnailGenerationItem item;
+                         item.iItemId = queryQueueDelta[0];
+                         TInt itemIndex = iQueryQueue.FindInOrder(item.iItemId, CompareId);
+                         
+                         if(itemIndex >= 0)
+                             {
+                             TN_DEBUG2( "CThumbAGProcessor::HandleQueryCompleted() remove %d from iQueryQueue", queryQueueDelta[0]);
+                             iQueryQueue.Remove( itemIndex );
+                             
+                             //remove from procesing queue
+                             itemIndex = iGenerationQueue.FindInOrder(item, Compare);
+                             
+                             if(itemIndex >= 0)
+                                 {
+                                 
+                                 if( iUnknown )
+                                     {
+                                     TN_DEBUG2( "CThumbAGProcessor::HandleQueryCompleted() mark %d as EGenerationItemTypeNotFound in iGenerationQueue", queryQueueDelta[0]);
+                                     //mark to be removed, cleanup is done below
+                                     iGenerationQueue[itemIndex].iItemType = EGenerationItemTypeNotFound;
+                                     }
+                                 else
+                                     {
+                                     TN_DEBUG2( "CThumbAGProcessor::HandleQueryCompleted() remove %d from iGenerationQueue", queryQueueDelta[0]);
+                                     iGenerationQueue.Remove( itemIndex );
+                                     }
+                                 }
+                             }
+                         queryQueueDelta.Remove(0);
+                         }
+                     queryQueueDelta.Close();
+                    }
+
+                if(iUnknown)
+                    {
+                    for(TInt i = 0; i < iQuery->Count(); i++)
+                      {    
+                      const CMdEObject* object = &iQuery->Result(i);
+                     
+                      if(!object)
+                          {
+                          continue;
+                          }
+
+                          TThumbnailGenerationItem tempItem;
+                          tempItem.iItemId = object->Id();
+                          TInt itemIndex = iGenerationQueue.FindInOrder(tempItem, Compare);
+                                           
+                        if(itemIndex >= 0)
                             {
-                            found = ETrue;
-                            break;
+                            TThumbnailGenerationItem& item = iGenerationQueue[itemIndex]; 
+                            
+                            if(iGenerationQueue[itemIndex].iItemType == EGenerationItemTypeNotFound)
+                                {
+                                TN_DEBUG2( "CThumbAGProcessor::HandleQueryCompleted() remove EGenerationItemTypeNotFound %d item from iGenerationQueue", item.iItemId);
+                                iGenerationQueue.Remove(itemIndex);
+                                continue;
+                                }
+                            
+                                SetGenerationItemType(item, object->Def().Id());
+                                    
+                                if(item.iItemType == EGenerationItemTypeUnknown )
+                                  {
+                                  TN_DEBUG2( "CThumbAGProcessor::HandleQueryCompleted() remove unknown item %d", item.iItemId);
+                                  iGenerationQueue.Remove(itemIndex);
+                                  continue;
+                                  }
+                              
+                              item.iPlaceholder = object->Placeholder(); 
+                                      
                             }
                         }
-                         
-                     if(!found)
-                         {
-                         TN_DEBUG2( "CThumbAGProcessor::HandleQueryCompleted() missing from results item %d", iQueryQueue[queryItem] );
-                         
-                         // ignore if fails
-                         queryQueueDelta.InsertInOrder(iQueryQueue[queryItem], Compare);
-                         }
-                     }
-                 
-                 TN_DEBUG2( "CThumbAGProcessor::HandleQueryCompleted() missing items total count %d", queryQueueDelta.Count()); 
-                 //cleanup from previous queue it item is not found from MDS
-                 while(queryQueueDelta.Count())
-                     {
-                     itemIndex = iLastQueue->FindInOrder(queryQueueDelta[0], Compare);
-                     
-                     if(itemIndex >= 0)
-                         {
-                         TN_DEBUG2( "CThumbAGProcessor::HandleQueryCompleted() remove items %d", iQueryQueue[0]);
-                         iLastQueue->Remove( itemIndex );
-                         }
-                     queryQueueDelta.Remove(0);
-                     }
-                 queryQueueDelta.Close();
-                }
+                
+                        iQueryQueue.Reset();
+                        iProcessingCount = 0;
+                        iUnknown = EFalse;
+                    }
             
             // no results, reset query
-            if( !iProcessingCount)
+            if( !iProcessingCount )
                 {
                 delete iQuery;
                 iQuery = NULL;
-                iProcessingCount = 0;
                 iModify = EFalse;
                 }
             }
@@ -389,7 +499,7 @@
     }
 
 // -----------------------------------------------------------------------------
-// CThumbAGProcessor::ThumbnailReady()
+// CThumbAGProcessor::ThumbnailReady()d
 // -----------------------------------------------------------------------------
 //
 void CThumbAGProcessor::ThumbnailReady( TInt aError, MThumbnailData& /*aThumbnail*/,
@@ -399,12 +509,6 @@
     
     iActiveCount--;
     
-    if(iActiveCount <= 0)
-        {
-        iActiveCount = 0;
-        iActive = EFalse;
-        }
-    
     // TNM server died, delete session
     if( aError == KErrServerTerminated )
         {
@@ -442,12 +546,6 @@
     
         iActiveCount--;
         
-        if(iActiveCount <= 0)
-            {
-            iActiveCount = 0;
-            iActive = EFalse;
-            }
-    
         ActivateAO();
         }
     }
@@ -456,7 +554,7 @@
 // CThumbAGProcessor::SetMdESession()
 // ---------------------------------------------------------------------------
 //
-void CThumbAGProcessor::SetMdESession( CMdESession* aMdESession )
+void CThumbAGProcessor::SetMdESessionL( CMdESession* aMdESession )
     {
     TN_DEBUG1( "CThumbAGProcessor::SetMdESession() - begin" );
     
@@ -468,14 +566,22 @@
     if (err != KErrNone)
         {
         TN_DEBUG2( "CThumbAGProcessor::SetMdESession() GetDefaultNamespaceDefL() err = %d", err );
+        __ASSERT_DEBUG((iDefNamespace), User::Panic(_L("CThumbAGProcessor::SetMdESession() !iDefNamespace "), KErrBadHandle));
         }
-    
-    __ASSERT_DEBUG((iDefNamespace), User::Panic(_L("CThumbAGProcessor::SetMdESession() !iDefNamespace "), KErrBadHandle));
-       
-    //do async init
-    iInit = ETrue;
-    
-	ActivateAO();
+    else
+        {
+        iImageObjectDef = &iDefNamespace->GetObjectDefL( MdeConstants::Image::KImageObject );
+        __ASSERT_DEBUG((iImageObjectDef), User::Panic(_L("CThumbAGProcessor::SetMdESession() !iDefNamespace "), KErrBadHandle));
+        iVideoObjectDef = &iDefNamespace->GetObjectDefL( MdeConstants::Video::KVideoObject );
+        __ASSERT_DEBUG((iVideoObjectDef), User::Panic(_L("CThumbAGProcessor::SetMdESession() !iVideoObjectDef "), KErrBadHandle));
+        iAudioObjectDef = &iDefNamespace->GetObjectDefL( MdeConstants::Audio::KAudioObject );
+        __ASSERT_DEBUG((iAudioObjectDef), User::Panic(_L("CThumbAGProcessor::SetMdESession() !iAudioObjectDef "), KErrBadHandle));
+        
+        //do async init
+        iInit = ETrue;
+
+        ActivateAO();
+        }
     }
 
 // ---------------------------------------------------------------------------
@@ -483,11 +589,13 @@
 // ---------------------------------------------------------------------------
 //
 void CThumbAGProcessor::AddToQueueL( TObserverNotificationType aType, 
+                                    TThumbnailGenerationItemType aItemType,
                                     const RArray<TItemId>& aIDArray, 
                                     const RPointerArray<HBufC>& aObjectUriArray,
                                     TBool /*aPresent*/ )
     {
     TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() - begin" );
+    
 
     // update queues
     if (aType == ENotifyAdd)
@@ -496,12 +604,18 @@
         
         for (int i=0; i<aIDArray.Count(); i++)
             {
-            // do not to append to Add queue if exist already in Add or 2nd Add queue (just processed)     
-            if (iAddQueue.FindInOrder(aIDArray[i], Compare) == KErrNotFound && 
-                i2ndRoundGenerateQueue.FindInOrder(aIDArray[i], Compare) == KErrNotFound)
+            TThumbnailGenerationItem item;
+            item.iItemId = aIDArray[i];      
+            item.iItemType = aItemType;
+            
+            SetGenerationItemType(item, aItemType);
+            
+            if(iPHHarvesting)
                 {
-                User::LeaveIfError(iAddQueue.InsertInOrder(aIDArray[i], Compare));    
+                item.iPlaceholder = ETrue;
                 }
+
+            AppendProcessingQueue( item );
             }
         }
     else if (aType == ENotifyModify)
@@ -513,19 +627,23 @@
             TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() - PH  harvesting active, treat like add" );
             for (int i=0; i<aIDArray.Count(); i++)
                 {
-                TInt itemIndex = iPlaceholderQueue.FindInOrder(aIDArray[i], Compare);
+                TThumbnailGenerationItem item;
+                item.iItemId = aIDArray[i];
+                
+                TInt itemIndex = iGenerationQueue.FindInOrder(item, Compare);
                                 
                 if (itemIndex >= 0)
                     {
-                    TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() - remove from placeholder queue");
-                    iPlaceholderQueue.Remove( itemIndex );
+                    TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() - set as non-placeholder");
+                    iGenerationQueue[itemIndex].iPlaceholder = EFalse;
                     }
-                
-                if(iAddQueue.FindInOrder(aIDArray[i], Compare) == KErrNotFound && 
-                   i2ndRoundGenerateQueue.FindInOrder(aIDArray[i], Compare) == KErrNotFound)
+                else
                     {
-                    TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() - append to add queue");
-                    User::LeaveIfError(iAddQueue.InsertInOrder(aIDArray[i], Compare));
+                    TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() - append");
+
+                     item.iPlaceholder = EFalse;
+                     SetGenerationItemType( item, 0 );
+                     AppendProcessingQueue( item );
                     }
                 }
             }
@@ -537,75 +655,89 @@
             
             for (int i=0; i<aIDArray.Count(); i++)
                 {
-                itemIndex = iPlaceholderQueue.FindInOrder(aIDArray[i], Compare);
+                TThumbnailGenerationItem item;
+                item.iItemId = aIDArray[i];
+                
+                itemIndex = iGenerationQueue.FindInOrder(item, Compare);
                 
                 if (itemIndex >= 0)
                     {
-                    TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() - placeholder modify, remove from placeholder queue");
-                    iPlaceholderQueue.Remove( itemIndex );
+                    if( iGenerationQueue[itemIndex].iPlaceholder )
+                        {
+                        TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() - placeholder modify");
+                        iGenerationQueue[itemIndex].iPlaceholder = EFalse;
+                        }
+                    else
+                        {
+                        TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() - real modify");
+                        iGenerationQueue[itemIndex].iItemAction = EGenerationItemActionModify;
+                        SetForceRun( ETrue );
+                        }
                     }
                 else
                     {
-                    TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() - real modify");
-                    itemIndex = iAddQueue.FindInOrder(aIDArray[i], Compare);
-                                    
-                    if (itemIndex >= 0)
-                        {
-                        TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() - remove from add queue");
-                        iAddQueue.Remove( itemIndex );
-                        }
-					else
-						{						
-						itemIndex = i2ndRoundGenerateQueue.FindInOrder(aIDArray[i], Compare);
-                                    
-	                    if (itemIndex >= 0)
-	                        {
-	                        TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() - remove from 2nd round add queue");
-	                        i2ndRoundGenerateQueue.Remove( itemIndex );
-	                        }
-					}
-                    
-                    TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() - append to modify queue");
-                    User::LeaveIfError(iModifyQueue.InsertInOrder(aIDArray[i], Compare));
-                    
-                    SetForceRun( ETrue );
-                    } 
+                    TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() - append");
+                    SetGenerationItemType( item, 0 );
+                    item.iPlaceholder = EFalse;
+                    AppendProcessingQueue( item );
+                    }
                 }
             }
         }
-        else if (aType == ENotifyRemove)
+        else if (aType == ENotifyRemove && aItemType == EGenerationItemTypeAny)
             {
             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.FindInOrder(aIDArray[i], Compare);
-                if(itemIndex >= 0)
-                    {
-                    iAddQueue.Remove(itemIndex);
-                    }
-    
-                // ..and Modify Queue
-                itemIndex = iModifyQueue.FindInOrder(aIDArray[i], Compare);
+                TThumbnailGenerationItem item;
+                item.iItemId = aIDArray[i];
+
+                TInt itemIndex = iGenerationQueue.FindInOrder(item, Compare);
+                
                 if(itemIndex >= 0)
                     {
-                    iModifyQueue.Remove(itemIndex);
+                    iGenerationQueue[itemIndex].iItemAction = EGenerationItemActionDelete;
+                    delete iGenerationQueue[itemIndex].iUri;
+                    iGenerationQueue[itemIndex].iUri = NULL;
+                    
+                    if( aObjectUriArray[i])
+                        {
+                        iGenerationQueue[itemIndex].iUri = aObjectUriArray[i]->AllocL();
+                        }
+                    else
+                        {
+                        //invalid URI remove from processing queue
+                        iGenerationQueue.Remove(itemIndex);
+                        }
                     }
-                }
-            
-            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); 
+                else
+                    {
+                    TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() - append");
+                    item.iItemAction = EGenerationItemActionDelete;
+                    delete item.iUri;
+                    item.iUri = NULL;
+                    
+                    if( aObjectUriArray[i])
+                        {
+                        item.iUri = aObjectUriArray[i]->AllocL();
+                        CleanupStack::PushL( item.iUri );
+                        User::LeaveIfError( iGenerationQueue.InsertInOrder(item, Compare) );
+                        CleanupStack::Pop();
+                        }
+                    
+                    //owned by item
+                    item.iUri = NULL;
+                    }
+                
+                TN_DEBUG2( "CThumbAGProcessor::AddToQueueL() - %S", aObjectUriArray[i]); 
                 }
             }
 #ifdef _DEBUG
         else
             {
 	        TN_DEBUG1( "CThumbAGProcessor::AddToQueueL() -  should not come here" );
+	        __ASSERT_DEBUG((EFalse), User::Panic(_L("CThumbAGProcessor::AddToQueueL()"), KErrArgument));
 	        User::Leave( KErrArgument );
             }
 #endif
@@ -635,8 +767,8 @@
     TInt64 modifiedVal = 0;
     
     CMdEProperty* orientation = NULL;
-    CMdEObjectDef& imageObjectDef = iDefNamespace->GetObjectDefL( MdeConstants::Image::KImageObject );       
-    TInt orientErr = aObject->Property( imageObjectDef.GetPropertyDefL( MdeConstants::Image::KOrientationProperty ), orientation, 0 );
+       
+    TInt orientErr = aObject->Property( iImageObjectDef->GetPropertyDefL( MdeConstants::Image::KOrientationProperty ), orientation, 0 );
     
     if (orientErr == KErrNone)
         {
@@ -661,6 +793,20 @@
             //generate both if needed
             TN_DEBUG1( "CThumbAGProcessor::CreateThumbnailsL() EOptimizeForQuality ");
             iTMSession->SetQualityPreferenceL( CThumbnailManager::EOptimizeForQuality );
+            
+            TN_DEBUG2( "CThumbAGProcessor::CreateThumbnailsL() - 2nd round add remove from queue", aObject->Id() );
+                        
+            TThumbnailGenerationItem item;
+            item.iItemId = aObject->Id();
+            TInt itemIndex = iGenerationQueue.FindInOrder(item, Compare);
+            
+            if(itemIndex >=0 )
+                {
+                if(iGenerationQueue[itemIndex].iItemAction == EGenerationItemAction2ndAdd)
+                    {
+                    iGenerationQueue.Remove(itemIndex);
+                    }
+                }
             }
 		// 1st roung generation
         else
@@ -669,27 +815,30 @@
             TN_DEBUG1( "CThumbAGProcessor::CreateThumbnailsL() EOptimizeForQualityWithPreview");
             iTMSession->SetQualityPreferenceL( CThumbnailManager::EOptimizeForQualityWithPreview );
             
-            CMdEObjectDef& videoObjectDef = iDefNamespace->GetObjectDefL( MdeConstants::Video::KVideoObject );
+            // add item to 2nd round queue 
+            TN_DEBUG2( "CThumbAGProcessor::CreateThumbnailsL() - 1st round add/modify, append to 2nd round queue", aObject->Id() );
             
-            // add item to 2nd round queue 
-            if(iLastQueue == &iAddQueue || iLastQueue == &iModifyQueue)
+            TThumbnailGenerationItem item;
+            item.iItemId = aObject->Id();
+            TInt itemIndex = iGenerationQueue.FindInOrder(item, Compare);
+            
+            if(itemIndex >=0 )
                 {
-                TN_DEBUG2( "CThumbAGProcessor::CreateThumbnailsL() - 1st round add/modify, append to 2nd round queue", aObject->Id() );
-                if(i2ndRoundGenerateQueue.FindInOrder(aObject->Id(), Compare) == KErrNotFound)
+                if(iGenerationQueue[itemIndex].iItemAction == EGenerationItemActionModify)
                     {
-                    // ignore if fails
-                    i2ndRoundGenerateQueue.InsertInOrder(aObject->Id(), Compare);
+                    iGenerationQueue.Remove(itemIndex);
+                    }
+                //change 1st round item for 2nd round processing
+                //2nd round item can be deleted
+                else if(iGenerationQueue[itemIndex].iItemAction == EGenerationItemActionAdd)
+                    {
+                    iGenerationQueue[itemIndex].iItemAction = EGenerationItemAction2ndAdd;
+                    }
+                else
+                    {
+                    iGenerationQueue.Remove(itemIndex);
                     }
                 }
-            
-		   // Symbian^4 specific --->
-           if( imageObjectDef.Id() != aObject->Def().Id()  )
-                {
-                TN_DEBUG1( "CThumbAGProcessor::CreateThumbnailsL() 1st round not image");
-                ActivateAO();
-                return;
-                }
-			//Symbian^4 specific <---
             }
 
         // run as lower priority than getting but higher that creating thumbnails
@@ -700,13 +849,11 @@
             TN_DEBUG2( "CThumbAGProcessor::CreateThumbnailsL, iTMSession error == %d", err );
             
             iSessionDied = ETrue;
-            iActive = EFalse;
             ActivateAO();
             } 
         else
             {
             iActiveCount++;
-            iActive = ETrue;
             }
         }
     else
@@ -721,14 +868,14 @@
 // CThumbAGProcessor::QueryL()
 // ---------------------------------------------------------------------------
 //
-void CThumbAGProcessor::QueryL( RArray<TItemId>& aIDArray )
+void CThumbAGProcessor::QueryL(/*RArray<TItemId>& aIDArray*/TThumbnailGenerationItemAction aAction  )
     {
     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)
+    if(!iMdESession  || !iDefNamespace || iShutdown)
         {
         return;
         }
@@ -736,7 +883,6 @@
 	//reset query queue
     iQueryQueue.Reset();
 	//set reference to current pprocessing queue
-    iLastQueue = &aIDArray;
     
     iQueryReady = EFalse;
 
@@ -748,18 +894,64 @@
         }
     
     //move ID from source queue to Query queue
-    TInt maxCount = aIDArray.Count();
+    TInt maxCount = iGenerationQueue.Count();
         
-    TN_DEBUG3( "CThumbAGProcessor::QueryL() - fill begin aIDArray == %d, iQueryQueue == %d", aIDArray.Count(), iQueryQueue.Count() );
+    TN_DEBUG3( "CThumbAGProcessor::QueryL() - fill begin iGenerationQueue == %d, iQueryQueue == %d", iGenerationQueue.Count(), iQueryQueue.Count() );
+    
     
-    for(TInt i=0; i < KMaxQueryItems && i < maxCount; i++)
+    TInt itemCount(0);
+    for(TInt i=0; itemCount < KMaxQueryItems && i < maxCount; i++)
         {
-        TN_DEBUG2( "CThumbAGProcessor::QueryL() - fill %d", aIDArray[0] );
-        iQueryQueue.InsertInOrder(aIDArray[0], Compare);
-        aIDArray.Remove(0);
+        TInt itemIndex(KErrNotFound);
+        switch(aAction)
+            {
+            //1st round items
+            case EGenerationItemActionAdd:
+                if(iGenerationQueue[i].iItemAction == aAction )
+                    {
+                    itemIndex = i;
+                    }
+                break;
+            case EGenerationItemActionModify:
+                if( iGenerationQueue[i].iItemAction == aAction )
+                    {
+                    itemIndex = i;
+                    }
+                break;
+            case EGenerationItemAction2ndAdd:
+                if( iGenerationQueue[i].iItemAction == aAction )
+                    {
+                    itemIndex = i;
+                    }
+                break;
+            //unknown stuff
+            case EGenerationItemActionResolveType:
+                if( iGenerationQueue[i].iItemType == EGenerationItemTypeUnknown )
+                    {
+                    itemIndex = i;
+                    }
+                break;
+            default:
+                break;
+            };
+        
+        if( itemIndex >= 0 )
+            {
+            TN_DEBUG2( "CThumbAGProcessor::QueryL() - fill %d", iGenerationQueue[itemIndex].iItemId );        
+            iQueryQueue.InsertInOrder(iGenerationQueue[itemIndex].iItemId, CompareId);
+            itemCount++;
+            }
         }
     
-    TN_DEBUG3( "CThumbAGProcessor::QueryL() - fill end aIDArray == %d, iQueryQueue == %d", aIDArray.Count(), iQueryQueue.Count() );
+    if(!itemCount)
+        {
+        TN_DEBUG1( "CThumbAGProcessor::QueryL() - empty query, cancel?!");
+        iQueryActive = EFalse;
+        __ASSERT_DEBUG((iMdESession), User::Panic(_L("CThumbAGProcessor::QueryL() empty! "), KErrNotFound));
+        return;
+        }
+    
+    TN_DEBUG3( "CThumbAGProcessor::QueryL() - fill end iGenerationQueue == %d, iQueryQueue == %d", iGenerationQueue.Count(), iQueryQueue.Count() );
     
     CMdEObjectDef& objDef = iDefNamespace->GetObjectDefL( MdeConstants::Object::KBaseObject );
     iQuery = iMdESession->NewObjectQueryL( *iDefNamespace, objDef, this );
@@ -774,7 +966,7 @@
     CleanupStack::Pop( &iQueryQueue );
     
     // add object type conditions 
-    if (!iModify)
+    if (!(iModify || iUnknown))
         {
         CMdELogicCondition& objDefCondition = rootCondition.AddLogicConditionL( ELogicConditionOperatorOr );
         
@@ -813,7 +1005,7 @@
     __ASSERT_DEBUG((iMdESession), User::Panic(_L("CThumbAGProcessor::QueryPlaceholdersL() !iMdeSession "), KErrBadHandle));
     __ASSERT_DEBUG((iDefNamespace), User::Panic(_L("CThumbAGProcessor::QueryPlaceholdersL() !iDefNamespace "), KErrBadHandle));
     
-    if(!iMdESession  || !iDefNamespace)
+    if(!iMdESession  || !iDefNamespace || iShutdown)
          {
          return;
          }
@@ -858,7 +1050,7 @@
     audioPHObjectCondition.SetPlaceholderOnly( ETrue );
     audioPHObjectCondition.SetNotPresent( ETrue );
     
-    iQueryPlaceholders->FindL(KMaxTInt, KMaxQueryItems2);   
+    iQueryPlaceholders->FindL(KMaxTInt, KMaxQueryBatchSize);   
    
     TN_DEBUG1( "CThumbAGProcessor::QueryPlaceholdersL - end" );
     }
@@ -871,6 +1063,12 @@
 void CThumbAGProcessor::RunL()
     {
     TN_DEBUG1( "CThumbAGProcessor::RunL() - begin" );
+	
+	if(iShutdown)
+		{
+        TN_DEBUG1( "CThumbAGProcessor::RunL() - shutdown" );
+		return;
+		}
     
     if (iSessionDied)
         {
@@ -886,11 +1084,8 @@
         iInit = EFalse;
         iInit2 = ETrue;
 
-        iAddQueue.Reset();
-        iModifyQueue.Reset();
-        iRemoveQueue.ResetAndDestroy();
+        iGenerationQueue.Reset();
         iQueryQueue.Reset();
-        iPlaceholderQueue.Reset();
         
         TRAP_IGNORE(QueryPlaceholdersL());
 		//query all items after PH query
@@ -912,13 +1107,20 @@
         err = iHarvesterClient.Connect();
         TN_DEBUG2( "CThumbAGProcessor::RunL() iHarvesterClient connect err = %d", err);
         
-        __ASSERT_DEBUG((err==KErrNone), User::Panic(_L("CThumbAGProcessor::RunL(), !iHarvesterClient "), err));
+        __ASSERT_DEBUG((err == KErrNone), User::Panic(_L("CThumbAGProcessor::RunL(), !iHarvesterClient "), err));
         
         if(  err == KErrNone )
             {
             TN_DEBUG1( "CThumbAGProcessor::RunL() add iHarvesterClient observer");
-            err = iHarvesterClient.AddHarvesterEventObserver( *this, EHEObserverTypeOverall | EHEObserverTypeMMC | EHEObserverTypePlaceholder, KMaxTInt );
+            err = iHarvesterClient.AddHarvesterEventObserver( *this, EHEObserverTypeOverall | EHEObserverTypeMMC | EHEObserverTypePlaceholder, 10 );
             TN_DEBUG2( "CThumbAGProcessor::RunL() iHarvesterClient observer err = %d", err);
+            
+            if( !err )
+                {
+                TN_DEBUG1( "CThumbAGProcessor::RunL() add iHarvesterClient observer failed");
+                // if we fail observer harvester, fake it
+                iHarvesterActivated = ETrue;
+                }
             __ASSERT_DEBUG((err==KErrNone), User::Panic(_L("CThumbAGProcessor::RunL(), !iHarvesterClient "), err));
             }
 #endif
@@ -942,7 +1144,6 @@
     if (!iTMSession)
         {
         TN_DEBUG1( "CThumbAGProcessor::RunL() - open TNM session");
-        iActive = EFalse;
         TRAPD( err, iTMSession = CThumbnailManager::NewL( *this ) );
 		
         if (err != KErrNone)
@@ -959,19 +1160,11 @@
         }    
    
     // do not run if request is already issued to TNM server even if forced
-    if( iActive)
+    if(iActiveCount >= KMaxDaemonRequests)
         {
-        if(iActiveCount >= KMaxDaemonRequests)
-            {
-            TN_DEBUG1( "CThumbAGProcessor::RunL() - waiting for previous to complete, abort..." );
-            return;
-            }
+        TN_DEBUG1( "CThumbAGProcessor::RunL() - waiting for previous to complete, abort..." );
+        return;
         }
-    else
-        {
-        iActiveCount = 0;   
-        }
-    
     
     //force run can proceed from this point
 #ifdef _DEBUG
@@ -1029,21 +1222,16 @@
             
             if ( object )
                 {
-                TInt itemIndex = iLastQueue->FindInOrder(object->Id(), Compare);
-                if(itemIndex >= 0)
-                    {
-                    iLastQueue->Remove(itemIndex);
-                    }
-				
                 //process one item at once
                 //remove item from queryQueue when request is issued 
-                itemIndex = iQueryQueue.FindInOrder(object->Id(), Compare);
+ 
+                TInt itemIndex = iQueryQueue.FindInOrder(object->Id(), CompareId);
                 if(itemIndex >= 0)
                     {
                     iQueryQueue.Remove(itemIndex);
                     }
             
-                TRAP( err, CreateThumbnailsL(object) );
+                TRAP( err, CreateThumbnailsL( object ) );
                 TN_DEBUG2( "CThumbAGProcessor::RunL(), CreateThumbnailsL error == %d", err );
                 __ASSERT_DEBUG((err==KErrNone), User::Panic(_L("CThumbAGProcessor::RunL(), CreateThumbnailsL() "), err));
                 }
@@ -1071,7 +1259,7 @@
     else if( iQueryActive )
         {
 		//state mismatch
-        if(iForceRun && !iModify)
+        if(iForceRun && !(iModify || iUnknown))
             {
 			//cancel query and move items back to original processing queue
             DeleteAndCancelQuery(ETrue);
@@ -1082,10 +1270,20 @@
             TN_DEBUG1( "CThumbAGProcessor::RunL() - waiting for query to complete, abort..." );
             }    
         }
+    else if ( iUnknownItemCount > 0 )
+        {
+        TN_DEBUG1( "void CThumbAGProcessor::RunL() unknown items in queue");
+        
+        i2ndRound = EFalse;
+        iModify = EFalse;
+        iUnknown = ETrue;
+        iQueryActive = ETrue;
 
+        QueryL( EGenerationItemActionResolveType );
+       }
     // no items in query queue, start new
     // select queue to process, priority by type
-    else if ( iModifyQueue.Count() > 0 )
+    else if ( iModifyItemCount > 0 )
         {
         TN_DEBUG1( "void CThumbAGProcessor::RunL() update thumbnails");
         
@@ -1094,54 +1292,77 @@
         // query for object info
         iQueryActive = ETrue;
         iModify = ETrue;
-        QueryL( iModifyQueue );
+        iUnknown = EFalse;
+        QueryL( EGenerationItemActionModify );
        }
-    else if ( iAddQueue.Count() > 0 )
+    else if ( iAddItemCount > 0 )
         {
         TN_DEBUG1( "void CThumbAGProcessor::RunL() update 1st round thumbnails");
         
         i2ndRound = EFalse;
-        
+        iUnknown = EFalse;
         // query for object info
         iQueryActive = ETrue;
         
-        QueryL( iAddQueue );     
+        QueryL( EGenerationItemActionAdd );     
         }
-    else if ( iRemoveQueue.Count() > 0 )
+    else if ( iDeleteItemCount > 0 )
         {
         TN_DEBUG1( "void CThumbAGProcessor::RunL() delete thumbnails");
-
         i2ndRound = EFalse;
-        
+        iUnknown = 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 );
+            TInt itemIndex(KErrNotFound);
+                                
+            for(TInt i=0;i<iGenerationQueue.Count() || itemIndex == KErrNotFound;i++)
+                {
+                if(iGenerationQueue[i].iItemAction == EGenerationItemActionDelete)
+                    {
+                    itemIndex = i;
+                    }
                 }
-            iRemoveQueue.Remove( 0 );
-            delete source;
-            delete uri;
-            
-            iActiveCount++;
-            iActive = ETrue;
+        
+            if(itemIndex >= 0)
+                {
+                if(!iGenerationQueue[itemIndex].iUri)
+                    {
+                    //URI is invalid
+                    TN_DEBUG1( "void CThumbAGProcessor::RunL() unable to delete URI inbalid");
+                    iGenerationQueue.Remove( itemIndex );
+                    ActivateAO();
+                    return;
+                    }
+
+                TN_DEBUG2( "void CThumbAGProcessor::RunL() delete %S",  iGenerationQueue[itemIndex].iUri);
+                CThumbnailObjectSource* source = NULL;                
+                TRAPD(err,  source = CThumbnailObjectSource::NewL( *iGenerationQueue[itemIndex].iUri, KNullDesC));
+                   
+                if(err == KErrNone)
+                    {
+                    iTMSession->DeleteThumbnails( *source );
+                    }
+                delete source;
+                
+                delete iGenerationQueue[itemIndex].iUri;
+                iGenerationQueue[itemIndex].iUri = NULL;
+                iGenerationQueue.Remove( itemIndex );
+                
+                iActiveCount++;
+                }
             }
         }
-    else if( i2ndRoundGenerateQueue.Count() > 0)
+    else if( i2ndAddItemCount > 0)
         {
         TN_DEBUG1( "void CThumbAGProcessor::RunL() update 2nd round thumbnails");
             
         // query for object info
         iQueryActive = ETrue;
         i2ndRound = ETrue;
-        QueryL( i2ndRoundGenerateQueue );     
+        iUnknown = EFalse;
+        QueryL( EGenerationItemAction2ndAdd );     
         }
         
     TN_DEBUG1( "CThumbAGProcessor::RunL() - end" );
@@ -1170,18 +1391,22 @@
     //move remainig IDs in query queue back to original queue
     while(iQueryQueue.Count())
         {
-        if(aRestoreItems && iLastQueue)
+        if(!aRestoreItems )
             {
-            if(iLastQueue->FindInOrder(iQueryQueue[0], Compare) == KErrNotFound)
+            TThumbnailGenerationItem item;
+            item.iItemId = iQueryQueue[0];
+            TInt itemIndex = iGenerationQueue.FindInOrder(item, Compare);
+                
+            if(itemIndex >= 0)
                 {
-                //ignore if fails
-                iLastQueue->InsertInOrder(iQueryQueue[0], Compare);
+                delete iGenerationQueue[itemIndex].iUri;
+                iGenerationQueue[itemIndex].iUri = NULL;
+                iGenerationQueue.Remove(itemIndex);
                 }
             }
         iQueryQueue.Remove(0);
         }
-    iLastQueue = NULL;
-    
+
     TN_DEBUG1( "CThumbAGProcessor::DeleteAndCancelQuery() out" );
     }
 
@@ -1197,10 +1422,20 @@
 void CThumbAGProcessor::HarvestingUpdated( 
          HarvesterEventObserverType aHEObserverType, 
          HarvesterEventState aHarvesterEventState,
-         TInt /*aItemsLeft*/ )
+         TInt aItemsLeft )
     {
-    TN_DEBUG3( "CThumbAGProcessor::HarvestingUpdated -- start() aHEObserverType = %d, aHarvesterEventState = %d", aHEObserverType, aHarvesterEventState );
+    TN_DEBUG4( "CThumbAGProcessor::HarvestingUpdated -- start() aHEObserverType = %d, aHarvesterEventState = %d, aItemsLeft = %d", aHEObserverType, aHarvesterEventState, aItemsLeft );
+    
+	if(iShutdown)
+        {
+        return;
+        }
 
+    if(!iHarvesterActivated)
+        {
+        iHarvesterActivated = ETrue;
+        }
+    
     #ifdef _DEBUG
     if( aHEObserverType == EHEObserverTypePlaceholder)
         {
@@ -1210,6 +1445,10 @@
         {
         TN_DEBUG1( "CThumbAGProcessor::HarvestingUpdated -- type EHEObserverTypeOverall");
         }
+    else if( aHEObserverType == EHEObserverTypeMMC)
+        {
+        TN_DEBUG1( "CThumbAGProcessor::HarvestingUpdated -- type EHEObserverTypeMMC");
+        }
     #endif
     
     //placeholder harvesting
@@ -1245,8 +1484,29 @@
                 {
                 TN_DEBUG1( "CThumbAGProcessor::HarvestingUpdated -- MDS placeholder harvesting finished");
                 TRAP_IGNORE(QueryPlaceholdersL());
+                iPHHarvestingItemsLeftTemp = 0;
                 }
             }
+        
+        //restart mount timout if PH item count is increasing durin MMC harvesting 
+        if(iMMCHarvesting && iPHHarvesting && aItemsLeft > iPHHarvestingItemsLeftTemp)
+          {
+          //if items count increasing, restart mount timeout 
+            TN_DEBUG1( "CThumbAGProcessor::HarvestingUpdated -- PH count increasing, restart mount timeout");
+            
+           if(iMountTimer->IsActive())
+              {
+              iMountTimer->Cancel();
+              }
+
+            iMountTimer->Start( KMountTimeout, KMountTimeout, TCallBack(MountTimerCallBack, this));
+          }
+          
+        //we are interestead of only PHs during MMC harvesting
+        if( iMMCHarvesting )
+            {
+            iPHHarvestingItemsLeftTemp = aItemsLeft;
+            }
         }
     //overall harvesting
     else if ( aHEObserverType == EHEObserverTypeOverall)
@@ -1275,7 +1535,7 @@
             
             if( iHarvesting )
                 {
-                TN_DEBUG1( "CThumbAGProcessor::HarvestingUpdated -- MDS harvesterin started");
+                TN_DEBUG1( "CThumbAGProcessor::HarvestingUpdated -- MDS harvesting started");
                 CancelTimeout();
                 }
             else
@@ -1283,6 +1543,11 @@
                 TN_DEBUG1( "CThumbAGProcessor::HarvestingUpdated -- MDS harvesting finished ");
                 // continue processing if needed
                 StartTimeout();
+                
+                if(iMountTimer->IsActive())
+                    {
+                    iMountTimer->Cancel();
+                    }
                 }
             }
         }
@@ -1314,17 +1579,29 @@
             if( iMMCHarvesting )
                 {
                 TN_DEBUG1( "CThumbAGProcessor::HarvestingUpdated -- MDS MMC harvesterin started");
-                if(iPreviousItemsLeft != KErrNotReady)
-                    {
-                    iPreviousItemsLeft = KErrNotReady;
-                    RProperty::Set(KTAGDPSNotification, KDaemonProcessing, iPreviousItemsLeft);
-                    }
+                UpdatePSValues(EFalse, ETrue);
+                iMMCHarvestingItemsLeftTemp = 0;
                 }
             else
                 {
                 TN_DEBUG1( "CThumbAGProcessor::HarvestingUpdated -- MDS MMC harvesting finished ");
                 }
             }
+        
+        //restart mount timout if MMC item count is still increasing 
+        if(iMMCHarvesting && aItemsLeft > iMMCHarvestingItemsLeftTemp)
+            {
+              TN_DEBUG1( "CThumbAGProcessor::HarvestingUpdated -- MMC count increasing, restart mount timeout");
+              
+             if(iMountTimer->IsActive())
+                {
+                iMountTimer->Cancel();
+                }
+
+              iMountTimer->Start( KMountTimeout, KMountTimeout, TCallBack(MountTimerCallBack, this));
+            }
+        
+            iMMCHarvestingItemsLeftTemp = aItemsLeft;
         }
    
     TN_DEBUG4( "CThumbAGProcessor::HarvestingUpdated -- end() iHarvesting == %d, iPHHarvesting == %d iMMCHarvesting == %d ", iHarvesting, iPHHarvesting, iMMCHarvesting);
@@ -1339,7 +1616,7 @@
     TN_DEBUG1( "CThumbAGProcessor::StartTimeout()");
     CancelTimeout();
     
-    if(!iHarvesting && !iMPXHarvesting && !iPeriodicTimer->IsActive())
+    if(!iHarvesting && !iMPXHarvesting && !iPeriodicTimer->IsActive() && !iShutdown)
         {
         iPeriodicTimer->Start( KHarvestingCompleteTimeout, KHarvestingCompleteTimeout,
                 TCallBack(PeriodicTimerCallBack, this));
@@ -1370,16 +1647,10 @@
     {
     TN_DEBUG2( "CThumbAGrocessor::RunError() %d", aError);
     
-    UpdatePSValues();
+    UpdatePSValues(EFalse, EFalse);
         
     iActiveCount--;
     
-    if(iActiveCount <= 0)
-        {
-        iActiveCount = 0;
-        iActive = EFalse;
-        }
-    
 	ActivateAO();
 	
     // nothing to do
@@ -1392,23 +1663,17 @@
 //
 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
+    UpdateItemCounts();
     
     if(iFormatting)
         {
         TN_DEBUG1( "CThumbAGProcessor::ActivateAO() - FORMATTING - DAEMON ON PAUSE");
         return;
         }
+    
         
     //check if forced run needs to continue
-    if (iModifyQueue.Count())
+    if ( iModifyItemCount || iUnknownItemCount > 0 )
         {
         SetForceRun( ETrue );
         }
@@ -1418,7 +1683,7 @@
         SetForceRun( EFalse );
         }
     
-    if( !IsActive() && ((!iActive && !iQueryActive) || iForceRun ))
+    if( !IsActive() && !iShutdown && ((iActiveCount == 0 && !iQueryActive) || iForceRun ))
         {
         TN_DEBUG1( "CThumbAGProcessor::ActivateAO() - Activated");
         SetActive();
@@ -1426,7 +1691,7 @@
         User::RequestComplete( statusPtr, KErrNone );
         }
 
-    UpdatePSValues();
+    UpdatePSValues(EFalse, EFalse);
     }
 
 // ---------------------------------------------------------------------------
@@ -1515,60 +1780,33 @@
     {
     TN_DEBUG2( "CThumbAGProcessor::RemoveFromQueues() aRemoveFromDelete == %d - begin", aRemoveFromDelete );
     
-    TInt itemIndex = KErrNotFound;
+    TInt itemIndex(KErrNotFound);
     
     for (int i=0; i< aIDArray.Count(); i++)
         {
+        TThumbnailGenerationItem item;
+        item.iItemId = aIDArray[i];
         TN_DEBUG2( "CThumbAGProcessor::RemoveFromQueues() - %d", aIDArray[i]);
 
-        itemIndex = iPlaceholderQueue.FindInOrder(aIDArray[i], Compare);                        
-        if(itemIndex >= 0)
-            {
-            iPlaceholderQueue.Remove(itemIndex);
-            TN_DEBUG1( "CThumbAGProcessor::RemoveFromQueues() - iPlaceholderQueue" );
-            }
-                
-        itemIndex = iAddQueue.FindInOrder(aIDArray[i], Compare);       
+        itemIndex = iGenerationQueue.FindInOrder(item, Compare);                        
         if(itemIndex >= 0)
             {
-            iAddQueue.Remove(itemIndex);
-            TN_DEBUG1( "CThumbAGProcessor::RemoveFromQueues() - iAddQueue" );
-            }
-
-        itemIndex = i2ndRoundGenerateQueue.FindInOrder(aIDArray[i], Compare);               
-        if(itemIndex >= 0)
-            {
-            i2ndRoundGenerateQueue.Remove(itemIndex);
-            TN_DEBUG1( "CThumbAGProcessor::RemoveFromQueues() - i2ndRoundGenerateQueue" );
+            delete iGenerationQueue[itemIndex].iUri;
+            iGenerationQueue[itemIndex].iUri = NULL;
+            iGenerationQueue.Remove(itemIndex);
+            TN_DEBUG1( "CThumbAGProcessor::RemoveFromQueues() - iGenerationQueue" );
             }
-        
-        itemIndex = iModifyQueue.FindInOrder(aIDArray[i], Compare);       
-        if(itemIndex >= 0)
-            {
-            iModifyQueue.Remove(itemIndex);
-            TN_DEBUG1( "CThumbAGProcessor::RemoveFromQueues() - iModifyQueue" );
-			 
-            if( iModifyQueue.Count() == 0)
-			    {
-			    SetForceRun( EFalse );
-		        }
-            }
-            
-        itemIndex = iQueryQueue.FindInOrder(aIDArray[i], Compare);                    
+                
+        itemIndex = iQueryQueue.FindInOrder(aIDArray[i], CompareId);                    
         if(itemIndex >= 0)
             {
             iQueryQueue.Remove(itemIndex);
             TN_DEBUG1( "CThumbAGProcessor::RemoveFromQueues() - iQueryQueue" );
             }
-         
-        itemIndex = iPlaceholderQueue.FindInOrder(aIDArray[i], Compare); 
-        if(itemIndex >= 0)
-        	{
-            iPlaceholderQueue.Remove(itemIndex);
-            TN_DEBUG1( "CThumbAGProcessor::RemoveFromQueues() - iPlaceholderQueue" );
-            }
         }
     
+    ActivateAO();
+    
     TN_DEBUG1( "CThumbAGProcessor::RemoveFromQueues() - end" );
     }
 	
@@ -1627,13 +1865,13 @@
     CMdELogicCondition& rootCondition = iQueryAllItems->Conditions();
     rootCondition.SetOperator( ELogicConditionOperatorOr );
     
-    CMdEObjectCondition& imagePHObjectCondition = rootCondition.AddObjectConditionL(imageObjDef);
+    CMdEObjectCondition& imageObjectCondition = rootCondition.AddObjectConditionL(imageObjDef);
     
-    CMdEObjectCondition& videoPHObjectCondition = rootCondition.AddObjectConditionL(videoObjDef);
+    CMdEObjectCondition& videoObjectCondition = rootCondition.AddObjectConditionL(videoObjDef);
     
-    CMdEObjectCondition& audioPHObjectCondition = rootCondition.AddObjectConditionL(audioObjDef);
+    CMdEObjectCondition& audioObjectCondition = rootCondition.AddObjectConditionL(audioObjDef);
     
-    iQueryAllItems->FindL(KMaxTInt, KMaxQueryItems2);  
+    iQueryAllItems->FindL(KMaxTInt, KMaxQueryBatchSize);  
     
     TN_DEBUG1( "CThumbAGProcessor::QueryAllItemsL - end" );
     }
@@ -1646,7 +1884,7 @@
 //
 void CThumbAGProcessor::HandleCollectionMessage( CMPXMessage* aMessage, TInt aError )
     {
-    if ( aError != KErrNone || !aMessage )
+    if ( aError != KErrNone || !aMessage || iShutdown )
         {
         return;
         }
@@ -1748,8 +1986,7 @@
         {
         iIdle = ETrue; 
         
-        if(iAddQueue.Count() + iModifyQueue.Count() + iRemoveQueue.Count() + 
-           iQueryQueue.Count() + i2ndRoundGenerateQueue.Count() > 0 )
+        if(iGenerationQueue.Count() > 0 )
             {
             ActivateAO();
             }
@@ -1801,55 +2038,90 @@
 // Update KItemsleft PS value if changed
 // ---------------------------------------------------------------------------
 //
-void CThumbAGProcessor::UpdatePSValues(const TBool aDefine)
+void CThumbAGProcessor::UpdatePSValues(const TBool aDefine, const TBool aForce)
     {
-    TInt itemsLeft = iModifyQueue.Count() + iAddQueue.Count();
-    TBool daemonProcessing = EFalse;
+    TInt itemsLeft(KErrNotReady);
+    TBool daemonProcessing = ETrue;
     
-    if(itemsLeft + i2ndRoundGenerateQueue.Count() + iRemoveQueue.Count() > 0 )
+    if(iShutdown)
+        {
+        RProperty::Set(KTAGDPSNotification, KDaemonProcessing, EFalse);
+        RProperty::Set(KTAGDPSNotification, KItemsleft, 0 );
+        return;
+        }
+   
+    if(aDefine)
         {
-        daemonProcessing = ETrue;
-        }
-    
-    //adjust items left to containing also items not yet processed but removed from queue under processing
-    if((iLastQueue == &iModifyQueue || iLastQueue == &iAddQueue) && !i2ndRound)
-        {
-        itemsLeft +=iQueryQueue.Count();
+        TInt ret = RProperty::Define(KTAGDPSNotification, KDaemonProcessing, RProperty::EInt);
+        
+        if( ret != KErrNone )
+            {
+            TN_DEBUG2( "CThumbAGProcessor::UpdatePSValues() define KDaemonProcessing ret = %d", ret);
+            }
+
+        ret = RProperty::Define(KTAGDPSNotification, KItemsleft, RProperty::EInt);
+        
+        if( ret != KErrNone )
+            {
+            TN_DEBUG2( "CThumbAGProcessor::UpdatePSValues() define KItemsleft ret = %d", ret);
+            }
         }
     
-    //cancel 2nd round generarion when there is items in 1st round queues
-    if(itemsLeft && i2ndRound)
-        {
-        DeleteAndCancelQuery(ETrue);
-        i2ndRound = EFalse;
-        }
-        
-    TN_DEBUG2( "CThumbAGProcessor::UpdatePSValues() KItemsleft == %d", itemsLeft);
+        // set itemsleft = KErrNotReady (-18) and daemonProcessing = ETrue if
+        // - key is initalized
+        // - mount timer is pending
+        // - harvester observer is not yet activated
+        // - single unknown item exists in processing queue
+        // - forced
+       if( iMountTimer->IsActive() || aForce || aDefine  || iUnknownItemCount
+               || !iHarvesterActivated  )
+           {
+           daemonProcessing = ETrue;
+           itemsLeft = KErrNotReady;
+           }
+       else
+           {
+           itemsLeft = iAddItemCount + iModifyItemCount;
+           }
+       
+       TN_DEBUG2( "CThumbAGProcessor::UpdatePSValues() KItemsleft == %d", itemsLeft);
+           
+       //cancel 2nd round generarion when there is items in 1st round queues
+       if(iAddItemCount && i2ndRound)
+           {
+           DeleteAndCancelQuery(ETrue);
+           i2ndRound = EFalse;
+           }
     
-    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 );
-        }
+        if( iGenerationQueue.Count() )
+            {
+            daemonProcessing = ETrue;
+            }
+        
+        if( daemonProcessing != iPreviousDaemonProcessing)
+            {
+            TN_DEBUG2( "CThumbAGProcessor::UpdatePSValues() update KDaemonProcessing == %d", daemonProcessing);
+            iPreviousDaemonProcessing = daemonProcessing;
+            TInt ret = RProperty::Set(KTAGDPSNotification, KDaemonProcessing, daemonProcessing);
+            
+            if(ret != KErrNone )
+                {
+                TN_DEBUG3( "CThumbAGProcessor::UpdatePSValues() set KDaemonProcessing %d failed %d", daemonProcessing, ret);
+                }
+            }
+        
+        if( itemsLeft != iPreviousItemsLeft)
+            {
+            TN_DEBUG2( "CThumbAGProcessor::UpdatePSValues() update KItemsleft == %d", itemsLeft);
+            iPreviousItemsLeft = itemsLeft;
+            TInt ret = RProperty::Set(KTAGDPSNotification, KItemsleft, itemsLeft );
+            
+            if(ret != KErrNone )
+                {
+                TN_DEBUG3( "CThumbAGProcessor::UpdatePSValues() set KItemsleft %d failed %d", itemsLeft, ret);
+                }
+            }
+        
     }
 
 // ---------------------------------------------------------------------------
@@ -1857,10 +2129,189 @@
 // Comparison function for logaritmic use of queue arrays
 // ---------------------------------------------------------------------------
 //
-TInt CThumbAGProcessor::Compare(const TItemId& aLeft, const TItemId& aRight)
+
+TInt CThumbAGProcessor::Compare(const TThumbnailGenerationItem& aLeft, const TThumbnailGenerationItem& aRight)
+    {  
+    return (aLeft.iItemId - aRight.iItemId);
+    }
+
+TInt CThumbAGProcessor::CompareId(const TItemId& aLeft, const TItemId& aRight)
     {  
     return (aLeft - aRight);
     }
 
+void CThumbAGProcessor::UpdateItemCounts()
+    {
+    TN_DEBUG1( "CThumbAGProcessor::UpdateItemCounts()");
+    iModifyItemCount = 0;
+    iDeleteItemCount = 0;
+    iAddItemCount = 0;
+    iUnknownItemCount = 0;
+    i2ndAddItemCount = 0;
+    iPlaceholderItemCount=0;
+    iCameraItemCount =0;
+    iImageItemCount=0;
+    iVideoItemCount=0;
+    iAudioItemCount=0;
+    
+    for(TInt i=0; i < iGenerationQueue.Count(); i++)
+    {
+    TThumbnailGenerationItem& item = iGenerationQueue[i];
+    
+        if(item.iItemAction == EGenerationItemActionModify)
+            {
+            iModifyItemCount++;
+            }
+        
+        if(item.iItemAction == EGenerationItemActionDelete)
+            {
+            iDeleteItemCount++;
+            }
+        
+        if(item.iItemType == EGenerationItemTypeUnknown)
+            {
+            iUnknownItemCount++;
+            }
+        if(item.iItemAction == EGenerationItemAction2ndAdd)
+            {
+            i2ndAddItemCount++;
+            }
+        if(item.iPlaceholder)
+            {
+            iPlaceholderItemCount++;
+            }
+        if(item.iItemType == EGenerationItemTypeCamera)
+            {
+            iCameraItemCount++;
+            }
+        if(item.iItemAction == EGenerationItemActionAdd )
+            {
+            iAddItemCount++;
+            }
+        if(item.iItemType == EGenerationItemTypeAudio)
+            {
+            iAudioItemCount++;
+            }
+        if(item.iItemType == EGenerationItemTypeVideo)
+            {
+            iVideoItemCount++;
+            }
+        if(item.iItemType == EGenerationItemTypeImage)
+            {
+            iImageItemCount++;
+            }
+    }
+    
+    TN_DEBUG2( "CThumbAGProcessor::UpdateItemCounts() iActiveCount = %d", 
+            iActiveCount);
+    TN_DEBUG5( "CThumbAGProcessor::UpdateItemCounts() iHarvesting == %d, iMMCHarvesting == %d, iPHHarvesting == %d, iMPXHarvesting == %d", 
+            iHarvesting, iMMCHarvesting, iPHHarvesting, iMPXHarvesting);
+    TN_DEBUG5( "CThumbAGProcessor::UpdateItemCounts() iIdle = %d, iForegroundRun = %d, timer = %d, iForceRun = %d", 
+            iIdle, iForegroundRun, iPeriodicTimer->IsActive(), iForceRun);
+    TN_DEBUG4( "CThumbAGProcessor::UpdateItemCounts() iModify = %d, iQueryReady = %d, iProcessingCount = %d", 
+            iModify, iQueryReady, iProcessingCount);
+    TN_DEBUG2( "CThumbAGProcessor::UpdateItemCounts() iMountTimer = %d", iMountTimer->IsActive());
+    TN_DEBUG3( "CThumbAGProcessor::UpdateItemCounts() ProcessingQueue = %d, iQueryQueue = %d", 
+            iGenerationQueue.Count(), iQueryQueue.Count());
+    TN_DEBUG5( "CThumbAGProcessor::UpdateItemCounts() iAddItemCount=%d, i2ndAddItemCount=%d, iModifyItemCount=%d, iDeleteItemCount=%d",
+            iAddItemCount, i2ndAddItemCount, iModifyItemCount, iDeleteItemCount );
+    TN_DEBUG3( "CThumbAGProcessor::UpdateItemCounts() iUnknownItemCount=%d, iPlaceholderItemCount=%d",
+            iUnknownItemCount, iPlaceholderItemCount);
+    TN_DEBUG4( "CThumbAGProcessor::UpdateItemCounts() iAudioItemCount=%d, iVideoItemCount=%d, iImageItemCount=%d",
+            iAudioItemCount, iVideoItemCount, iImageItemCount);
+    TN_DEBUG2( "CThumbAGProcessor::UpdateItemCounts() iCameraItemCount=%d", iCameraItemCount);
+    }
+
+
+// ---------------------------------------------------------------------------
+// CThumbAGProcessor::MountTimerCallBack()
+// ---------------------------------------------------------------------------
+//
+TInt CThumbAGProcessor::MountTimerCallBack(TAny* aAny)
+    {
+    TN_DEBUG1( "CThumbAGProcessor::MountTimerCallBack()");
+    CThumbAGProcessor* self = static_cast<CThumbAGProcessor*>( aAny );
+    
+    self->iMountTimer->Cancel();
+
+    return KErrNone; // Return value ignored by CPeriodic
+    }
+
+// ---------------------------------------------------------------------------
+// CThumbAGProcessor::SetGenerationItemAction()
+// ---------------------------------------------------------------------------
+//
+void CThumbAGProcessor::SetGenerationItemAction( TThumbnailGenerationItem& aGenerationItem, TThumbnailGenerationItemType aItemType )
+    {
+    switch( aItemType )
+        {
+        case EGenerationItemTypeAudio:
+            aGenerationItem.iItemAction = EGenerationItemAction2ndAdd;
+            break;
+        case EGenerationItemTypeCamera:
+            aGenerationItem.iItemAction = EGenerationItemAction2ndAdd;
+            aGenerationItem.iPlaceholder = ETrue;
+            break;
+        case EGenerationItemTypeImage:
+            aGenerationItem.iItemAction = EGenerationItemActionAdd;
+            break;
+        case EGenerationItemTypeVideo:
+            //S^3 EGenerationItemActionAdd
+            //S^4 EGenerationItemAction2ndAdd
+            aGenerationItem.iItemAction = EGenerationItemAction2ndAdd;    
+            break;
+        default:
+            aGenerationItem.iItemAction = EGenerationItemActionResolveType;
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// CThumbAGProcessor::SetGenerationItemType()
+// ---------------------------------------------------------------------------
+//
+void CThumbAGProcessor::SetGenerationItemType( TThumbnailGenerationItem& aGenerationItem, const TDefId aDefId )
+    {
+        if(aDefId == iImageObjectDef->Id())
+          {
+            aGenerationItem.iItemType = EGenerationItemTypeImage;
+          }
+      else if(aDefId == iAudioObjectDef->Id())
+          {
+          aGenerationItem.iItemType = EGenerationItemTypeAudio;
+          }
+      else if(aDefId == iVideoObjectDef->Id())
+          {
+          aGenerationItem.iItemType = EGenerationItemTypeVideo;
+          }
+      else
+          {
+          aGenerationItem.iItemType = EGenerationItemTypeUnknown;
+          }
+        
+        SetGenerationItemAction( aGenerationItem, aGenerationItem.iItemType );
+    }
+
+
+// -----------------------------------------------------------------------------
+// CThumbAGProcessor::AppendProcessingQueue()
+// -----------------------------------------------------------------------------
+//
+void CThumbAGProcessor::AppendProcessingQueue( TThumbnailGenerationItem& item )
+    {
+
+    TInt itemIndex = iGenerationQueue.FindInOrder( item, Compare );
+           
+    if(itemIndex >= 0)
+       {
+       iGenerationQueue[itemIndex].iPlaceholder = item.iPlaceholder;
+       iGenerationQueue[itemIndex].iItemType = item.iItemType;
+       iGenerationQueue[itemIndex].iItemAction = item.iItemAction;
+       }
+    else
+       {
+       iGenerationQueue.InsertInOrder(item, Compare);
+       }
+    }
+
 
 // End of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/imagehandlingutilities/thumbnailmanager/thumbagdaemon/src/thumbagvideoobserver.cpp	Wed Jun 23 18:33:48 2010 +0300
@@ -0,0 +1,343 @@
+/*
+* 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:  Thumbnail Auto Generate Daemon 
+*
+*/
+
+
+#include <e32svr.h>
+#include <centralrepository.h>
+
+#include <mdesession.h>
+#include <mdeconstants.h>
+#include <mdequery.h>
+#include <mdeobject.h>
+
+#include "thumbagvideoobserver.h"
+#include "thumbnaillog.h"
+#include "thumbnailmanagerconstants.h"
+#include "thumbnailmanagerprivatecrkeys.h"
+
+
+// ---------------------------------------------------------------------------
+// NewLC
+// ---------------------------------------------------------------------------
+//
+CThumbAGVideoObserver* CThumbAGVideoObserver::NewLC(CThumbAGProcessor* aProcessor)
+    {
+    TN_DEBUG1( "CThumbAGVideoObserver::NewLC() - begin" );
+    
+	CThumbAGVideoObserver* self = new (ELeave) CThumbAGVideoObserver(aProcessor);
+	CleanupStack::PushL( self );
+	self->ConstructL();
+	return self;
+	}
+	
+// ---------------------------------------------------------------------------
+// NewL
+// ---------------------------------------------------------------------------
+//
+CThumbAGVideoObserver* CThumbAGVideoObserver::NewL(CThumbAGProcessor* aProcessor)
+	{
+	TN_DEBUG1( "CThumbAGVideoObserver::NewL() - begin" );
+    
+	CThumbAGVideoObserver* self = CThumbAGVideoObserver::NewLC(aProcessor);
+	CleanupStack::Pop( self );
+	return self;
+	}
+
+// ---------------------------------------------------------------------------
+// CThumbAGVideoObserver
+// ---------------------------------------------------------------------------
+//
+CThumbAGVideoObserver::CThumbAGVideoObserver(CThumbAGProcessor* aProcessor)
+ 	: iShutdownObserver(NULL), iMDSShutdownObserver(NULL), iMdESession(NULL), iProcessor(aProcessor)
+ 	{
+ 	// No implementation required
+ 	}
+
+// ---------------------------------------------------------------------------
+// ConstructL
+// ---------------------------------------------------------------------------
+//
+void CThumbAGVideoObserver::ConstructL()
+	{
+	TN_DEBUG1( "CThumbAGVideoObserver::ConstructL() - begin" );
+	
+#ifdef _DEBUG
+    iAddCounter = 0;
+    iModCounter = 0;
+#endif
+    
+    InitializeL();
+    	
+	TN_DEBUG1( "CThumbAGVideoObserver::ConstructL() - end" );
+	}
+
+// ---------------------------------------------------------------------------
+// ~CThumbAGVideoObserver
+// ---------------------------------------------------------------------------
+//
+void CThumbAGVideoObserver::InitializeL()
+    {
+    TN_DEBUG1( "CThumbAGVideoObserver::InitializeL() - begin" );
+    
+   
+        TN_DEBUG1( "CThumbAGVideoObserver::InitializeL() - create observers" );
+        
+        // create shutdown observer
+        if(iMDSShutdownObserver)
+            {
+            delete iMDSShutdownObserver;
+            iMDSShutdownObserver = NULL;
+            }     
+        iMDSShutdownObserver = CTMShutdownObserver::NewL( *this, KMdSPSShutdown, KMdSShutdown, EFalse );
+
+        if(iShutdownObserver)
+            {
+            delete iShutdownObserver;
+            iShutdownObserver = NULL;
+            }
+        iShutdownObserver = CTMShutdownObserver::NewL( *this, KTAGDPSNotification, KShutdown, ETrue );  
+        iShutdown = EFalse;
+        
+        // MDS session reconnect timer
+        if (!iReconnect)
+            {
+            iReconnect = CPeriodic::NewL(CActive::EPriorityIdle);
+            }
+        
+        TN_DEBUG1( "CThumbAGVideoObserver::InitializeL() - connect to MDS" );
+        
+        if(iMdESession)
+            {
+            TRAP_IGNORE( iMdESession->RemoveObjectObserverL( *this ) );
+            TRAP_IGNORE( iMdESession->RemoveObjectObserverL( *this ) );
+        
+            // connect to MDS
+            delete iMdESession;
+            iMdESession = NULL;
+            }
+
+        iMdESession = CMdESession::NewL( *this );
+        iSessionError = EFalse;
+      
+        TN_DEBUG1( "CThumbAGVideoObserver::InitializeL() - end" );
+    }
+
+// ---------------------------------------------------------------------------
+// ~CThumbAGVideoObserver
+// ---------------------------------------------------------------------------
+//
+CThumbAGVideoObserver::~CThumbAGVideoObserver()
+    {
+    TN_DEBUG1( "CThumbAGVideoObserver::~CThumbAGVideoObserver() - begin" );
+    
+    iShutdown = ETrue;    
+    
+    delete iMDSShutdownObserver;
+    delete iShutdownObserver;
+    
+    if(iReconnect)
+        {
+        iReconnect->Cancel();
+        delete iReconnect;
+        iReconnect = NULL;
+        }
+    
+    if (iMdESession)
+        {
+        // 2 observers
+        TRAP_IGNORE( iMdESession->RemoveObjectObserverL( *this ) );
+        TRAP_IGNORE( iMdESession->RemoveObjectObserverL( *this ) );
+                
+        delete iMdESession;
+        iMdESession = NULL;
+        }
+    
+    TN_DEBUG1( "CThumbAGVideoObserver::~CThumbAGVideoObserver() - end" );
+    }
+
+// -----------------------------------------------------------------------------
+// CThumbAGVideoObserver::HandleSessionOpened
+// -----------------------------------------------------------------------------
+//
+void CThumbAGVideoObserver::HandleSessionOpened( CMdESession& /* aSession */, TInt aError )
+    {
+    TN_DEBUG1( "CThumbAGVideoObserver::HandleSessionOpened");
+    
+    if (aError == KErrNone)
+        {
+        TRAPD( err, AddObserversL() );
+        if (err != KErrNone)
+            {
+            TN_DEBUG2( "CThumbAGVideoObserver::HandleSessionOpened, AddObserversL error == %d", err );
+            }
+        }
+    else
+        {
+        TN_DEBUG2( "CThumbAGVideoObserver::HandleSessionOpened error == %d", aError );
+        }
+    }
+
+// -----------------------------------------------------------------------------
+// CThumbAGVideoObserver::HandleSessionError
+// -----------------------------------------------------------------------------
+//
+void CThumbAGVideoObserver::HandleSessionError( CMdESession& /*aSession*/, TInt aError )
+    {
+    TN_DEBUG2( "CThumbAGVideoObserver::HandleSessionError == %d", aError );
+    if (aError != KErrNone && !iSessionError)
+        {
+        iSessionError = ETrue;
+    
+        if (!iShutdown)
+            {
+            if (!iReconnect->IsActive())
+                {
+                iReconnect->Start( KMdEReconnect, KMdEReconnect, 
+                                   TCallBack(ReconnectCallBack, this));
+                
+                TN_DEBUG1( "CThumbAGVideoObserver::HandleSessionError() - reconnect timer started" );
+                }
+            }
+
+        }   
+    }
+
+// -----------------------------------------------------------------------------
+// CThumbAGVideoObserver::HandleObjectNotification
+// -----------------------------------------------------------------------------
+//
+void CThumbAGVideoObserver::HandleObjectNotification( CMdESession& /*aSession*/, 
+                                               TObserverNotificationType aType,
+                                               const RArray<TItemId>& aObjectIdArray )
+    {
+    TN_DEBUG1( "CThumbAGVideoObserver::HandleObjectNotification() - begin" );
+
+    // no processor or shutting down
+    if ( iShutdown || !iProcessor)
+        {
+        return;
+        }
+    
+#ifdef _DEBUG
+    if (aType == ENotifyAdd)
+        {
+        TN_DEBUG2( "CThumbAGVideoObserver::HandleObjectNotification() - ENotifyAdd %d", aObjectIdArray.Count() );
+        iAddCounter = aObjectIdArray.Count();
+        }
+    else if (aType == ENotifyModify)
+        {
+        TN_DEBUG2( "CThumbAGVideoObserver::HandleObjectNotification() - ENotifyModify %d", aObjectIdArray.Count() );
+        iModCounter = aObjectIdArray.Count();
+        }
+#endif
+    
+    if ( (aType == ENotifyAdd || aType == ENotifyModify ) && (aObjectIdArray.Count() > 0) )
+        {
+        TN_DEBUG1( "CThumbAGVideoObserver::HandleObjectNotification() - AddToQueueL" );
+
+        // Add event to processing queue by type and enable force run        
+        RPointerArray<HBufC> dummyArray;
+        TRAPD(err, iProcessor->AddToQueueL(aType, EGenerationItemTypeAudio, aObjectIdArray, dummyArray, EFalse));
+        if (err != KErrNone)
+            {
+            TN_DEBUG1( "CThumbAGVideoObserver::HandleObjectNotification() - error adding to queue" );
+            }
+        }
+    else
+        {
+        TN_DEBUG1( "CThumbAGVideoObserver::HandleObjectNotification() - bad notification" );
+        }
+    
+#ifdef _DEBUG
+    TN_DEBUG3( "CThumbAGImageObserver::IN-COUNTERS---------- Add = %d Modify = %d", iAddCounter, iModCounter );
+    iModCounter = 0;
+    iAddCounter = 0;
+#endif
+
+    TN_DEBUG1( "CThumbAGVideoObserver::HandleObjectNotification() - end" );
+    }
+
+// -----------------------------------------------------------------------------
+// CThumbAGVideoObserver::ShutdownNotification
+// -----------------------------------------------------------------------------
+//
+void CThumbAGVideoObserver::ShutdownNotification()
+    {
+    TN_DEBUG1( "CThumbAGVideoObserver::ShutdownNotification()" );
+    
+    if (!iShutdown)
+        {
+        TN_DEBUG1( "CThumbAGVideoObserver::ShutdownNotification() shutdown" );
+        iShutdown = ETrue;
+        }
+    }
+
+// ---------------------------------------------------------------------------
+// CThumbAGVideoObserver::AddObserversL
+// ---------------------------------------------------------------------------
+//
+void CThumbAGVideoObserver::AddObserversL()
+    {
+    TN_DEBUG1( "CThumbAGVideoObserver::AddObserversL() - begin" );
+    
+    CMdENamespaceDef& defaultNamespace = iMdESession->GetDefaultNamespaceDefL();
+    CMdEObjectDef& objectDef = defaultNamespace.GetObjectDefL( MdeConstants::Object::KBaseObject );
+    CMdEPropertyDef& originPropDef = objectDef.GetPropertyDefL( MdeConstants::Object::KOriginProperty );
+    CMdEObjectDef& videoDef = defaultNamespace.GetObjectDefL( MdeConstants::Video::KVideoObject );
+    
+    // set observing conditions
+    CMdELogicCondition* addCondition = CMdELogicCondition::NewLC( ELogicConditionOperatorAnd );
+    addCondition->AddObjectConditionL( videoDef );
+    addCondition->AddPropertyConditionL( originPropDef, TMdEUintNotEqual(MdeConstants::Object::ECamera));
+    CleanupStack::Pop( addCondition );  
+    
+    CMdELogicCondition* modifyCondition = CMdELogicCondition::NewLC( ELogicConditionOperatorAnd );
+    modifyCondition->AddObjectConditionL( videoDef );
+    addCondition->AddPropertyConditionL( originPropDef, TMdEUintNotEqual(MdeConstants::Object::ECamera));
+    CleanupStack::Pop( modifyCondition );
+    
+    // add observer
+    iMdESession->AddObjectObserverL( *this, addCondition, ENotifyAdd ); 
+
+    // modify observer
+    iMdESession->AddObjectObserverL( *this, modifyCondition, ENotifyModify );
+     
+    TN_DEBUG1( "CThumbAGVideoObserver::AddObserversL() - end" );
+    }
+
+// ---------------------------------------------------------------------------
+// CThumbAGVideoObserver::ReconnectCallBack()
+// ---------------------------------------------------------------------------
+//
+TInt CThumbAGVideoObserver::ReconnectCallBack(TAny* aAny)
+    {
+    TN_DEBUG1( "CThumbAGVideoObserver::ReconnectCallBack() - reinitialize");
+    
+    CThumbAGVideoObserver* self = static_cast<CThumbAGVideoObserver*>( aAny );
+    
+    self->iReconnect->Cancel();
+    
+    // reconnect to MDS
+    TRAP_IGNORE( self->InitializeL() );
+    
+    TN_DEBUG1( "CThumbAGVideoObserver::ReconnectCallBack() - done");
+    
+    return KErrNone;
+    }
+
+
+// End of file
--- a/imagehandlingutilities/thumbnailmanager/thumbnailclient/inc/thumbnailrequestactive.h	Fri Jun 11 13:58:45 2010 +0300
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailclient/inc/thumbnailrequestactive.h	Wed Jun 23 18:33:48 2010 +0300
@@ -471,6 +471,11 @@
     // request already canceled by client
     TBool iCanceled;
     
+#ifdef __RETRY_ON_SERVERCRASH
+    //request retry count
+    TUint iRetry;
+#endif
+    
 #ifdef _DEBUG
     TTime iStartExecTime;
 #endif
--- a/imagehandlingutilities/thumbnailmanager/thumbnailclient/src/thumbnailmanagerimpl.cpp	Fri Jun 11 13:58:45 2010 +0300
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailclient/src/thumbnailmanagerimpl.cpp	Wed Jun 23 18:33:48 2010 +0300
@@ -47,7 +47,11 @@
 //
 CThumbnailManagerImpl::~CThumbnailManagerImpl()
     {
-    delete iRequestQueue;   
+    TN_DEBUG1( "CThumbnailManagerImpl::~CThumbnailManagerImpl() - start" );
+	
+    delete iRequestQueue;  
+    iRequestQueue = NULL;
+    
     iSession.Close();
     iFs.Close();
 
@@ -65,6 +69,8 @@
         }
 
     delete iMimeTypeList;
+	
+	TN_DEBUG1( "CThumbnailManagerImpl::~CThumbnailManagerImpl() - end" );
     }
 
 
@@ -94,6 +100,7 @@
     ( EOptimizeForQuality ), iRequestId( 0 )
     {
     // No implementation required
+    TN_DEBUG1( "CThumbnailManagerImpl::CThumbnailManagerImpl()" );
     }
 
 
@@ -104,6 +111,8 @@
 //
 void CThumbnailManagerImpl::ConstructL()
     {
+    TN_DEBUG1( "CThumbnailManagerImpl::ConstructL - start");
+    
     User::LeaveIfError( iSession.Connect());
     User::LeaveIfError( iFs.Connect());
     User::LeaveIfError( iFs.ShareProtected());
@@ -129,11 +138,14 @@
             {
             // Fbs connection was available in the beginning, no need to
             // increase the reference count
+            TN_DEBUG1( "CThumbnailManagerImpl::ConstructL - no need to update sessionCount");
             }
         }
     
     // request processor
     iRequestQueue = CThumbnailRequestQueue::NewL();
+    
+    TN_DEBUG1( "CThumbnailManagerImpl::ConstructL - end");
     }
 
 
--- a/imagehandlingutilities/thumbnailmanager/thumbnailclient/src/thumbnailrequestactive.cpp	Fri Jun 11 13:58:45 2010 +0300
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailclient/src/thumbnailrequestactive.cpp	Wed Jun 23 18:33:48 2010 +0300
@@ -48,11 +48,15 @@
         iTimer->Cancel();
         }
     delete iTimer;
+    iTimer = NULL;
     
     ReleaseServerBitmap();
     delete iCallbackThumbnail;
+    iCallbackThumbnail = NULL;
     delete iParams.iBuffer;
+    iParams.iBuffer = NULL;
     delete iBitmap;
+    iBitmap = NULL;
     iFile.Close();
     iMyFileHandle.Close();
     }
@@ -89,6 +93,9 @@
     CActive( aPriority ), iSession( aThumbnailSession ), iParamsPckg( iParams ),
     iObserver( aObserver ), iRequestObserver( aRequestObserver ), iFs( aFs ), iBitmapHandle( 0 ), 
     iRequestId( aId ), iRequestQueue( aQueue ), iCanceled( EFalse )
+#ifdef __RETRY_ON_SERVERCRASH
+    ,iRetry(0)
+#endif
     {
     CActiveScheduler::Add( this );
     TN_DEBUG2( "CThumbnaiRequestActive::CThumbnailRequestActive() AO's priority = %d", Priority());
@@ -572,9 +579,24 @@
 	            {
 	            iError = KErrNotFound;
 	            }
-			
-            TN_DEBUG2( "CThumbnaiRequestActive::HandleError() - iObserver.ThumbnailReady %d", iParams.iRequestId );
-            iObserver.ThumbnailReady( iError, *iCallbackThumbnail, iParams.iRequestId );
+	        
+#ifdef __RETRY_ON_SERVERCRASH
+	        if(iError == KErrServerTerminated )
+	            {
+                  
+                if(iRetry < KMaxRequestRetryCount )
+                    {
+                    iRetry++;
+                    TN_DEBUG2( "CThumbnaiRequestActive::HandleError() - KErrServerTerminated, retry %d", iRetry);
+                    iError = KErrNone;
+                    TRAPD(err, StartL());
+                    return;
+                    }
+	            }
+#endif
+	        TN_DEBUG2( "CThumbnaiRequestActive::HandleError() - iObserver.ThumbnailReady %d", iParams.iRequestId );
+	        iObserver.ThumbnailReady( iError, *iCallbackThumbnail, iParams.iRequestId );
+	            
             }
         
         iError = KErrNone;
--- a/imagehandlingutilities/thumbnailmanager/thumbnailclient/src/thumbnailsession.cpp	Fri Jun 11 13:58:45 2010 +0300
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailclient/src/thumbnailsession.cpp	Wed Jun 23 18:33:48 2010 +0300
@@ -31,6 +31,7 @@
 RThumbnailSession::RThumbnailSession(): RSessionBase()
     {
     // No implementation required
+    TN_DEBUG1( "RThumbnailSession::RThumbnailSession");
     }
 
 
@@ -40,6 +41,8 @@
 //
 TInt RThumbnailSession::Connect()
     { 
+    TN_DEBUG1( "RThumbnailSession::Connect - start");
+    
     StartServer();
     
     // special case
@@ -54,12 +57,16 @@
     // old server still alive, wait and try again
     while (retry <= 10 && err != KErrNone)
         {
+        TN_DEBUG1( "RThumbnailSession::Connect - retry");
+    
         User::After(retry * 50000);
         StartServer();
         err = CreateSession( KThumbnailServerName, Version(), KMessageSlots );
         retry++;
         }
     
+    TN_DEBUG1( "RThumbnailSession::Connect - end");
+    
     return err;
     }
 
@@ -71,6 +78,8 @@
 //
 void RThumbnailSession::Close()
     {
+    TN_DEBUG1( "RThumbnailSession::Close");
+    
     RSessionBase::Close();
     }
 
@@ -94,23 +103,29 @@
 //
 TInt RThumbnailSession::StartServer()
     {
+    TN_DEBUG1( "RThumbnailSession::StartServer - start");
+    
     TInt res( KErrNone );
     // create server - if one of this name does not already exist
 
     TFindServer findServer( KThumbnailServerName );
     TFullName name;
     if ( findServer.Next( name ) != KErrNone )
-    // we don't exist already
+        // we don't exist already
         {
+        TN_DEBUG1( "RThumbnailSession::StartServer - server process doesn't exist yet");
+    
         RProcess server;
         // Create the server process
         // KNullDesC param causes server's E32Main() to be run
         res = server.Create( KThumbnailServerExe, KNullDesC );
         if ( res != KErrNone )
-        // thread created ok - now start it going
             {
+            TN_DEBUG2( "RThumbnailSession::StartServer - error creating process: %d", res);
             return res;
             }
+        
+        TN_DEBUG1( "RThumbnailSession::StartServer - process created");
 
         // Process created successfully
         TRequestStatus status;
@@ -122,13 +137,18 @@
 
         if ( status != KErrNone )
             {
+            TN_DEBUG2( "RThumbnailSession::StartServer - status: %d, closing", status.Int() );
+        
             server.Close();
             return status.Int();
             }
+        
         // Server created successfully
         server.Close(); // we're no longer interested in the other process
-
         }
+    
+    TN_DEBUG1( "RThumbnailSession::StartServer - end");
+    
     return res;
     }
 
--- a/imagehandlingutilities/thumbnailmanager/thumbnailserver/group/thumbnailserver.mmp	Fri Jun 11 13:58:45 2010 +0300
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/group/thumbnailserver.mmp	Wed Jun 23 18:33:48 2010 +0300
@@ -82,6 +82,7 @@
 LIBRARY                 centralrepository.lib
 LIBRARY                 platformenv.lib
 LIBRARY			imageconversion.lib 
+LIBRARY 		iclextjpegapi.lib
 LIBRARY       		caf.lib
 LIBRARY         	cafutils.lib
 LIBRARY         	mdeclient.lib
--- a/imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/thumbnailserver.h	Fri Jun 11 13:58:45 2010 +0300
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/inc/thumbnailserver.h	Wed Jun 23 18:33:48 2010 +0300
@@ -234,6 +234,14 @@
      * @return Thumbnail provider.
      */
     CThumbnailProvider* ResolveProviderL( const TDesC8& aMimeType );
+    
+    /**
+     * Preload provider plugins
+     *
+     * @since S^3
+     */
+    void PreLoadProviders();
+    
 
     /**
      * Add thumbnailtask to processor queue.
@@ -538,6 +546,20 @@
      */
     static TInt ReconnectCallBack(TAny* aAny);
     
+    /**
+     * Start unmount timer
+     *
+     * @since S60 S^3
+     */
+    void StartUnmountTimeout( const TInt aDrive);
+    
+    /**
+     * Callback for unmount timer
+     *
+     * @since S60 S^3
+     */
+    static TInt UnmountCallBack(TAny* aAny);
+    
 private:
 
     /**
@@ -690,6 +712,12 @@
     
     // reconnect timer
     CPeriodic* iReconnect;
+
+    // unmount timer
+    CPeriodic* iUnmount;
+    
+    // array of unmounte
+    RArray < TInt > iUnmountedDrives;
     
 #ifdef _DEBUG
     TUint32 iPlaceholderCounter;
--- a/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailfetchedchecker.cpp	Fri Jun 11 13:58:45 2010 +0300
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailfetchedchecker.cpp	Wed Jun 23 18:33:48 2010 +0300
@@ -96,12 +96,15 @@
                 if( iNotFetched.Count() < KMaxStoredEntries )
                     {
                     TInt err = iNotFetched.InsertInOrder( entry, CEntry::InsertCB );
-                    if ( err != KErrNone )
+                    if ( err == KErrNone )
                         {
-                        delete entry;
+                        entry = NULL; // owned by array now
                         }
                     }
                 }
+            
+            delete entry;
+            entry = NULL;
             }
         }
     }
--- a/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailscaletask.cpp	Fri Jun 11 13:58:45 2010 +0300
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailscaletask.cpp	Wed Jun 23 18:33:48 2010 +0300
@@ -134,11 +134,15 @@
 
     if ( !iCrop )
         {
+        TN_DEBUG2( "CThumbnailScaleTask(0x%08x)::StartL() - cropping OFF", this );
+    
         // target size at max, keep aspect ratio
         CalculateTargetSize();
         }
     else
         {
+        TN_DEBUG2( "CThumbnailScaleTask(0x%08x)::StartL() - cropping ON", this );
+    
         // exact target size, crop excess
         CalculateCropRectangle();
         }
--- a/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailserver.cpp	Fri Jun 11 13:58:45 2010 +0300
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailserver.cpp	Wed Jun 23 18:33:48 2010 +0300
@@ -234,6 +234,9 @@
     REComSession::ListImplementationsL( TUid::Uid( THUMBNAIL_PROVIDER_IF_UID ),
         iPluginInfoArray );
     
+	//preload provide plugins
+    PreLoadProviders();
+    
     CTMGetImei * imeiGetter = CTMGetImei::NewLC();
    
     iImei = imeiGetter->GetIMEI();
@@ -252,10 +255,13 @@
     
     iFormatting = EFalse;
     
-    //OpenStoresL();
+    OpenStoresL();
     
     AddUnmountObserversL();
     iFetchedChecker = CThumbnailFetchedChecker::NewL();
+    
+    // Unmount timeout timer
+    iUnmount = CPeriodic::NewL(CActive::EPriorityIdle);
     }
 
 
@@ -269,6 +275,15 @@
 
     iShutdown = ETrue;
     
+    if(iUnmount)
+        {
+        iUnmount->Cancel();
+        delete iUnmount;
+        iUnmount = NULL;
+        }
+		
+	iUnmountedDrives.Close();
+    
     delete iFetchedChecker;
     delete iShutdownObserver;
     delete iProcessor;
@@ -318,9 +333,13 @@
 // CThumbnailServer::HandleSessionOpened
 // -----------------------------------------------------------------------------
 //
+#ifdef _DEBUG
+void CThumbnailServer::HandleSessionOpened( CMdESession& /* aSession */, TInt aError )
+#else
 void CThumbnailServer::HandleSessionOpened( CMdESession& /* aSession */, TInt /*aError*/ )
+#endif
     {
-    TN_DEBUG1( "CThumbnailServer::HandleSessionOpened");
+    TN_DEBUG2( "CThumbnailServer::HandleSessionOpened error == %d", aError );
     }
 
 // -----------------------------------------------------------------------------
@@ -444,12 +463,12 @@
 
     if ( iSessionCount <= 0 )
         {
-        // rename thread
-        User::RenameThread( KThumbnailServerShutdown );
-        
         // server shutdown
         if (!iShutdown)
             {
+            // rename thread
+            User::RenameThread( KThumbnailServerShutdown );
+        
             CActiveScheduler::Stop();
             iShutdown = ETrue;
             }
@@ -462,8 +481,10 @@
 //
 void CThumbnailServer::ShutdownNotification()
     {
+    TN_DEBUG1( "CThumbnailServer::ShutdownNotification()");
     if (!iShutdown)
         {
+        TN_DEBUG1( "CThumbnailServer::ShutdownNotification() shutdown");
         CActiveScheduler::Stop();
         iShutdown = ETrue;
         }
@@ -775,6 +796,22 @@
 
 
 // -----------------------------------------------------------------------------
+// CThumbnailServer::GetProviderL()
+// -----------------------------------------------------------------------------
+//
+void CThumbnailServer::PreLoadProviders(  )
+    {
+    TN_DEBUG1( "CThumbnailServer::PreLoadProvidersL()" );
+    TInt err(KErrNone);
+    
+    for(TInt i=0; i< iPluginInfoArray.Count(); i++)
+        {
+            TRAP(err, GetProviderL( iPluginInfoArray[i]->ImplementationUid()));
+        }
+    }
+
+
+// -----------------------------------------------------------------------------
 // CThumbnailServer::QueueTaskL()
 // Adds thumbnailtask to processor queue.
 // -----------------------------------------------------------------------------
@@ -887,6 +924,13 @@
 CThumbnailStore* CThumbnailServer::StoreForDriveL( const TInt aDrive )
     {
     TN_DEBUG2( "CThumbnailServer::StoreForDriveL() drive=%d", aDrive );
+    
+    if(iUnmountedDrives.Find( aDrive ) >= KErrNone)
+        {
+        TN_DEBUG1( "CThumbnailServer::StoreForDriveL() unmount in progress, skip!");
+        User::Leave( KErrDisMounted );
+        }
+    
     CThumbnailStore** resPtr = iStores.Find( aDrive );
     CThumbnailStore* res = NULL;
 
@@ -901,8 +945,10 @@
            TN_DEBUG1( "CThumbnailServer::StoreForDriveL() - FORMATTING! - ABORT");
            User::Leave( KErrNotSupported );
            } 
+        
         TVolumeInfo volumeInfo;
         TInt err = iFs.Volume( volumeInfo, aDrive );
+        
         if ( err || volumeInfo.iDrive.iDriveAtt& KDriveAttRom ||
             volumeInfo.iDrive.iDriveAtt& KDriveAttRemote ||
             volumeInfo.iDrive.iMediaAtt& KMediaAttWriteProtected ||
@@ -912,14 +958,14 @@
             // must be read-write and not locked.
             User::Leave( KErrAccessDenied);
             }
-
+        
         res = CThumbnailStore::NewL( iFs, aDrive, iImei, this );
         CleanupStack::PushL( res );
         iStores.InsertL( aDrive, res );
         res->SetPersistentSizes(iPersistentSizes);
         CleanupStack::Pop( res );
         
-        for(TInt i = 0; i<iUnmountObservers.Count(); i++)
+        for(TInt i = 0; i < iUnmountObservers.Count(); i++)
             {
             iUnmountObservers[i]->StartNotify();
             }
@@ -1002,6 +1048,8 @@
     TN_DEBUG2( "CThumbnailServer::CloseStoreForDriveL drive=%d", aDrive);
     CThumbnailStore** store = iStores.Find( aDrive );
     
+    StartUnmountTimeout( aDrive);
+    
     if (store)
         {
         delete *store;
@@ -1098,15 +1146,44 @@
         TInt err_drive = iFs.Drive(driveInfo, drive);    
         
         // mount -- if removable drive, add new store
-        if (!err && !err_drive && driveInfo.iDriveAtt& KDriveAttRemovable)
+        if (!err && !err_drive 
+                && driveInfo.iType != EMediaNotPresent
+                && driveInfo.iDriveAtt& KDriveAttRemovable )
             {
+            TN_DEBUG2( "CThumbnailServer::MemoryCardStatusChangedL mount drive==%d", drive);
+            
+            CThumbnailStore** resPtr = iStores.Find( drive );
+
+            if ( resPtr )
+                {
+                TN_DEBUG2( "CThumbnailServer::MemoryCardStatusChangedL() already mounted, skip %d", drive);
+                continue;
+                }
+            
             // ignore errors
-            //TRAP_IGNORE( StoreForDriveL( drive ));
+            TRAP_IGNORE( StoreForDriveL( drive ));
+            
+            TN_DEBUG2( "CThumbnailServer::MemoryCardStatusChangedL() update KItemsleft == %d", KErrNotReady);
+            RProperty::Set(KTAGDPSNotification, KItemsleft, KErrNotReady );
+			
+            TInt index = iUnmountedDrives.Find( drive );
+            
+            if(index >= KErrNone)
+                {
+                iUnmountedDrives.Remove( index );
+                }
+            
+            if(!iUnmountedDrives.Count()&& iUnmount && iUnmount->IsActive())
+                {
+                TN_DEBUG1( "CThumbnailServer::MemoryCardStatusChangedL() cancel unmount timer");
+                iUnmount->Cancel();
+                }
             }
         
         //dismount -- if removable drive, close store
-        else if(err && !err_drive && driveInfo.iDriveAtt& KDriveAttRemovable)
+        else if(err && !err_drive && driveInfo.iDriveAtt& KDriveAttRemovable )
             {
+            TN_DEBUG2( "CThumbnailServer::MemoryCardStatusChangedL() unmount drive==%d", drive);
             CloseStoreForDriveL( drive);
             }
         }
@@ -1665,3 +1742,48 @@
     return ETrue;
     }
 
+// ---------------------------------------------------------------------------
+// CThumbnailServer::StartUnmount()
+// ---------------------------------------------------------------------------
+//
+void CThumbnailServer::StartUnmountTimeout( const TInt aDrive)
+    {
+    TN_DEBUG2( "CThumbnailServer::StartUnmountTimeout(%d)", aDrive);
+    
+    if(iUnmount )
+        {
+        if(iUnmountedDrives.Find( aDrive ) == KErrNotFound)
+            {
+            iUnmountedDrives.Append( aDrive );
+            }
+        
+       if(iUnmount->IsActive())
+           {
+           iUnmount->Cancel();
+           }
+       
+       TN_DEBUG1( "CThumbnailServer::StartUnmountTimeout() start unmount timer");
+       iUnmount->Start( KUnmountTimerTimeout, KUnmountTimerTimeout, TCallBack(UnmountCallBack, this));
+       }
+       __ASSERT_DEBUG(( iUnmount ), ThumbnailPanic( EThumbnailNullPointer ));
+    }
+
+
+// ---------------------------------------------------------------------------
+// CThumbnailServer::ReconnectCallBack()
+// ---------------------------------------------------------------------------
+//
+TInt CThumbnailServer::UnmountCallBack(TAny* aAny)
+    {
+    TN_DEBUG1( "CThumbnailServer::UnmountCallBack() - unmount finished");
+    
+    CThumbnailServer* self = static_cast<CThumbnailServer*>( aAny );
+    
+    self->iUnmount->Cancel();
+    
+    self->iUnmountedDrives.Reset();
+    
+    TN_DEBUG1( "CThumbAGDaemon::UnmountCallBack() - done");
+    
+    return KErrNone;
+    }
--- a/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailserversession.cpp	Fri Jun 11 13:58:45 2010 +0300
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailserversession.cpp	Wed Jun 23 18:33:48 2010 +0300
@@ -444,6 +444,7 @@
     const TThumbnailRequestParams& params = iRequestParams();
 
     RFile64 file;
+    CleanupClosePushL(file);
     User::LeaveIfError( file.AdoptFromClient( aMessage, 2, 3 ));
     
     ResolveMimeTypeL(&file);
@@ -461,9 +462,10 @@
     if (params.iControlFlags == EThumbnailGeneratePersistentSizesOnly)
         {
         TN_DEBUG1( "CThumbnailServerSession::RequestThumbByFileHandleAsyncL() - EThumbnailGeneratePersistentSizesOnly" );
-        CleanupClosePushL( file );
         CreateGenerateTaskFromFileHandleL( &file );
-        CleanupStack::Pop( &file );         
+        
+        // ownership of the file transferred
+        CleanupStack::Pop(&file);
         }
     // single thumbnail request
     else
@@ -477,13 +479,16 @@
             
             aMessage.Complete( err );
             iMessage = RMessage2();
+            
+            // close file
+            CleanupStack::PopAndDestroy(&file);
             }
         else if ( !err && iBitmap )
             {
             TN_DEBUG1( "CThumbnailServerSession::RequestThumbByFileHandleAsyncL() - found existing thumbnail - bitmap " );
 
             // Thumbnail already stored
-            file.Close();
+            CleanupStack::PopAndDestroy(&file);
             TN_DEBUG1("CThumbnailServerSession::RequestThumbByFileHandleAsyncL - file handle closed");
 
             ProcessBitmapL();
@@ -493,6 +498,9 @@
             {
             TN_DEBUG1( "CThumbnailServerSession::RequestThumbByFileHandleAsyncL() - KErrNotFound & !EDoNotCreate" );
             CreateGenerateTaskFromFileHandleL( &file);
+            
+            // ownership of the file transferred
+        	CleanupStack::Pop(&file);
             }
         else if (!err && iBuffer)
             {
@@ -511,7 +519,9 @@
             
             //CThumbnailDecodeTask is responsible freeing
             iBuffer = NULL;
-            file.Close();
+            
+            // close file
+            CleanupStack::PopAndDestroy(&file);
             TN_DEBUG1("CThumbnailServerSession::RequestThumbByFileHandleAsyncL - file handle closed");
             }
         else
@@ -520,6 +530,9 @@
             
             aMessage.Complete( ConvertSqlErrToE32Err( err ));
             iMessage = RMessage2();
+            
+            // close file
+            CleanupStack::PopAndDestroy(&file);
             }     
         }
     }
@@ -1099,16 +1112,6 @@
     {   
     TThumbnailRequestParams& params = iRequestParams();
     
-    // in import case store bitmap
-    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.iModified,
-                                   EFalse, EFalse);
-        }
-    
     if ( ClientThreadAlive() )
         {        
         TN_DEBUG2("CThumbnailServerSession::ProcessBitmapL(), iBitmap handle= 0x%08x", iBitmap->Handle());
--- a/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailstore.cpp	Fri Jun 11 13:58:45 2010 +0300
+++ b/imagehandlingutilities/thumbnailmanager/thumbnailserver/src/thumbnailstore.cpp	Wed Jun 23 18:33:48 2010 +0300
@@ -212,11 +212,6 @@
         iMaintenanceTimer = NULL;
         }
     
-    if(!iServer->IsFormatting())
-        {
- 	    FlushCacheTable( ETrue );
-        }
-    
     CloseStatements();   
     iDatabase.Close();
     
@@ -571,7 +566,7 @@
                 
     stmt.Close();
     
-    if(ret < 0)
+    if(rowStatus < 0)
         {
 #ifdef _DEBUG
         TPtrC errorMsg2 = iDatabase.LastErrorMessage();
@@ -596,7 +591,7 @@
             
     stmt.Close();
     
-    if(ret < 0)
+    if( rowStatus < 0)
         {
 #ifdef _DEBUG
         TPtrC errorMsg2 = iDatabase.LastErrorMessage();
@@ -648,7 +643,7 @@
     
     stmt.Close();
     
-    if(ret < 0 )
+    if( rowStatus < 0 )
         {
 #ifdef _DEBUG
          TPtrC errorMsg = iDatabase.LastErrorMessage();
@@ -699,7 +694,7 @@
     
     stmt.Close(); 
     
-    if(ret < 0 )
+    if( rowStatus < 0 )
         {
 #ifdef _DEBUG
          TPtrC errorMsg = iDatabase.LastErrorMessage();
@@ -1267,7 +1262,39 @@
                 HBufC8* data = NULL;
                 CleanupStack::PushL( data );
                 
-                CImageEncoder* encoder = CImageEncoder::DataNewL( data,  KJpegMime(), CImageEncoder::EOptionAlwaysThread );
+                CImageEncoder* encoder = NULL;
+                TRAPD( decErr, encoder = CExtJpegEncoder::DataNewL( CExtJpegEncoder::EHwImplementation, data, CImageEncoder::EOptionAlwaysThread ) );
+                if ( decErr != KErrNone )
+                    {
+                    TN_DEBUG2( "CThumbnailStore::StoreThumbnailL( public ) - HW CExtJpegEncoder failed %d", decErr);
+                
+                    TRAPD( decErr, encoder = CExtJpegEncoder::DataNewL( CExtJpegEncoder::ESwImplementation, data, CImageEncoder::EOptionAlwaysThread ) );
+                    if ( decErr != KErrNone )
+                        {
+                        TN_DEBUG2( "CThumbnailStore::StoreThumbnailL( public ) - SW CExtJpegEncoder failed %d", decErr);
+                    
+                        TRAPD( decErr, encoder = CImageEncoder::DataNewL( data,  KJpegMime(), CImageEncoder::EOptionAlwaysThread ) );
+                        if ( decErr != KErrNone )
+                            {
+                            TN_DEBUG2( "CThumbnailStore::StoreThumbnailL( public ) - CImageEncoder failed %d", decErr);
+                            
+                            User::Leave(decErr);
+                            }
+                        else
+                            {
+                            TN_DEBUG1( "CThumbnailStore::StoreThumbnailL( public ) - CImageEncoder created" );
+                            }
+                        }
+                    else
+                        {
+                        TN_DEBUG1( "CThumbnailStore::StoreThumbnailL( public ) - SW CExtJpegEncoder created" );
+                        }
+                    }
+                else
+                    {
+                    TN_DEBUG1( "CThumbnailStore::StoreThumbnailL( public ) - HW CExtJpegEncoder created" );
+                    }             
+                
                 CleanupStack::Pop( data );
                 CleanupStack::PushL( encoder );
              
--- a/imagehandlingutilities/thumbnailmanager/tmcommon/src/tmactivitymanager.cpp	Fri Jun 11 13:58:45 2010 +0300
+++ b/imagehandlingutilities/thumbnailmanager/tmcommon/src/tmactivitymanager.cpp	Wed Jun 23 18:33:48 2010 +0300
@@ -53,12 +53,15 @@
     {
     TN_DEBUG1( "CTMActivityManager::~CTMActivityManager()");
     
+    iObserver = NULL;
+    Cancel();
+    
 #ifdef MONITOR_LIGHTS
     delete iLight;
     iLight = NULL;
 #endif
-    
-    Cancel();
+
+    iTimer.Cancel();
     iTimer.Close();
     }
  
--- a/imagehandlingutilities/thumbnailmanager/tmcommon/src/tmformatobserver.cpp	Fri Jun 11 13:58:45 2010 +0300
+++ b/imagehandlingutilities/thumbnailmanager/tmcommon/src/tmformatobserver.cpp	Wed Jun 23 18:33:48 2010 +0300
@@ -81,6 +81,7 @@
         }
     
     delete iBackupSession;
+    iBackupSession = NULL;
     }
 
 // ---------------------------------------------------------------------------
--- a/imagehandlingutilities/thumbnailmanager/tmcommon/src/tmshutdownobserver.cpp	Fri Jun 11 13:58:45 2010 +0300
+++ b/imagehandlingutilities/thumbnailmanager/tmcommon/src/tmshutdownobserver.cpp	Wed Jun 23 18:33:48 2010 +0300
@@ -20,6 +20,7 @@
 
 #include "tmshutdownobserver.h"
 #include "thumbnailmanagerconstants.h"
+#include "thumbnaillog.h"
 
 // ---------------------------------------------------------------------------
 // CTMShutdownObserver::NewL()
@@ -60,19 +61,23 @@
 //
 void CTMShutdownObserver::ConstructL()
     { 
+    TN_DEBUG1( "CTMShutdownObserver::ConstructL()" );
     // define P&S property types
     if (iDefineKey)
         {
+        TN_DEBUG1( "CTMShutdownObserver::ConstructL() define" );
         RProperty::Define(iKeyCategory,iPropertyKey,
                           RProperty::EInt,KAllowAllPolicy,KPowerMgmtPolicy);
         }
     
     // attach to the property
     TInt err = iProperty.Attach(iKeyCategory,iPropertyKey,EOwnerThread);
+    TN_DEBUG2( "CTMShutdownObserver::ConstructL() attach err = %d", err );
     User::LeaveIfError(err);
     
     // wait for the previously attached property to be updated
     iProperty.Subscribe(iStatus);
+    TN_DEBUG1( "CTMShutdownObserver::ConstructL() subscribe" );
     SetActive();
     }
 
@@ -82,6 +87,7 @@
 //
 CTMShutdownObserver::~CTMShutdownObserver()
     {
+    TN_DEBUG1( "CTMShutdownObserver::~CTMShutdownObserver()" );
     Cancel();
     iProperty.Close();
     }
@@ -92,13 +98,16 @@
 //
 void CTMShutdownObserver::RunL()
     {
+    TN_DEBUG2( "CTMShutdownObserver::RunL(%d)", iStatus.Int() );
     // resubscribe before processing new value to prevent missing updates
     iProperty.Subscribe(iStatus);
     SetActive();
     
     // retrieve the value
     TInt value = 0;
-    iProperty.Get(value);
+    TInt err = iProperty.Get(value);
+    
+    TN_DEBUG2( "CTMShutdownObserver::RunL() Get err = %d", err );
 
     // observer callback
     if (value)
@@ -113,6 +122,7 @@
 //
 void CTMShutdownObserver::DoCancel()
     {
+    TN_DEBUG1( "CTMShutdownObserver::DoCancel()" );
     iProperty.Cancel();
     }
 
--- a/imagehandlingutilities/thumbnailmanager/tmiadrestart/src/tmiadrestart.cpp	Fri Jun 11 13:58:45 2010 +0300
+++ b/imagehandlingutilities/thumbnailmanager/tmiadrestart/src/tmiadrestart.cpp	Wed Jun 23 18:33:48 2010 +0300
@@ -19,12 +19,14 @@
 #include <e32base.h>
 #include <e32std.h>  
 #include <e32property.h>
+#include "thumbnaillog.h"
 
 #include "thumbnailmanagerconstants.h"
 
 LOCAL_C void MainL()
     {
     // delay so that cenrep has time to read new config
+    TN_DEBUG1( "MainL() after" );
     User::After(5000000);
     
     TInt res( KErrNone );
@@ -32,50 +34,66 @@
     TFullName name;
     
     // find and terminate Thumb AG Daemon
+    TN_DEBUG1( "MainL() KTAGDaemonProcess find" );
     TFindProcess findProcess( KTAGDaemonProcess );   
+
     if ( findProcess.Next(name) == KErrNone )
         {
         res = process.Open(name);
+        TN_DEBUG2( "MainL() KTAGDaemonProcess open res = %d", res );    
         
         // logon to get termination signal
         TRequestStatus status;
+        TN_DEBUG1( "MainL() KTAGDaemonProcess logon" );
         process.Logon(status);
-         
+
         // shutdown using P&S key
-        RProperty::Set(KTAGDPSNotification,KShutdown,1);
-        
+        TN_DEBUG2( "MainL() KTAGDaemonProcess Set = %d", res );
+        res = RProperty::Set(KTAGDPSNotification,KShutdown,1);
+       
         // blocks here until thread is terminated
-        User::WaitForRequest(status); 
+        TN_DEBUG1( "MainL() KTAGDaemonProcess wait" );
+        User::WaitForRequest(status);
         
         // reset key
-        RProperty::Set(KTAGDPSNotification,KShutdown,0);
+        TN_DEBUG1( "MainL() KTAGDaemonProcess reset" );
+        res = RProperty::Set(KTAGDPSNotification, KShutdown, 0);
         
+        TN_DEBUG1( "MainL() KTAGDaemonProcess close" );
         process.Close();
         }
     
     // find and terminate Thumbnail Server
     TFindProcess findProcess2( KThumbnailServerProcess );
+    TN_DEBUG1( "MainL() KThumbnailServerProcess find" );
     if ( findProcess2.Next(name) == KErrNone )
         {
         res = process.Open(name);
-         
+        TN_DEBUG2( "MainL() KThumbnailServerProcess open res = %d", res );
+        
         // logon to get termination signal
         TRequestStatus status;
+        TN_DEBUG1( "MainL() KThumbnailServerProcess logon" );
         process.Logon(status);
           
         // shutdown using P&S key
-        RProperty::Set(KTMPSNotification,KShutdown,1);
+        TN_DEBUG2( "MainL() KThumbnailServerProcess Set res = %d", res );
+        res = RProperty::Set(KTMPSNotification,KShutdown,1);
          
         // blocks here until thread is terminated
-        User::WaitForRequest(status); 
+        TN_DEBUG1( "MainL() KThumbnailServerProcess wait" );
+        User::WaitForRequest(status);
          
         // reset key
-        RProperty::Set(KTMPSNotification,KShutdown,0);
-         
+        TN_DEBUG2( "MainL() KThumbnailServerProcess reset res = %d", res );
+        res = RProperty::Set(KTMPSNotification, KShutdown, 0);
+
+        TN_DEBUG1( "MainL() KThumbnailServerProcess close" );
         process.Close();
         }    
     
     // delay just in case old daemon hasn't died yet
+    TN_DEBUG1( "MainL() after" );
     User::After(2500000);
     
     // start new ThumbAGDaemon
@@ -84,29 +102,38 @@
     
     // Create the server process
     // KNullDesC param causes server's E32Main() to be run
+    TN_DEBUG2( "MainL() KTAGDaemonExe create res = %d", res );
     res = server.Create( KTAGDaemonExe, KNullDesC );
     
     // try again 3 times if fails
     while ( res != KErrNone)
         {
+        TN_DEBUG1( "MainL() KTAGDaemonExe retry" );
         if (retryCount > 2)
             {
+            TN_DEBUG1( "MainL() KTAGDaemonExe retry > 2" );
             return;
             }
         
+        TN_DEBUG1( "MainL() after" );
         User::After(2500000);
+        TN_DEBUG2( "MainL() KTAGDaemonExe create res = %d", res );
         res = server.Create( KTAGDaemonExe, KNullDesC );
-        
         retryCount++;
         }
     
     // Process created successfully
     TRequestStatus status;
+    TN_DEBUG1( "MainL() Rendezvous" );
     server.Rendezvous( status );
+    TN_DEBUG1( "MainL() Resume" );
     server.Resume(); // start it going
     
+    
     // Wait until the completion of the server creation
+    TN_DEBUG1( "MainL() wait" );
     User::WaitForRequest( status );
+    TN_DEBUG1( "MainL() wait done" );
     
     // Server created successfully
     server.Close(); // we're no longer interested in the other process