//this file is part of eMule
//Copyright (C)2002-2008 Merkur ( strEmail.Format("%s@%s", "devteam", "emule-project.net") / http://www.emule-project.net )
//
//This program is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either
//version 2 of the License, or (at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#include "stdafx.h"
#include "ToolTipCtrlX.h"
#include "OtherFunctions.h"
#include "emule.h"
#include "log.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

#define DFLT_DRAWTEXT_FLAGS	(DT_NOPREFIX | DT_END_ELLIPSIS)


IMPLEMENT_DYNAMIC(CToolTipCtrlX, CToolTipCtrl)

BEGIN_MESSAGE_MAP(CToolTipCtrlX, CToolTipCtrl)
	ON_WM_SYSCOLORCHANGE()
	ON_WM_SETTINGCHANGE()
	ON_WM_PAINT()  //TK4 Mod
	ON_WM_NCPAINT()//TK4 Mod
	ON_NOTIFY_REFLECT(NM_CUSTOMDRAW, OnNMCustomDraw)
	ON_NOTIFY_REFLECT(NM_THEMECHANGED, OnNMThemeChanged)
END_MESSAGE_MAP()



void CToolTipCtrlX::OnNcPaint()
{
	
  if(b_isXP_Vista) CToolTipCtrl::OnNcPaint();
}



void CToolTipCtrlX::OnPaint()
{

  if(b_isXP_Vista) CToolTipCtrl::OnPaint();
    else SendMessage(NM_CUSTOMDRAW);
}


CToolTipCtrlX::CToolTipCtrlX()
{
	m_bCol1Bold = true;
	m_bShowFileIcon = false;
	ResetSystemMetrics();
	m_dwCol1DrawTextFlags = DFLT_DRAWTEXT_FLAGS | DT_LEFT;
	m_dwCol2DrawTextFlags = DFLT_DRAWTEXT_FLAGS | DT_LEFT;
    //TK4 MOD borrowed from otherfunctions
	b_isXP_Vista = true; 
	OSVERSIONINFOEX osvi;
	ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
	osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
	if(!GetVersionEx((OSVERSIONINFO*)&osvi))
	{
		osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
		if(!GetVersionEx((OSVERSIONINFO*)&osvi)) 
		return;
	}

	switch(osvi.dwPlatformId)
	{
		case VER_PLATFORM_WIN32_NT:
			if((osvi.dwMajorVersion == 5 && osvi.dwMinorVersion > 0) || osvi.dwMajorVersion > 5)
				return;
		    b_isXP_Vista = false; /// else 2K or NT4
			return;
      
		case VER_PLATFORM_WIN32_WINDOWS:
			b_isXP_Vista = false; /// Guess - the old OSs behave like 2K...?
	        return;

	}


	
}

CToolTipCtrlX::~CToolTipCtrlX()
{
}

void CToolTipCtrlX::SetCol1DrawTextFlags(DWORD dwFlags)
{
	m_dwCol1DrawTextFlags = DFLT_DRAWTEXT_FLAGS | dwFlags;
}

void CToolTipCtrlX::SetCol2DrawTextFlags(DWORD dwFlags)
{
	m_dwCol2DrawTextFlags = DFLT_DRAWTEXT_FLAGS | dwFlags;
}

void CToolTipCtrlX::ResetSystemMetrics()
{
	m_fontBold.DeleteObject();
	m_fontNormal.DeleteObject();
    LOGFONT lf;
    NONCLIENTMETRICS ncm;
    ncm.cbSize = sizeof(NONCLIENTMETRICS);
	if (SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(NONCLIENTMETRICS), &ncm, 0)){
		memcpy(&lf, &(ncm.lfStatusFont), sizeof(LOGFONT));
		VERIFY( m_fontNormal.CreateFontIndirect(&lf) );
	}

	m_crTooltipBkColor = GetSysColor(COLOR_INFOBK);
	m_crTooltipTextColor = GetSysColor(COLOR_INFOTEXT);
	m_rcScreen.left = 0;
	m_rcScreen.top = 0;
	m_rcScreen.right = GetSystemMetrics(SM_CXSCREEN);
	m_rcScreen.bottom = GetSystemMetrics(SM_CYSCREEN);
	m_iScreenWidth4 = m_rcScreen.Width() >> 2; //TK4 MOD optimize was /4
}

void CToolTipCtrlX::OnNMThemeChanged(NMHDR* /*pNMHDR*/, LRESULT* pResult)
{
	ResetSystemMetrics();
	*pResult = 0;
}

void CToolTipCtrlX::OnSysColorChange()
{
	ResetSystemMetrics();
	CToolTipCtrl::OnSysColorChange();
}

void CToolTipCtrlX::OnSettingChange(UINT uFlags, LPCTSTR lpszSection)
{
	ResetSystemMetrics();
	CToolTipCtrl::OnSettingChange(uFlags, lpszSection);
}

void CToolTipCtrlX::OnNMCustomDraw(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMTTCUSTOMDRAW pNMCD = reinterpret_cast<LPNMTTCUSTOMDRAW>(pNMHDR);
	/*There is only one drawstage for tooltips and CDRF_SKIPDEFAULT doesn't work under 2000!?*/
	if (pNMCD->nmcd.dwDrawStage == CDDS_PREPAINT) //leaving this in as a safety device because who knows what will change next...
	{
		CWnd* pwnd = CWnd::FromHandle(pNMCD->nmcd.hdr.hwndFrom);
		CDC* pdc = CDC::FromHandle(pNMCD->nmcd.hdc);

		CString strText;
		pwnd->GetWindowText(strText);

		POINT Pos;
		GetCursorPos(&Pos);
		CRect rcWnd;
		CRect rcParentWnd;
		WindowFromPoint(Pos)->GetWindowRect(&rcParentWnd);
		rcParentWnd.right -= 16;  //allow for scrollbar can't do for top and bottom as it just makes one overlap worse.
	   
	        rcWnd.right  = rcWnd.left = Pos.x; 
	        rcWnd.bottom = rcWnd.top  = Pos.y + 20;


		CFont* pOldDCFont = NULL;
		if (m_fontNormal.m_hObject != NULL){
			 pOldDCFont = pdc->SelectObject(&m_fontNormal);
		}
		if (m_bCol1Bold && m_fontBold.m_hObject == NULL) {
			LOGFONT lf;
			m_fontNormal.GetLogFont(&lf);
			lf.lfWeight = FW_BOLD;
			VERIFY( m_fontBold.CreateFontIndirect(&lf) );
		}
		pdc->SetTextColor(m_crTooltipTextColor);

		// Auto-format the text only if explicitly requested. Otherwise we would also format
		// single line tooltips for regular list items, and if those list items contain ':'
		// characters they would be shown partially in bold. For performance reasons, the
		// auto-format is to be requested by appending the TOOLTIP_AUTOFORMAT_SUFFIX_CH 
		// character. Appending, because we can remove that character efficiently without
		// re-allocating the entire string.
		bool bAutoFormatText = strText.GetLength() > 0 && strText[strText.GetLength() - 1] == TOOLTIP_AUTOFORMAT_SUFFIX_CH;
		if (bAutoFormatText)
			strText.Truncate(strText.GetLength() - 1); // truncate the TOOLTIP_AUTOFORMAT_SUFFIX_CH char by setting it to NUL
		bool bShowFileIcon = m_bShowFileIcon && bAutoFormatText;
		if (bShowFileIcon) {
			int iPosNL = strText.Find(_T('\n'));
			if (iPosNL > 0) {
				int iPosColon = strText.Find(_T(':'));
				if (iPosColon < iPosNL)
					bShowFileIcon = false; // 1st line does not contain a filename
			}
		}
		int iTextHeight = 0;
		int iMaxCol1Width = 0;
		int iMaxCol2Width = 0;
		int iMaxSingleLineWidth = 0;
		CSize sizText(0);
		int iPos = 0;
		int iCaptionEnd = bShowFileIcon ? max(strText.Find(_T("\n<br_head>\n")), 0) : 0; // special tooltip with file icon
		int iCaptionHeight = 0;
		int iIconMinYBorder = bShowFileIcon ? 3 : 0;
		int iIconWidth = bShowFileIcon ? theApp.GetBigSytemIconSize().cx : 0;
		int iIconHeight = bShowFileIcon ? theApp.GetBigSytemIconSize().cy : 0;
		int iIconDrawingWidth = bShowFileIcon ? (iIconWidth + 9) : 0;
		while (iPos != -1)
		{
			CString strLine = GetNextString(strText, _T('\n'), iPos);
			int iColon = bAutoFormatText ? strLine.Find(_T(':')) : -1;
			if (iColon != -1) {
				CFont* pOldFont = m_bCol1Bold ? pdc->SelectObject(&m_fontBold) : NULL;
				CSize siz = pdc->GetTextExtent(strLine, iColon + 1);
				if (pOldFont)
					pdc->SelectObject(pOldFont);
				iMaxCol1Width = max(iMaxCol1Width, siz.cx + ((bShowFileIcon && iPos <= iCaptionEnd + strLine.GetLength()) ? iIconDrawingWidth : 0));
				iTextHeight = siz.cy + 1; // update height with 'col1' string, because 'col2' string might be empty and therefore has no height
				if (iPos <= iCaptionEnd)
					iCaptionHeight += siz.cy + 1;
				else
					sizText.cy += siz.cy + 1;

				LPCTSTR pszCol2 = (LPCTSTR)strLine + iColon + 1;
				while (_istspace((_TUCHAR)*pszCol2))
					pszCol2++;
				if (*pszCol2 != _T('\0')) {
					siz = pdc->GetTextExtent(pszCol2, ((LPCTSTR)strLine + strLine.GetLength()) - pszCol2);
					iMaxCol2Width = max(iMaxCol2Width, siz.cx);
				}
			}
			else if (bShowFileIcon && iPos <= iCaptionEnd && iPos == strLine.GetLength() + 1){
				// file name, printed bold on top without any tabbing or desc
				CFont* pOldFont = m_bCol1Bold ? pdc->SelectObject(&m_fontBold) : NULL;
				CSize siz = pdc->GetTextExtent(strLine);
				if (pOldFont)
					pdc->SelectObject(pOldFont);
				iMaxSingleLineWidth = max(iMaxSingleLineWidth, siz.cx + iIconDrawingWidth);
				iCaptionHeight += siz.cy + 1;
			}
			else if (!strLine.IsEmpty() && strLine.Compare(_T("<br>")) != 0 && strLine.Compare(_T("<br_head>")) != 0) {
				CSize siz = pdc->GetTextExtent(strLine);
				iMaxSingleLineWidth = max(iMaxSingleLineWidth, siz.cx + ((bShowFileIcon && iPos <= iCaptionEnd) ? iIconDrawingWidth : 0));
				if (bShowFileIcon && iPos <= iCaptionEnd + strLine.GetLength())
					iCaptionHeight += siz.cy + 1;
				else
					sizText.cy += siz.cy + 1;
			}
			else{
				CSize siz = pdc->GetTextExtent(_T(" "), 1);
				sizText.cy += siz.cy;
			}
		}
		if (bShowFileIcon && iCaptionEnd > 0)
			iCaptionHeight = max(iCaptionHeight, theApp.GetBigSytemIconSize().cy + (2*iIconMinYBorder));
		sizText.cy += iCaptionHeight;

		iMaxCol1Width = min(m_iScreenWidth4, iMaxCol1Width);
		iMaxCol2Width = min(m_iScreenWidth4*2, iMaxCol2Width);

		const int iMiddleMargin = 6;
		iMaxSingleLineWidth = max(iMaxSingleLineWidth, iMaxCol1Width + iMiddleMargin + iMaxCol2Width);
		/*Allow for stupidly long file names forcing the start of the tooltip window out of the drawable area
		  and allow for the right hand scrollbar too! */
		sizText.cx = min(iMaxSingleLineWidth,rcParentWnd.Width() - 16);
	        iMaxSingleLineWidth = sizText.cx; //Fix for line lenght in constrained window
		CRect rcNewSize(rcWnd.left, rcWnd.top, rcWnd.left + sizText.cx, rcWnd.top + sizText.cy);
		AdjustRect(&rcNewSize);		
		rcWnd.right = rcWnd.left + rcNewSize.Width();
		rcWnd.bottom = rcWnd.top + rcNewSize.Height();

        /*Because the bottom of the parent window when off screen can go over screen size
		  EG: m_rcScreen.bottom = 768  rcParentWnd.bottom = 1032 They can also go negative!*/
        if( rcParentWnd.bottom > m_rcScreen.bottom ) rcParentWnd.bottom = m_rcScreen.bottom;
        if( rcParentWnd.right  > m_rcScreen.right ) rcParentWnd.right  = m_rcScreen.right;
	    /*The below rcScreen should always equal Zero, but who knows what weirdness can be implemented my M$*/
        if( rcParentWnd.left < m_rcScreen.left ) rcParentWnd.left = m_rcScreen.left; 
 	    if( rcParentWnd.top < m_rcScreen.top ) rcParentWnd.top = m_rcScreen.top;
            
        /*Parent window size rather than screen size*/
		if (rcWnd.left >= rcParentWnd.left && rcWnd.right > rcParentWnd.right) {
          rcWnd.OffsetRect(-(rcWnd.right - rcParentWnd.right), 0);
		}

		if(rcWnd.top >= rcParentWnd.top && rcWnd.bottom > rcParentWnd.bottom && rcWnd.Height() <= rcParentWnd.Height()) {
         if(rcWnd.Height() < (rcParentWnd.Height() >> 1))  rcWnd.OffsetRect(0, -(rcWnd.Height() + 20));//position like a normal tooltip if possible
		  else 	{//fallback to the original code if space is limited
			      rcWnd.OffsetRect(0, -(rcWnd.bottom - rcParentWnd.bottom));
		}
		}

        //TK4 MOD Position and fill our tooltips window.
        pNMCD->nmcd.rc = rcWnd;
		//TK4 MOD if it's 2K we need to show what we have created
		if(!b_isXP_Vista)  ShowWindow(1);
		else if(pNMCD->uDrawFlags & DT_CALCRECT)
		       { //if this is the first pass to calculate size return
				   *pResult =  CDRF_DODEFAULT;
					return;
 		        }
		pwnd->MoveWindow(&rcWnd);
	    GetClientRect(rcWnd);
		pdc->FillSolidRect(&rcWnd, m_crTooltipBkColor);
	    CPoint ptText(rcWnd.left + iMiddleMargin, rcWnd.top + iMiddleMargin);

		iPos = 0;
		while (iPos != -1)
		{
			CString strLine = GetNextString(strText, _T('\n'), iPos);
			int iColon = bAutoFormatText ? strLine.Find(_T(':')) : -1;
			CRect rcDT;
			if (!bShowFileIcon || (unsigned)iPos > (unsigned)iCaptionEnd + strLine.GetLength())
				rcDT.SetRect(ptText.x, ptText.y, ptText.x + iMaxCol1Width, ptText.y + iTextHeight);
			else
				rcDT.SetRect(ptText.x + iIconDrawingWidth, ptText.y, ptText.x + iMaxCol1Width, ptText.y + iTextHeight);
			if (iColon != -1) {
				// don't draw empty <col1> strings (they are still handy to use for skipping the <col1> space)
				if (iColon > 0) {
					CFont* pOldFont = m_bCol1Bold ? pdc->SelectObject(&m_fontBold) : NULL;
					pdc->DrawText(strLine, iColon + 1, &rcDT, m_dwCol1DrawTextFlags);
					if (pOldFont)
						pdc->SelectObject(pOldFont);
				}

				LPCTSTR pszCol2 = (LPCTSTR)strLine + iColon + 1;
				while (_istspace((_TUCHAR)*pszCol2))
					pszCol2++;
				if (*pszCol2 != _T('\0')) {
					rcDT.left = ptText.x + iMaxCol1Width + iMiddleMargin;
					rcDT.right = rcDT.left + iMaxCol2Width;
					pdc->DrawText(pszCol2, ((LPCTSTR)strLine + strLine.GetLength()) - pszCol2, &rcDT, m_dwCol2DrawTextFlags);
				}

				ptText.y += iTextHeight;
			}
			else if (bShowFileIcon && iPos <= iCaptionEnd && iPos == strLine.GetLength() + 1){
				// first line on special fileicon tab - draw icon and bold filename
				CFont* pOldFont = m_bCol1Bold ? pdc->SelectObject(&m_fontBold) : NULL;
				pdc->DrawText(strLine, CRect(ptText.x  + iIconDrawingWidth, ptText.y, ptText.x + iMaxSingleLineWidth, ptText.y + iTextHeight), m_dwCol1DrawTextFlags);
				if (pOldFont)
					pdc->SelectObject(pOldFont);

				ptText.y += iTextHeight;
				int iImage = theApp.GetFileTypeSystemImageIdx(strLine, -1, true);
				if (theApp.GetBigSystemImageList() != NULL) {
					int iPosY = rcDT.top;
					if (iCaptionHeight > iIconHeight)
						iPosY += (iCaptionHeight - iIconHeight) >> 1; // /2 replaced with >>1 TK4 MOD

					::ImageList_Draw(theApp.GetBigSystemImageList(), iImage, pdc->GetSafeHdc(), ptText.x, iPosY, ILD_NORMAL|ILD_TRANSPARENT);
				}
			}
			else {
				bool bIsBrHeadLine = false;
				if (bAutoFormatText && (strLine.Compare(_T("<br>")) == 0 || (bIsBrHeadLine = strLine.Compare(_T("<br_head>")) == 0) == true)){
					CPen pen;
					pen.CreatePen(0, 1, m_crTooltipTextColor);
					CPen *pOP = pdc->SelectObject(&pen);
					if (bIsBrHeadLine)
						ptText.y = iCaptionHeight;
					pdc->MoveTo(ptText.x, ptText.y + ((iTextHeight - 2) >> 1)); // /2 replaced with >>1 TK4 MOD
					pdc->LineTo(ptText.x + iMaxSingleLineWidth, ptText.y + ((iTextHeight - 2) >> 1));// /2 replaced with >>1 TK4 MOD
					ptText.y += iTextHeight;
					pdc->SelectObject(pOP);
					pen.DeleteObject();
				}
				else{
					CSize siz = pdc->TabbedTextOut(ptText.x, ptText.y, strLine, 0, NULL, 0);
					ptText.y += siz.cy;
				}
			}
		}

    //TK4 MOD if it's 2K we need to draw the frame for the tooltip
	if(!b_isXP_Vista) pdc->FrameRect(&rcWnd,&CBrush(RGB(0,0,0)));//Draw the frame last to prevent big text breaking it

		if (pOldDCFont)
			pdc->SelectObject(pOldDCFont);

		*pResult = CDRF_SKIPDEFAULT;
		return;
	}
	*pResult = CDRF_DODEFAULT;
}