⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 taskmanagerappview.cpp

📁 Symbian OS 任务管理器源代码 比较好用的例子
💻 CPP
字号:
/*
* ============================================================================
*  Name     : CTaskManagerAppView from TaskManagerAppView.cpp
*  Part of  : TaskManager
*  Created  : 15/03/2006 by Forum Nokia
*  Version  : 1.2
*  Copyright: Nokia Corporation
* ============================================================================
*/

// INCLUDE FILES
#include "TaskManager.hrh"
#include "TaskManagerAppView.h"
#include "TaskManagerAppUi.h"
#include "Response.h"

#include <coemain.h>
#include <aknlists.h>			// CAknSingleStyleListBox
#include <barsread.h>			// TResourceReader
#include <aknnotewrappers.h>	// CAknInformationNote
#include <SocketTaskManager.rsg>
#include <stringloader.h>
#include <e32std.h>
#include <aknquerydialog.h>

// CONSTANTS
#define KListPosition TPoint(0,0)
_LIT(KTab, "\t");
_LIT(KError, "Error: %d");
_LIT(KNoTasks, "No Tasks!");
_LIT(KLoadingTasks, "Loading tasks...");
_LIT(KCompletingTask, "Completing task...");
_LIT(KTaskCompleted, "\n\nTask completed?");
_LIT(KInvalidTask, "Invalid task. Cannot complete.");
_LIT(KTaskFormat, "%d\t%S");
_LIT(KOpeningConnection, "Opening connection...");
const TInt KMaxErrorLength = 30;


// ================= MEMBER FUNCTIONS =======================

// constructor
CTaskManagerAppView::CTaskManagerAppView(CTaskManagerAppUi& aAppUi)
	:	iAppUi(aAppUi)
	{
	iStatusText = KNoTasks;
	}

// destructor
CTaskManagerAppView::~CTaskManagerAppView()
	{
	delete iTaskList;
	}

// ----------------------------------------------------
// CTaskManagerAppView::NewL()
// Two-phased constructor.
// ----------------------------------------------------
//
CTaskManagerAppView *CTaskManagerAppView::NewL(const TRect& aRect, CTaskManagerAppUi& aAppUi)
	{
    CTaskManagerAppView *self = new(ELeave) CTaskManagerAppView(aAppUi);
    CleanupStack::PushL(self);
    self->ConstructL(aRect);
    CleanupStack::Pop(self);
    return self;
	}

// ----------------------------------------------------
// CTaskManagerAppView::ConstructL()
// Symbian OS default constructor can leave.
// ----------------------------------------------------
//	
void CTaskManagerAppView::ConstructL(const TRect& aRect)
	{
    // Create a window for this application view
    CreateWindowL();
	
	CreateListL();
	
    // Set the windows size
    SetRect(aRect);

    // Activate the window, which makes it ready to be drawn
    ActivateL();
	}

// ----------------------------------------------------
// CTaskManagerAppView::ConstructL()
// Creates a listbox that is used for showing the tasks
// to the user.
// ----------------------------------------------------
//
void CTaskManagerAppView::CreateListL()
	{
	iTaskList = new (ELeave) CAknSingleStyleListBox;
	iTaskList->SetContainerWindowL( *this );
	
	iTaskList->SetListBoxObserver( this );
	
	TResourceReader reader;
	iEikonEnv->CreateResourceReaderLC( reader, R_TASKMANAGER_TASKLIST );
	iTaskList->ConstructFromResourceL( reader );

	iTaskList->MakeVisible( EFalse );
	
	CleanupStack::PopAndDestroy(); // ResourceReader
	}


// ----------------------------------------------------
// CTaskManagerAppView::Draw()
// This function is used for window server-initiated 
// redrawing of controls, and for some 
// application-initiated drawing. Here we show the 
// status text to the user.
// ----------------------------------------------------
//
void CTaskManagerAppView::Draw(const TRect& /*aRect*/) const
	{
    // Get the standard graphics context 
    CWindowGc &gc = SystemGc();
    
    // Gets the control's extent
    TRect rect = Rect();
    
    // Clears the screen
    gc.Clear(rect);
    
    // status text is showed only if iTaskList isn't visible
    if( !iTaskList->IsVisible() )
    	{
   		gc.UseFont( iCoeEnv->NormalFont() );
   		
   		// This is done to center the text
   		TInt pointX = rect.Width() / 2 -
   					  iCoeEnv->NormalFont()->TextWidthInPixels( iStatusText ) / 2;

   		TInt pointY = rect.Height() / 2 -
   					  iCoeEnv->NormalFont()->HeightInPixels() / 2;
   					  
		gc.DrawText( iStatusText, TPoint( pointX, pointY ) );
    	}

	}

// ----------------------------------------------------
// CTaskManagerAppView::HandleListBoxEventL()
// Handles list box events. When enter key is pressed, 
// the selected task is marked completed.
// ----------------------------------------------------
//
void CTaskManagerAppView::HandleListBoxEventL(CEikListBox* aListBox, 
                                              TListBoxEvent aListBoxEvent)
	{
	if( aListBoxEvent == MEikListBoxObserver::EEventEnterKeyPressed )
		{

		const MDesCArray* items = aListBox->Model()->MatchableTextArray();
		
		// We get the currently selected item's text to print it in a query
		TPtrC pointer = items->MdcaPoint( aListBox->CurrentItemIndex() );
		
		TInt tabOffSet = pointer.Find(KTab);
		// id of the task was not found.
		if (tabOffSet == KErrNotFound || tabOffSet == 0)
			{
			CAknInformationNote *informationNote = new(ELeave) CAknInformationNote;
			informationNote->ExecuteLD(KInvalidTask);
			return;
			}
		
		TLex lex(pointer.Left(tabOffSet));
		TInt taskId;
		User::LeaveIfError(lex.Val(taskId));
		
		// (KMaxTaskLength +20) space for task and KTaskCompleted
		TBuf<KMaxTaskLength + 20> message = pointer.Mid(tabOffSet+1);
		message.Append( KTaskCompleted ); 
		
		// A waiting confirmation note
		CAknQueryDialog* note = CAknQueryDialog::NewL(); 
		CleanupStack::PushL(note);
		note->SetPromptL( message );
		CleanupStack::Pop(note);
		
		iAppUi.SetViewBusyL(ETrue);
		
		// The query is shown
		if( note->ExecuteLD( R_TASKMANAGER_TASK_CONFIRMATION_QUERY ) )
			{
			// show 'Completing task' to the user.
			ShowStatus(KCompletingTask);
			
			iAppUi.ShowConnectingCbaL(ETrue);
			iAppUi.Model().MarkTaskDoneL(taskId);
			iTransactionStatus = EMarkingTaskDone;
			}		
		
		iAppUi.SetViewBusyL(EFalse);
		}	
	}

// ----------------------------------------------------
// CTaskManagerAppView::DeleteSelectedTaskL()
// Removes the selected task from the listbox.
// ----------------------------------------------------
//
void CTaskManagerAppView::DeleteSelectedTaskL()
	{
	CTextListBoxModel* model = iTaskList->Model();
	CDesCArray* itemArray = static_cast<CDesCArray*>( model->ItemTextArray() );
	
	TInt currentItem = iTaskList->CurrentItemIndex();
	
	itemArray->Delete( currentItem );
	
	AknListBoxUtils::HandleItemRemovalAndPositionHighlightL( iTaskList,
															 currentItem,
															 ETrue );

	iTaskList->DrawNow();		
	
	// no more tasks, show 'No tasks' to user.													 
	if( model->NumberOfItems() == 0 )
		{
		iTaskList->MakeVisible( EFalse );
		}
	}

// ----------------------------------------------------
// CTaskManagerAppView::ReadTasksL()
// Reads tasks from aResponse and adds them to the listbox.
// ----------------------------------------------------
//
void CTaskManagerAppView::ReadTasksL( const CResponse& aResponse )
	{
	CTextListBoxModel* model = iTaskList->Model();
	
	model->SetOwnershipType( ELbmOwnsItemArray ); // Just to underline the relation
	CDesCArray* itemArray = static_cast<CDesCArray*>( model->ItemTextArray() );
										 
	itemArray->Reset();
	
	TInt taskCount = aResponse.TaskCount();
	// reserve space for task description and for taskid
	TBuf<KMaxTaskLength+10> taskDesc;
	for (TInt i = 0; i < taskCount; i++)
		{
		TBuf<KMaxTaskLength> desc = aResponse.TaskDescription(i);
		taskDesc.Format(KTaskFormat, aResponse.TaskId(i), &desc);
		itemArray->AppendL(taskDesc);
		}
	
	// If there are items in the listbox, make the listbox visible.
	if( model->NumberOfItems() > 0 )
		{
		iTaskList->HandleItemAdditionL();
		iTaskList->DrawNow();
		iTaskList->MakeVisible( ETrue );
		}
	}

// ----------------------------------------------------
// CTaskManagerAppView::CountComponentControls()
// Gets the number of controls contained in a compound 
// control. 
// ----------------------------------------------------
//
TInt CTaskManagerAppView::CountComponentControls() const
	{
	TInt count = 0;
	if (iTaskList)
		{
		count++;
		}
		
	return count;
	}

// ----------------------------------------------------
// CTaskManagerAppView::ComponentControl()
// Gets the specified component of a compound control.
// ----------------------------------------------------
//
CCoeControl* CTaskManagerAppView::ComponentControl( TInt aIndex ) const
	{
	switch( aIndex )
		{
		case 0:
			return iTaskList;
		default:
			return 0;
		};
	}

// ----------------------------------------------------
// CTaskManagerAppView::SizeChanged()
// Responds to size changes to sets the size and 
// position of the contents of this control. 
// ----------------------------------------------------
//	
void CTaskManagerAppView::SizeChanged()
	{
	iTaskList->SetExtent( KListPosition, iTaskList->MinimumSize() );	
	}

// ----------------------------------------------------
// CTaskManagerAppView::OfferKeyEventL()
// When a key event occurs, the control framework calls 
// this function for each control on the control stack, 
// until one of them can process the key event 
// (and returns EKeyWasConsumed).
// ----------------------------------------------------
//	
TKeyResponse CTaskManagerAppView::OfferKeyEventL( const TKeyEvent& aKeyEvent,
												  TEventCode aType )
	{
	if( iTaskList && iTaskList->IsVisible() )
		{
		return iTaskList->OfferKeyEventL( aKeyEvent, aType );
		}
	else
		{
		return EKeyWasNotConsumed;
		}
	}

// ----------------------------------------------------
// CTaskManagerAppView::OpeningConnectionL()
// Called when a GPRS connection is opened.
// ----------------------------------------------------
//	
void CTaskManagerAppView::OpeningConnectionL()
	{
	ShowStatus(KOpeningConnection);
	iAppUi.ShowConnectingCbaL(ETrue);
	}
	
// ----------------------------------------------------
// CTaskManagerAppView::ConnectingL()
// Called when a transaction is initiated. 
// ----------------------------------------------------
//
void CTaskManagerAppView::ConnectingToServerL(const TBool& aLoadingTasks)
	{
	if (aLoadingTasks)
		{
		ShowStatus(KLoadingTasks);
		}
	else
		{
		ShowStatus(KCompletingTask);
		}

	// show cancel button.
	iAppUi.ShowConnectingCbaL(ETrue);
	}

// ----------------------------------------------------
// CTaskManagerAppView::SuccessL()
// Called when the transaction has successfully 
// finished. 
// ----------------------------------------------------
//	
void CTaskManagerAppView::SuccessL(const CResponse& aResponse)
	{
	// even though the transaction was successful, errors might have occurred
	// in the server database.
	if (aResponse.HasError())
		{
		CAknInformationNote *informationNote = new(ELeave) CAknInformationNote;
		informationNote->ExecuteLD(aResponse.Error());
		}
	// no errors.
	else
		{
		// we were completing a task, remove it from the listbox.
		if (iTransactionStatus == EMarkingTaskDone)
			{
			iTransactionStatus = EFetchingTasks;
			DeleteSelectedTaskL();
			}
		// we were loading tasks, show them in the listbox.
		else
			{
			ReadTasksL(aResponse);
			}
		}
	
	// will show 'No tasks' or if tasks exist, a list of tasks is shown.
	ShowStatus(KNoTasks);
	
	iAppUi.ShowConnectingCbaL(EFalse);
	}

// ----------------------------------------------------
// CTaskManagerAppView::FailedL()
// Called when the transaction has failed. 
// ----------------------------------------------------
//	
void CTaskManagerAppView::FailedL(const TInt& aError)
	{
	TBuf<KMaxErrorLength> error;
	error.Format(KError, aError);
	CAknInformationNote *informationNote = new(ELeave) CAknInformationNote;
	informationNote->ExecuteLD(error);
	
	// will show 'No tasks' or if tasks exist, a list of tasks is shown.
	ShowStatus(KNoTasks);

	iAppUi.ShowConnectingCbaL(EFalse);
	}
	
// ----------------------------------------------------
// CTaskManagerAppView::CancelledL()
// Called when the transaction was cancelled by 
// the user. 
// ----------------------------------------------------
//	
void CTaskManagerAppView::CancelledL()
	{
	// will show 'No tasks' or if tasks exist, a list of tasks is shown.
	ShowStatus(KNoTasks);

	iAppUi.ShowConnectingCbaL(EFalse);
	}

// ----------------------------------------------------
// CTaskManagerAppView::ErrorL()
// Called when connection settings are invalid and the 
// transaction cannot be initiated. This occurs 
// e.g. when username and/or password is not set.
// ----------------------------------------------------
//	
void CTaskManagerAppView::ErrorL(const TDesC& aErrorMsg)
	{
	CAknInformationNote *informationNote = new(ELeave) CAknInformationNote;
	informationNote->ExecuteLD(aErrorMsg);
	
	// will show 'No tasks' or if tasks exist, a list of tasks is shown.
	ShowStatus(KNoTasks);

	iAppUi.ShowConnectingCbaL(EFalse);
	}

// ----------------------------------------------------
// CTaskManagerAppView::QueryIapL()
// Opens up a querylist dialog containing all IAPs. User 
// selects from the list the IAP that he/she wants to use.
// ----------------------------------------------------
//		
TBool CTaskManagerAppView::QueryIapL(TUint32& aId, const TUint32& aDefaultId)
	{
	TBool retval = EFalse;
	RArray<TIap>& iaps = iAppUi.Model().Iaps();
	TInt iapCount = iaps.Count();
	
	CDesCArrayFlat* iapArray = new (ELeave) CDesCArrayFlat(iapCount);
	CleanupStack::PushL(iapArray);
	
	TInt selectedIndex = 0;
	
	// Load all IAPs to the list.
	for (TInt i = 0; i < iapCount; i++)
		{
		if (iaps[i].iId == aDefaultId)
			{
			selectedIndex = i;
			}
		iapArray->AppendL(iaps[i].iName);
		}
		
	TInt index(0);
	CAknListQueryDialog* query = new (ELeave) CAknListQueryDialog(&index);
	query->PrepareLC(R_TASKMANAGER_IAP_LIST_QUERY);
	query->SetItemTextArray(iapArray);
	query->SetOwnershipType(ELbmDoesNotOwnItemArray);
	query->ListBox()->SetCurrentItemIndex(selectedIndex);
	if (query->RunLD())
		{
		aId = iaps[index].iId;
		retval = ETrue;
		}
		
	CleanupStack::PopAndDestroy(iapArray);	
	return retval;
	}

// ----------------------------------------------------
// CTaskManagerAppView::ShowStatus()
// Shows proper status text to the user.
// ----------------------------------------------------
//	
void CTaskManagerAppView::ShowStatus(const TDesC& aStatus)
	{
	iStatusText = aStatus;
	
	// Show 'No tasks' or if tasks exist, show list of tasks.
	if (aStatus == KNoTasks)
		{
		if (iTaskList->Model()->NumberOfItems() > 0)
			{
			iTaskList->MakeVisible(ETrue);
			}
		}
	// Show only status text.
	else
		{
		iTaskList->MakeVisible(EFalse);
		}
		
	DrawNow();
	}
	
// End of file

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -