//------------jun hirabayashi jun@hirax.net 2006/05/03------------------
#include "BrowserWindow.h"

//------文字列置換用----------------------------
std::string& replace(std::string& str, const std::string sb, const std::string sa)
{
	std::string::size_type n, nb = 0;
	while ((n = str.find(sb,nb)) != std::string::npos)
	{
		str.replace(n,sb.size(),sa);
		nb = n + sa.size();
	}
	return str;
}
//------コンストラクタ------------------------------
BrowserWindow::BrowserWindow()
{
    URL       = "Unknown";
    PageTitle = "Unknown";
    previousURL       = URL;
    previousPageTitle = PageTitle;
    isChanged = true;
    WindowInfo.Left       = NULL;
    WindowInfo.Right      = NULL;
    WindowInfo.Top        = NULL;
    WindowInfo.Bottom     = NULL;
    WindowInfo.Hwnd       = NULL;
    Browser = "Unknown";
}
//------デストラクタ---------------------------------
BrowserWindow::~BrowserWindow()
{
}
//------最前面Windowの情報更新   --------------------
#define IE_STRING " - Microsoft Internet Explorer"
#define SLEIPNIR "Sleipnir - "
#define SLEIPNIR2 " - Sleipnir"
#define FIREFOX " - Mozilla Firefox"
#define MOZILLA " - Mozilla"
#define OPERA " - Opera"
bool BrowserWindow::Check( void )
{
    previousURL       = URL;
    previousPageTitle = PageTitle;

    char lpString[256];
    HWND hWnd = GetForegroundWindow();
    int iTitleLegth=GetWindowText( hWnd, lpString, 255 );
    string sTitle = lpString;
    {
        PageTitle = sTitle;
        if( sTitle.find ( (string)IE_STRING, 0) != string::npos )  // IE
        {
            getFromIE( PageTitle );
            PageTitle = sTitle.substr(0, sTitle.length()
                                 - ((string)IE_STRING).length() );
            Browser = (string)"IExplore";
        }
        else if( sTitle.find ( (string)SLEIPNIR, 0) != string::npos )
        {   // Sleipnir 1 -> Proxyの名前はslepnirの設定で出さないように!
            getFromSleipnir( PageTitle );
            PageTitle = sTitle.substr( ((string)SLEIPNIR).length()+1,
                            sTitle.length() - ((string)SLEIPNIR).length()-2 );
            Browser = (string)"Sleipnir";
        }
        else if( sTitle.find ( (string)SLEIPNIR2, 0) != string::npos )
        {   // Sleipnir 2  ->  ここらを後で調整
            getFromSleipnir2( PageTitle );
            PageTitle = PageTitle + "";
            Browser = (string)"Sleipnir2";
        }
        else if( sTitle.find ( (string)FIREFOX, 0) != string::npos )
        {   // Mozilla Firefox
            Browser = (string)FIREFOX;
            PageTitle = sTitle.substr(0, sTitle.length() - Browser.length() ) + "";
            Browser = (string)"Firefox";
            getUrlByDDE( Browser );
        }
        else if( sTitle.find ( (string)MOZILLA, 0) != string::npos )
        {   // Mozilla
            Browser = (string)MOZILLA;
            PageTitle = sTitle.substr(0, sTitle.length() - Browser.length() ) + "";
            Browser = (string)"Mozilla";
            getUrlByDDE( Browser );
        }
        else if( sTitle.find ( (string)OPERA, 0) != string::npos )
        {   // Opera
            Browser = (string)OPERA;
            PageTitle = sTitle.substr(0, sTitle.length() - Browser.length() ) + "";
            Browser = (string)"Opera";
            getUrlByDDE( Browser );
        }
        else
            return false;  // ブラウザが前面にいない → falseを返す
    }
    getWindowPosition( hWnd ); // ブラウザの位置も取得
    if ( previousURL != URL || previousPageTitle != PageTitle )
    {
        isChanged = true;
    }
    else isChanged = false;
    return true;
}
//------Window位置取得---------------------------------
bool BrowserWindow::getWindowPosition( HWND aHwnd )
{
    WINDOWINFO wi;
    if( GetWindowInfo( aHwnd, &wi ) )
    {
        RECT aRect = wi.rcWindow;
        WindowInfo.Left       = aRect.left;
        WindowInfo.Right      = aRect.right;
        WindowInfo.Top        = aRect.top;
        WindowInfo.Bottom     = aRect.bottom;
        WindowInfo.Hwnd       = aHwnd;
    }
    return true;
}
//------DDE経由で取得------------------------------------
bool BrowserWindow::getUrlByDDE( string aBrowser )
{
    DWORD idInst=0;
    if (DdeInitialize(&idInst,DdeCallback,APPCMD_CLIENTONLY,0L) == DMLERR_NO_ERROR)
    {
        LPSTR lpszApplication = aBrowser.begin();
        LPSTR lpszTopic = "WWW_GetWindowInfo";
        HSZ hszApplication = DdeCreateStringHandle(idInst, lpszApplication, CP_WINANSI);
        HSZ hszTopic = DdeCreateStringHandle(idInst, lpszTopic, CP_WINANSI);
        HSZ hszItem  = DdeCreateStringHandle(idInst, "-1", CP_WINANSI);
        if (hszApplication && hszTopic && hszItem)
            {
            HCONV hConv = DdeConnect( idInst, hszApplication, hszTopic, NULL );
            if (hConv)
            {
                HSZ hszItem = DdeCreateStringHandle(idInst, "-1", CP_WINANSI);
                HDDEDATA hData = DdeClientTransaction(NULL, 0, hConv, hszItem,
                                           CF_TEXT, XTYP_REQUEST, 1000, NULL);
                char *pStart = DdeAccessData(hData, NULL);
                if (hData)
                {
                    while (*pStart != '\"') ++pStart;
                    pStart++;
                    char *pEnd = pStart;
                    while (*pEnd != '\"') ++pEnd;
                    *pEnd = 0;
                    URL = pStart;
                }else{ URL = "hData error";}
                DdeDisconnect( hConv );
            }else{ URL = "hConv error";}
        }else{ URL = "hszService && hszTopic && hszItem error";}
        if (hszItem) DdeFreeStringHandle(idInst, hszItem);
        if (hszTopic) DdeFreeStringHandle(idInst, hszTopic);
        if (hszApplication) DdeFreeStringHandle(idInst, hszApplication);
        DdeUninitialize( idInst );
    }
    return true;
}
//------IE Windowからタイトル取得---------------------------------
bool BrowserWindow::getFromIE( string aPageTitle )
{
    char buffer[256];
    HWND child;
    HWND ie;
    if(ie = FindWindow(NULL, aPageTitle.c_str()) )
	    if(child = FindWindowEx(ie,0,"WorkerW",0))
            if(child = FindWindowEx(child, 0,"ReBarWindow32", 0))
                if(child = FindWindowEx(child, 0, "ComboBoxEx32", 0))
                {
                    SendMessage(child,WM_GETTEXT,255, (long)&buffer[0]);
                    URL = buffer;
                }
    return true;
}
//------Sleipnir Windowからタイトル取得------------------------
bool BrowserWindow::getFromSleipnir( string aPageTitle )
{
    char buffer[256];
    HWND child;
    HWND ie;
    if(ie = FindWindow( NULL , aPageTitle.c_str()) )
	    if(child = FindWindowEx(ie,0,"ReBarWindow32",0))
		    if(child = FindWindowEx( child, 0,NULL, "Sleipnir_AddressBar"))
			{
                if(child = FindWindowEx(child, 0, "ComboBox", 0))
			     {
						SendMessage(child,WM_GETTEXT,255, (long)&buffer[0]);
						URL = buffer;
			     }
            }
    return true;
}
//------Sleipnir2 Windowからタイトル取得-----------------------
bool BrowserWindow::getFromSleipnir2( string aPageTitle )
{
    char buffer[256];
    HWND child;
    HWND ie;
    if(ie = FindWindow( NULL , aPageTitle.c_str()) )
	{
        if(child = FindWindowEx(ie,0,"ReBarWindow32",0))
		{
            if(child = FindWindowEx( child, 0,"FenrirAdressBarCtrl",NULL))
			{
                if(child = FindWindowEx(child, 0, "FenrirComboBoxCtrl", 0))
			     {
                    if(child = FindWindowEx(child, 0, "Edit", 0))
                    {
						SendMessage(child,WM_GETTEXT,255, (long)&buffer[0]);
						URL = buffer;
                    }
			     }
            }
        }
    }
    return true;
}
