// EIKMNBUT.CPP
//
// Copyright (c) 1997-1999 Symbian Ltd.  All rights reserved.
//

#include <eikmnbut.h>
#include <eikmenup.h>
#include <barsread.h>
#include <coeaui.h>
#include <eikenv.h>
#include <eikappui.h>				    

EXPORT_C CEikMenuButton::CEikMenuButton()
    {								   
	SetReportOnPointerDown();
    }

EXPORT_C CEikMenuButton::~CEikMenuButton()
    {
	if (iMenuPopup)
		{
		iEikonEnv->EikAppUi()->RemoveFromStack(iMenuPopup);
		delete iMenuPopup;
		}
	}

EXPORT_C void CEikMenuButton::SetMenuPaneId(TInt aMenuPaneId)
    {								   
	iMenuPaneId=aMenuPaneId;
    }

EXPORT_C void CEikMenuButton::ConstructFromResourceL(TResourceReader& aReader)
	{
	iMenuPaneId=aReader.ReadInt32();
	CEikCommandButton::ConstructFromResourceL(aReader);
	}

EXPORT_C void CEikMenuButton::Animate()
	{
	iButFlags|=0x10; // same as KButtonPressedMask - avoid magic number !!!
	StateChanged();
	DrawNow();
	iCoeEnv->WsSession().Flush();
	}

EXPORT_C void CEikMenuButton::ProcessCommandL(TInt aCommandId)
	{
	if (iMenuPopup)
	    ClosePopupMenu();
	iMenuObserver->ProcessCommandL(aCommandId);
	}

EXPORT_C void CEikMenuButton::LaunchPopupMenuL(MEikMenuObserver* aObserver)
    {
	iMenuObserver=aObserver;
    iMenuPopup=new(ELeave) CEikMenuPane(this);
	TRAPD(err,DoLaunchPopupMenuL());
	if (err)
		{
		ClosePopupMenu();
		User::Leave(err);
		}
	}

void CEikMenuButton::DoLaunchPopupMenuL()
	{
	iMenuPopup->ConstructL(NULL);
	iMenuObserver->RestoreMenuL(iMenuPopup,iMenuPaneId,MEikMenuObserver::EMenuPane);
	iMenuPopup->SetPointerCapture(ETrue);
	iEikonEnv->EikAppUi()->AddToStackL(iMenuPopup,ECoeStackPriorityDialog);
	
	const TSize popupSize=iMenuPopup->CalculateSize();
	const TSize screenSize=iEikonEnv->ScreenDevice()->SizeInPixels();
	
	TPoint pos=PositionRelativeToScreen();
	// try to position popup to right of button, then below, then left and lastly above
	if (pos.iX+iSize.iWidth+popupSize.iWidth<=screenSize.iWidth)
		pos.iX+=iSize.iWidth;
	else if (pos.iY+iSize.iHeight+popupSize.iHeight<=screenSize.iHeight)
		pos.iY+=iSize.iHeight;
	else if (pos.iX-popupSize.iWidth>=0)
		pos.iX-=popupSize.iWidth;
	else if (pos.iY-popupSize.iHeight>=0)
		pos.iY-=popupSize.iHeight;
	else
		{
		pos.iX+=iSize.iWidth;
		pos.iY+=iSize.iHeight;
		}
	
	iMenuPopup->StartDisplayingMenuPane(NULL,pos,NULL,0/*,EPopupTargetTopRight*/);
	if (iCoeEnv->LastEvent().Type()==EEventPointer)
		{
		SetIgnoreNextPointerUp();
		iMenuPopup->ClaimPointerGrab();
		}
	iMenuPopup->SetLaunchingButton(this);
	}

void CEikMenuButton::ClosePopupMenu()
	{
	if (!iMenuPopup)
		return;
	iEikonEnv->EikAppUi()->RemoveFromStack(iMenuPopup);
	delete iMenuPopup;
	iMenuPopup=NULL;
	}

EXPORT_C void CEikMenuButton::SetEmphasis(CCoeControl* /*aMenuControl*/,TBool /*aEmphasis*/)
	{ // !! what should go here
	}

