Пример #1
0
HRESULT AddLoggingMsg(TCHAR* ptcDeviceName, UCHAR* pucMacAddr, FILETIME ft, TCHAR* ptcMessage)
{
    HRESULT		hr = S_OK;
    SYSTEMTIME  SystemTime;
    FILETIME	LocalTime;

    EnterCriticalSection(&g_LogMsgQueue.Lock);

    // If the list is full
    if(g_LogMsgQueue.dwNewMsgIdx - g_LogMsgQueue.dwOldMsgIdx == -1)
    {
        g_LogMsgQueue.dwNewMsgIdx = g_LogMsgQueue.dwOldMsgIdx;

        // Check if we should wrap around the array
        if(g_LogMsgQueue.dwOldMsgIdx == WZCLOG_ENTRIES - 1)
        {
            g_LogMsgQueue.dwOldMsgIdx = 0;
        }
        else
        {
            g_LogMsgQueue.dwOldMsgIdx++;
        }
    }
    // If the list is empty
    else if(g_LogMsgQueue.dwOldMsgIdx == -1 && g_LogMsgQueue.dwNewMsgIdx == -1)
    {
        g_LogMsgQueue.dwNewMsgIdx = 0;
    }
    // If the list has one entry
    else if(g_LogMsgQueue.dwOldMsgIdx == -1)
    {
        g_LogMsgQueue.dwNewMsgIdx++;
        g_LogMsgQueue.dwOldMsgIdx = 0;
    }
    else
    {
        // Check if we should wrap around the array
        if(g_LogMsgQueue.dwNewMsgIdx == WZCLOG_ENTRIES - 1)
        {
            g_LogMsgQueue.dwOldMsgIdx++;
            g_LogMsgQueue.dwNewMsgIdx = 0;
        }
        else
        {
            g_LogMsgQueue.dwNewMsgIdx++;
        }
    }

    FileTimeToLocalFileTime(&ft, &LocalTime);
    FileTimeToSystemTime(&LocalTime, &SystemTime);

    PREFAST_ASSERT(g_LogMsgQueue.dwNewMsgIdx < WZCLOG_ENTRIES);

    if(pucMacAddr == NULL)
    {
        _sntprintf(g_LogMsgQueue.pszList[g_LogMsgQueue.dwNewMsgIdx], LOG_STATUS_SIZE, TEXT("[%02d:%02d:%02d - %s] %s"),
                   SystemTime.wHour,
                   SystemTime.wMinute,
                   SystemTime.wSecond,
                   ptcDeviceName,
                   ptcMessage);
    }
    else
    {
        _sntprintf(g_LogMsgQueue.pszList[g_LogMsgQueue.dwNewMsgIdx], LOG_STATUS_SIZE, TEXT("[%02d:%02d:%02d - %s] %s - AP [%02x-%02x-%02x-%02x-%02x-%02x]"),
                   SystemTime.wHour,
                   SystemTime.wMinute,
                   SystemTime.wSecond,
                   ptcDeviceName,
                   ptcMessage,
                   pucMacAddr[0],
                   pucMacAddr[1],
                   pucMacAddr[2],
                   pucMacAddr[3],
                   pucMacAddr[4],
                   pucMacAddr[5]);
    }

    // Update dialog if it is visible
    if(g_LogMsgQueue.dwState == WZCLOG_ACTIVE)
    {
        UpdateWZCLogView();
    }

    LeaveCriticalSection(&g_LogMsgQueue.Lock);

    return hr;

} // AddLoggingMsg
Пример #2
0
/**
 * Instantiate a new window.
 * @param full_screen Whether to make a full screen window or not.
 * @return True if the window could be created.
 */
bool VideoDriver_Win32::MakeWindow(bool full_screen)
{
	_fullscreen = full_screen;

	/* recreate window? */
	if ((full_screen || _wnd.fullscreen) && _wnd.main_wnd) {
		DestroyWindow(_wnd.main_wnd);
		_wnd.main_wnd = 0;
	}

#if defined(WINCE)
	/* WinCE is always fullscreen */
#else
	if (full_screen) {
		DEVMODE settings;

		/* Make sure we are always at least the screen-depth of the blitter */
		if (_fullscreen_bpp < BlitterFactory::GetCurrentBlitter()->GetScreenDepth()) _fullscreen_bpp = BlitterFactory::GetCurrentBlitter()->GetScreenDepth();

		memset(&settings, 0, sizeof(settings));
		settings.dmSize = sizeof(settings);
		settings.dmFields =
			(_fullscreen_bpp != 0 ? DM_BITSPERPEL : 0) |
			DM_PELSWIDTH |
			DM_PELSHEIGHT |
			(_display_hz != 0 ? DM_DISPLAYFREQUENCY : 0);
		settings.dmBitsPerPel = _fullscreen_bpp;
		settings.dmPelsWidth  = _wnd.width_org;
		settings.dmPelsHeight = _wnd.height_org;
		settings.dmDisplayFrequency = _display_hz;

		/* Check for 8 bpp support. */
		if (settings.dmBitsPerPel != 32 && ChangeDisplaySettings(&settings, CDS_FULLSCREEN | CDS_TEST) != DISP_CHANGE_SUCCESSFUL) {
			settings.dmBitsPerPel = 32;
		}

		/* Test fullscreen with current resolution, if it fails use desktop resolution. */
		if (ChangeDisplaySettings(&settings, CDS_FULLSCREEN | CDS_TEST) != DISP_CHANGE_SUCCESSFUL) {
			RECT r;
			GetWindowRect(GetDesktopWindow(), &r);
			/* Guard against recursion. If we already failed here once, just fall through to
			 * the next ChangeDisplaySettings call which will fail and error out appropriately. */
			if ((int)settings.dmPelsWidth != r.right - r.left || (int)settings.dmPelsHeight != r.bottom - r.top) {
				return this->ChangeResolution(r.right - r.left, r.bottom - r.top);
			}
		}

		if (ChangeDisplaySettings(&settings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL) {
			this->MakeWindow(false);  // don't care about the result
			return false;  // the request failed
		}
	} else if (_wnd.fullscreen) {
		/* restore display? */
		ChangeDisplaySettings(NULL, 0);
		/* restore the resolution */
		_wnd.width = _bck_resolution.width;
		_wnd.height = _bck_resolution.height;
	}
#endif

	{
		RECT r;
		DWORD style, showstyle;
		int w, h;

		showstyle = SW_SHOWNORMAL;
		_wnd.fullscreen = full_screen;
		if (_wnd.fullscreen) {
			style = WS_POPUP;
			SetRect(&r, 0, 0, _wnd.width_org, _wnd.height_org);
		} else {
			style = WS_OVERLAPPEDWINDOW;
			/* On window creation, check if we were in maximize mode before */
			if (_window_maximize) showstyle = SW_SHOWMAXIMIZED;
			SetRect(&r, 0, 0, _wnd.width, _wnd.height);
		}

#if !defined(WINCE)
		AdjustWindowRect(&r, style, FALSE);
#endif
		w = r.right - r.left;
		h = r.bottom - r.top;

		if (_wnd.main_wnd != NULL) {
			if (!_window_maximize) SetWindowPos(_wnd.main_wnd, 0, 0, 0, w, h, SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOMOVE);
		} else {
			TCHAR Windowtitle[50];
			int x = (GetSystemMetrics(SM_CXSCREEN) - w) / 2;
			int y = (GetSystemMetrics(SM_CYSCREEN) - h) / 2;

			_sntprintf(Windowtitle, lengthof(Windowtitle), _T("OpenTTD %s"), MB_TO_WIDE(_openttd_revision));

			_wnd.main_wnd = CreateWindow(_T("OTTD"), Windowtitle, style, x, y, w, h, 0, 0, GetModuleHandle(NULL), 0);
			if (_wnd.main_wnd == NULL) usererror("CreateWindow failed");
			ShowWindow(_wnd.main_wnd, showstyle);
		}
	}

	BlitterFactory::GetCurrentBlitter()->PostResize();

	GameSizeChanged(); // invalidate all windows, force redraw
	return true; // the request succeeded
}
Пример #3
0
void CTeenSpiritDlg::OnTimer(UINT nIDEvent)
{
	PrgAPI* pAPI = PRGAPI();
	SQLManager* pSM = pAPI->GetSQLManager();
	switch (nIDEvent)
	{
	case TMR_InitialDelay:
		SetTimer(TMR_PlayerMonitor, PLAYERMONITOR_TIMER_DELAY, NULL);
		pAPI->GetTrayToolTipDlg();
		KillTimer(nIDEvent);
		{
			TracksFilter tf;
			if (pSM->GetTrackCount(tf) == 0)
			{
				TCHAR url[1000];
				pAPI->GetSiteURL(url, 1000, PrgAPI::SA_Help, _T("emptycollection"));
				CMessageDlg dlg(this);
				dlg.SetText(CMessageDlg::TT_Title, pAPI->GetString(IDS_EMPTYCOLLECTION_TITLE));
				dlg.SetText(CMessageDlg::TT_SubTitle, pAPI->GetString(IDS_EMPTYCOLLECTION_DETAIL));
				dlg.SetHelpLink(pAPI->GetString(IDS_HELP_S), url);
				dlg.SetText(CMessageDlg::TT_ButtonRight, pAPI->GetString(IDS_OK));
				switch (dlg.DoModal())
				{
				case CMessageDlg::RES_Close:
					pAPI->GoToSiteURL(PrgAPI::SA_Help, _T("emptycollection"));
					break;
				case CMessageDlg::RES_Right:
					pAPI->GetActionManager()->ShowAddNewCollectionDlg(this);
					UpdateWindow();
					break;
				}
			}
			if (pAPI->GetOption(OPT_GEN_UseNativeOnlineServices) == -1)
			{
				CMessageDlg dlg(this);
				
				dlg.SetText(CMessageDlg::TT_Title, pAPI->GetString(IDS_OPTIONS));
				dlg.SetText(CMessageDlg::TT_SubTitle, pAPI->GetString(IDS_CONFIRMATION));
				TCHAR bf[1000];
				_sntprintf(bf, 1000, _T("%s (beta)"), pAPI->GetString(IDS_TSONLINESERVICES));
				dlg.SetText(CMessageDlg::TT_CheckBox, bf);
				pAPI->GetSiteURL(bf, 1000, PrgAPI::SA_Navigate, _T("onlineservices-about"));
				dlg.SetHelpLink(pAPI->GetString(IDS_HELP_S), bf);
				dlg.SetCheck(TRUE);
				dlg.SetText(CMessageDlg::TT_ButtonRight, pAPI->GetString(IDS_OK));
				if (dlg.DoModal() != CMessageDlg::RES_Close)
					pAPI->SetOption(OPT_GEN_UseNativeOnlineServices, dlg.IsChecked() ? 1 : 0);
			}
			MediaPlayer* pPlayer = PRGAPI()->GetMediaPlayer();
			m_playerBar.SetMediaPlayer(pPlayer);
			if (pAPI->GetOption(OPT_MINIPLR_ShowAtStartup) != 0)
				pAPI->GetMiniPlayerDlg(TRUE)->Show();
		}
		break;
	case TMR_CheckNewVersion:
		KillTimer(nIDEvent);
		if (pAPI->GetOption(OPT_GEN_CheckForUpdates))
		{
			PrgAPI* pAPI = PRGAPI();
			SYSTEMTIME st;
			GetLocalTime(&st);
			DOUBLE thisDay;
			SystemTimeToVariantTime(&st, &thisDay);
			if (INT(thisDay) - pAPI->GetOption(OPT_GEN_CheckLastCheck) >= pAPI->GetOption(OPT_GEN_DaysBetweenCheck))
			{
				pAPI->SetOption(OPT_GEN_CheckLastCheck, INT(thisDay));
				AfxBeginThread(&NewVersionCheckThreadST, (void*)this ,0 ,0 ,0);
			}
		}
		break;
	case TMR_AutoUpdateDB:
		KillTimer(nIDEvent);
		if (pAPI->GetOption(OPT_GEN_AutoUpdateDB) != 0)
			pAPI->GetCollectionManager()->RefreshLocalCollections(TRUE, FALSE, TRUE);
		break;
	//case COLLECTIONREFRESH_TIMER:
	//	{
	//		PrgAPI* pAPI = PRGAPI();
	//		CollectionManager* pCM = pAPI->GetCollectionManager();
	//		if (pCM->GetState() == CollectionManager::S_Working)
	//		{
	//			const CollectionUpdateJob::Progress prog = pCM->GetProgress();
	//			INT curVal = prog.curPos;
	//			if (curVal - m_lastUpdateActionsPerformed > 100)
	//			{
	//				m_lastUpdateActionsPerformed = curVal;
	//			}
	//		}
	//		else
	//			KillTimer(nIDEvent);
	//	}
	//	break;
	case TMR_HeartBeat://Used by BaseDirector for Send/Post Messages
		pAPI->GetStateManager()->HeartBeat();
		break;
	case TMR_AppMonitor://Used for History Tracking, Download Status Update etc
		pAPI->Monitor();
		break;
	case TMR_PlayerMonitor:
		{
			MediaPlayer::Changes changes = pAPI->GetMediaPlayer()->GetChanges();
			if (changes.tickPlayList >= m_monitorPlayerTick)
				pAPI->GetStateManager()->SendMessage(SM_PlayListChanged);
			if (changes.tickMediaChanged >= m_monitorPlayerTick && m_monitorPlayerTick > 0)
				pAPI->GetStateManager()->SendMessage(SM_MediaChanged);
			m_monitorPlayerTick = GetTickCount();
		}
		break;
	case TMR_ShowTrayTooltipOnMouseMove:
		{
			KillTimer(nIDEvent);
			CPoint ptCurPos;
			GetCursorPos(&ptCurPos);
			if (ptCurPos == m_ptTrayCursorPos)
			{
				pAPI->GetTrayToolTipDlg()->OnMouseOverTray(ptCurPos);
			}
		}
		break;
	default:
		CDialog::OnTimer(nIDEvent);
		break;
	}

}
Пример #4
0
//-----------------------------------------------------------------------------
// Name: GetDXVersion()
// Desc: This function returns the DirectX version.
// Arguments: 
//      pdwDirectXVersion - This can be NULL.  If non-NULL, the return value is:
//              0x00000000 = No DirectX installed
//              0x00010000 = DirectX 1.0 installed
//              0x00020000 = DirectX 2.0 installed
//              0x00030000 = DirectX 3.0 installed
//              0x00030001 = DirectX 3.0a installed
//              0x00050000 = DirectX 5.0 installed
//              0x00060000 = DirectX 6.0 installed
//              0x00060100 = DirectX 6.1 installed
//              0x00060101 = DirectX 6.1a installed
//              0x00070000 = DirectX 7.0 installed
//              0x00070001 = DirectX 7.0a installed
//              0x00080000 = DirectX 8.0 installed
//              0x00080100 = DirectX 8.1 installed
//              0x00080101 = DirectX 8.1a installed
//              0x00080102 = DirectX 8.1b installed
//              0x00080200 = DirectX 8.2 installed
//              0x00090000 = DirectX 9.0 installed
//      strDirectXVersion - Destination string to receive a string name of the DirectX Version.  Can be NULL.
//      cchDirectXVersion - Size of destination buffer in characters.  Length should be at least 10 chars.
// Returns: S_OK if the function succeeds.  
//          E_FAIL if the DirectX version info couldn't be determined.
//
// Please note that this code is intended as a general guideline. Your
// app will probably be able to simply query for functionality (via
// QueryInterface) for one or two components.
//
// Also please ensure your app will run on future releases of DirectX.
// For example:
//     "if( dwDirectXVersion != 0x00080100 ) return false;" is VERY BAD. 
//     "if( dwDirectXVersion < 0x00080100 ) return false;" is MUCH BETTER.
//-----------------------------------------------------------------------------
HRESULT GetDXVersion( DWORD* pdwDirectXVersion, TCHAR* strDirectXVersion, int cchDirectXVersion )
{
    bool bGotDirectXVersion = false;  

    // Init values to unknown
    if( pdwDirectXVersion )
        *pdwDirectXVersion = 0;
    if( strDirectXVersion && cchDirectXVersion > 0 )
        strDirectXVersion[0] = 0;

    DWORD dwDirectXVersionMajor = 0;
    DWORD dwDirectXVersionMinor = 0;
    TCHAR cDirectXVersionLetter = ' ';

    // First, try to use dxdiag's COM interface to get the DirectX version.  
    // The only downside is this will only work on DX9 or later.
    if( SUCCEEDED( GetDirectXVersionViaDxDiag( &dwDirectXVersionMajor, &dwDirectXVersionMinor, &cDirectXVersionLetter ) ) )
        bGotDirectXVersion = true;
  
    if( !bGotDirectXVersion )
    {
        // Getting the DirectX version info from DxDiag failed, 
        // so most likely we are on DX8.x or earlier
        if( SUCCEEDED( GetDirectXVerionViaFileVersions( &dwDirectXVersionMajor, &dwDirectXVersionMinor, &cDirectXVersionLetter ) ) )
            bGotDirectXVersion = true;
    }

    // If both techniques failed, then return E_FAIL
    if( !bGotDirectXVersion )
        return E_FAIL;
        
    // Set the output values to what we got and return       
    cDirectXVersionLetter = (char)tolower(cDirectXVersionLetter);
    
    if( pdwDirectXVersion )
    {
        // If pdwDirectXVersion is non-NULL, then set it to something 
        // like 0x00080102 which would represent DX8.1b
        DWORD dwDirectXVersion = dwDirectXVersionMajor;
        dwDirectXVersion <<= 8;
        dwDirectXVersion += dwDirectXVersionMinor;
        dwDirectXVersion <<= 8;
        if( cDirectXVersionLetter >= 'a' && cDirectXVersionLetter <= 'z' )
            dwDirectXVersion += (cDirectXVersionLetter - 'a') + 1;
        
        *pdwDirectXVersion = dwDirectXVersion;
    }
    
    if( strDirectXVersion && cchDirectXVersion > 0 )
    {
        // If strDirectXVersion is non-NULL, then set it to something 
        // like "8.1b" which would represent DX8.1b
        if( cDirectXVersionLetter == ' ' )
            _sntprintf( strDirectXVersion, cchDirectXVersion, TEXT("%d.%d"), dwDirectXVersionMajor, dwDirectXVersionMinor );
        else
            _sntprintf( strDirectXVersion, cchDirectXVersion, TEXT("%d.%d%c"), dwDirectXVersionMajor, dwDirectXVersionMinor, cDirectXVersionLetter );
        strDirectXVersion[cchDirectXVersion-1] = 0;
    }
    
   return S_OK;
}
Пример #5
0
//加载等级
bool __cdecl CGameRankManager::LoadGameLevel(LPCTSTR pszDirectory, WORD wGameGenre)
{
	//释放等级
	ASSERT(m_bLoadLevel==false);
	if (m_bLoadLevel==true) UnLoadGameLevel();

	//文件目录
	TCHAR szFileName[MAX_PATH]=TEXT("");
	_sntprintf(szFileName,CountArray(szFileName),TEXT("%s\\GameLevel.ini"),pszDirectory);

	//变量定义
	WORD wItemIndex=0;
	TCHAR szItemName[16]=TEXT("");
	TCHAR szReadData[256]=TEXT("");

	//游戏等级
	//if (wGameGenre&(GAME_GENRE_SCORE|(GAME_GENRE_EDUCATE|GAME_GENRE_MATCH|GAME_GENRE_GOLD)))

	//读取资料
	do
	{
		//读取字符
		_sntprintf(szItemName,CountArray(szItemName),TEXT("LevelItem%d"),wItemIndex+1);
		GetPrivateProfileString(TEXT("LevelDescribe"),szItemName,TEXT(""),szReadData,sizeof(szReadData),szFileName);

		//读取字符
		if (szReadData[0]!=0)
		{
			//获取子项
			tagLevelDescribe * pLevelDescribe=CreateLevelDescribe();

			//错误处理
			if (pLevelDescribe==NULL)
			{
				ASSERT(FALSE);
				return false;
			}

			//设置变量
			pLevelDescribe->lLevelScore=0L;
			pLevelDescribe->szLevelName[0]=0;

			//读取等级
			WORD wStringIndex=0,i=0;
			for (i=0;i<CountArray(pLevelDescribe->szLevelName)-1;i++)
			{
				//过虑处理
				if ((szReadData[i]==TEXT(','))||(szReadData[i]==0)) break;
				if ((wStringIndex==0)&&(szReadData[i]==TEXT(' '))) continue;

				//设置字符
				pLevelDescribe->szLevelName[wStringIndex++]=szReadData[i];
			}
			pLevelDescribe->szLevelName[wStringIndex]=0;

			//寻找开始
			LPCTSTR pszScore=&szReadData[i];
			while (((pszScore[0]>0)&&(pszScore[0]<TEXT('0')))||(pszScore[0]>TEXT('9'))) pszScore++;

			//读取积分
			while ((pszScore[0]>=TEXT('0'))&&(pszScore[0]<=TEXT('9')))
			{
				pLevelDescribe->lLevelScore=pLevelDescribe->lLevelScore*10L+pszScore[0]-TEXT('0');
				++pszScore;
			}

			//设置变量
			wItemIndex++;
			m_LevelDescribeActive.Add(pLevelDescribe);
		}
		else break;

	} while (true);

	//设置变量
	if (m_LevelDescribeActive.GetCount()>0L) m_bLoadLevel=true;

	return (m_LevelDescribeActive.GetCount()>0L);
}
Пример #6
0
//读取帐号
void CDlgLogon::LoadAccountsInfo()
{
	//变量定义
	CComboBox * pComBoxAccounts=(CComboBox *)GetDlgItem(IDC_ACCOUNTS);
	CComboBox * pComBoxUserID=(CComboBox *)GetDlgItem(IDC_USER_ID);

	//读取信息
	CRegKey RegUserInfo;
	RegUserInfo.Open(HKEY_CURRENT_USER,REG_USER_INFO,KEY_READ);
	if (RegUserInfo!=NULL)
	{
		int iInsertItem=CB_ERR;
		LONG lErrorCode=ERROR_SUCCESS;
		DWORD dwType=REG_SZ,dwIndex=0,dwUserDBID=0;
		TCHAR szUserIDBuffer[32]=TEXT(""),szTempBuffer[256]=TEXT("");
		do
		{
			//设置变量
			dwUserDBID=0;
			szTempBuffer[0]=0;
			szUserIDBuffer[0]=0;

			//读取游戏 ID
			DWORD dwBufferSize=sizeof(szUserIDBuffer);
			if (RegUserInfo.EnumKey(dwIndex++,szUserIDBuffer,&dwBufferSize,NULL)!=ERROR_SUCCESS) break;
			dwUserDBID=atol(szUserIDBuffer);
			if (dwUserDBID==0) continue;

			//加载其他信息
			CRegKey RegUserAccount;
			_snprintf(szTempBuffer,sizeof(szTempBuffer),TEXT("%s\\%ld"),REG_USER_INFO,dwUserDBID);
			RegUserAccount.Open(HKEY_CURRENT_USER,szTempBuffer,KEY_READ);
			if (RegUserAccount!=NULL)
			{
				//游戏帐号
				dwBufferSize=sizeof(szTempBuffer);
				lErrorCode=RegUserAccount.QueryValue(TEXT("UserAccount"),&dwType,szTempBuffer,&dwBufferSize);
				if ((lErrorCode==ERROR_SUCCESS)&&(szTempBuffer[0]!=0)&&(ComboBoxFindString(pComBoxAccounts,szTempBuffer)==LB_ERR))
				{
					iInsertItem=pComBoxAccounts->AddString(szTempBuffer);
					pComBoxAccounts->SetItemData(iInsertItem,dwUserDBID);
				}

				//游戏 ID
				DWORD dwGameID=0L;
				dwBufferSize=sizeof(dwGameID);
				if ((RegUserAccount.QueryValue(TEXT("GameID"),&dwType,&dwGameID,&dwBufferSize)==ERROR_SUCCESS)&&(dwGameID!=0L))
				{
					_sntprintf(szTempBuffer,CountArray(szTempBuffer),TEXT("%ld"),dwGameID);
					iInsertItem=pComBoxUserID->AddString(szTempBuffer);
					pComBoxUserID->SetItemData(iInsertItem,dwUserDBID);
				}
			}
		} while (true);
	}

	//最近用户
	DWORD dwLastUserID=AfxGetApp()->GetProfileInt(REG_OPTION_LOGON,TEXT("LastUserID"),0L);
	if (dwLastUserID!=0L)
	{
		for (int i=0;i<pComBoxUserID->GetCount();i++)
		{
			DWORD dwComboBoxID=(DWORD)pComBoxUserID->GetItemData(i);
			if ((dwComboBoxID!=0L)&&(dwComboBoxID==dwLastUserID))
			{
				pComBoxUserID->SetCurSel(i);
				UpdateUserComboBox(IDC_USER_ID);
				break;
			}
		}
	}

	//设置选择
	if ((pComBoxUserID->GetCurSel()==LB_ERR)&&(pComBoxUserID->GetCount()>0))
	{
		pComBoxUserID->SetCurSel(0);
		UpdateUserComboBox(IDC_USER_ID);
	}

	//设置选择
	if ((pComBoxAccounts->GetCurSel()==LB_ERR)&&(pComBoxAccounts->GetCount()>0))
	{
		pComBoxAccounts->SetCurSel(0);
		UpdateUserComboBox(IDC_ACCOUNTS);
	}

	return;
}
Пример #7
0
BOOL DSXDeclare(PDeviceDescriptor_t d, Declaration_t *decl, unsigned errBufferLen, TCHAR errBuffer[])
{
  // Must have at least two, max 12 waypoints
  if(decl->num_waypoints < 2) {
    // LKTOKEN  _@M1412_ = "Not enough waypoints!"
    _tcsncpy(errBuffer, MsgToken(1412), errBufferLen);
    return FALSE;
  }
  if(decl->num_waypoints > 12) {
    // LKTOKEN  _@M1413_ = "Too many waypoints!"
    _tcsncpy(errBuffer, MsgToken(1413), errBufferLen);
    return FALSE;
  }

  bool status = true;

  // Stop RX thread
  d->Com->StopRxThread();
  d->Com->SetRxTimeout(3000);                     // set RX timeout to 3000[ms]

  const unsigned BUFF_LEN = 128;
  TCHAR buffer[BUFF_LEN];

  // Enable DSX declaration mode
  // LKTOKEN  _@M1400_ = "Task declaration"
  // LKTOKEN  _@M1401_ = "Enabling declaration mode"
  _sntprintf(buffer, BUFF_LEN, _T("%s: %s..."), MsgToken(1400), MsgToken(1401));
  CreateProgressDialog(buffer);
  status = DSXSwitchDeclareMode(d, true, errBufferLen, errBuffer);

  if(status) {
    // Send user, glider and competition data
    // LKTOKEN  _@M1400_ = "Task declaration"
    // LKTOKEN  _@M1403_ = "Sending  declaration"
    _sntprintf(buffer, BUFF_LEN, _T("%s: %s..."), MsgToken(1400), MsgToken(1403));
    CreateProgressDialog(buffer);
    status = status && DSXHSend(d, *decl, errBufferLen, errBuffer);

    // Send T1 sentence with task general data
    status = status && DSXT1Send(d, *decl, errBufferLen, errBuffer);

    // Send T2 sentence with takeoff, start, finish, landing data
    status = status && DSXT2Send(d, *decl, errBufferLen, errBuffer);

    // Send T3 sentence for each turnpoint
    unsigned tpCount = decl->num_waypoints - 2;   // skip Start and Finish waypoint
    for(unsigned i=0; i<tpCount; i++)
      status = status && DSXT3Send(d, *decl, i, errBufferLen, errBuffer);
  }

  // Disable DSX declaration mode
  // LKTOKEN  _@M1400_ = "Task declaration"
  // LKTOKEN  _@M1402_ = "Disabling declaration mode"
  _sntprintf(buffer, BUFF_LEN, _T("%s: %s..."), MsgToken(1400), MsgToken(1402));
  CreateProgressDialog(buffer);
  status = DSXSwitchDeclareMode(d, false, errBufferLen, errBuffer) && status; // always do that step otherwise NMEA will not be send

  // Restart RX thread
  d->Com->SetRxTimeout(RXTIMEOUT);    // clear timeout
  d->Com->StartRxThread();

  return status;
}
Пример #8
0
HANDLE WINAPI EXP_NAME(OpenPlugin)(int openFrom, INT_PTR item)
{
    PCTSTR filePath;
    auto_ptr<wchar_t> cmdLine;
    auto_ptr<PluginPanelItem> panelItem;
    switch(openFrom) {
        case OPEN_COMMANDLINE:
            {
            if(!item)
                return INVALID_HANDLE_VALUE;
#ifdef FAR3
            cmdLine.reset(_wcsdup(((OpenCommandLineInfo*)item)->CommandLine));
            filePath  = cmdLine.get();
#else
            filePath = (PCTSTR)item;
#endif
            if(!filePath || !*filePath)
	        return INVALID_HANDLE_VALUE;

            if(*filePath == '\"') {
                PTSTR p1 = const_cast<PTSTR>(filePath) + _tcslen(filePath) - 1;
                if(*p1 == '\"')
                    *p1 = 0;
                memmove(const_cast<PTSTR>(filePath), filePath + 1, (p1 - filePath + 1) * sizeof(TCHAR));
            }
            }
            break;

        case OPEN_PLUGINSMENU:
            {
            //assert(item->)
            filePath = JsonPlugin::ClipboardName;
            /*panelItem.reset(GetCurrentItem());
            panelItem->FileName;
            if(!filePath || !*filePath)
                return INVALID_HANDLE_VALUE;*/                
            }
            break;

#ifdef FAR3
        case OPEN_SHORTCUT:
            if(!item)
                return INVALID_HANDLE_VALUE;
	        filePath = ((OpenShortcutInfo*)item)->HostFile;
                break;
#endif
        default:
	    return INVALID_HANDLE_VALUE;
    }

	//SaveScreen ss;
	//PCTSTR Items[]={_T(""),GetMsg(MLoading)};
	//Message(0,NULL,Items,_countof(Items),0);

    // These command lines are possible:
    //   file.json
    //   c:\dir\file.json
    //???   http://site.com/url

    tstring sFilePath( 
#ifdef FAR3
        openFrom == OPEN_SHORTCUT ? ((OpenShortcutInfo*)item)->HostFile : 
#endif
                    filePath);
    tstring sSubDir;
    if(openFrom == OPEN_COMMANDLINE) {
        tstring sCommandLine(filePath);
        size_t colon = sCommandLine.find(':');
        if(colon != tstring::npos) {
            tstring s1 = sCommandLine.substr(0, colon);
            if(GetFileAttributes(s1.c_str()) != 0xffffffff) { // file before 1st colon exists, get the rest 
                sFilePath = s1;
                sSubDir = sCommandLine.substr(colon+1);
            } else {
                colon = sCommandLine.find(':', colon+1);
                sFilePath = sCommandLine.substr(0, colon);
                if(colon != tstring::npos) // second colon exists, get the rest
                    sSubDir = sCommandLine.substr(colon+1);
            }
        }
        TCHAR absPath[MAX_PATH];
#ifdef UNICODE
        if(!wcschr(sFilePath.c_str(), ':')) // if rel path, convert it
        {
            StartupInfo.FSF->ConvertPath(CPM_FULL, sFilePath.c_str(), absPath, _countof(absPath));
#else
        if(GetFileAttributes(sFilePath.c_str()) != 0xffffffff) { // if local file exists, use its abs path
	    _tfullpath(absPath, sFilePath.c_str(), _countof(absPath));
#endif
            sFilePath = absPath;
        }
    }
    JsonPlugin* plugin;
    try
    {
        plugin = new JsonPlugin(sFilePath.c_str());
    }
    catch(WinExcept ex)
    {
        WinError(ex);
        return INVALID_HANDLE_VALUE;
    }
    if(plugin->HasParseError()) {
        auto error = plugin->GetParseError();
        auto eroffs = plugin->GetErrorOffset();
        delete plugin;
        tstring err(GetMsg(error + MParseErrorNone - kParseErrorNone));
        err += '\n';
        LPCTSTR err2 = GetMsg(MParseOffset);
        vector<TCHAR> err3(_tcslen(err2) + 20);
        _sntprintf(&err3[0], err3.size()-1, err2, eroffs); err3[err3.size()-1] = 0;
        err += &err3[0];
        WinError(err.c_str());
        return INVALID_HANDLE_VALUE;
    }
    if(!sSubDir.empty())
	try {
        plugin->SetDirectory(sSubDir.c_str(),0);
	}
	catch(...) {}
    return plugin;
}

#ifdef FAR3
HANDLE WINAPI AnalyseW(const AnalyseInfo *info)
{
    HANDLE h = OpenFilePluginW(info->FileName, (BYTE*)info->Buffer, (int)info->BufferSize, (int)info->OpMode);
    return h == INVALID_HANDLE_VALUE ? NULL : h;
}
Пример #9
0
BOOL CPPgStats::OnApply()
{
	//TODO: cache all parameters. stats should be redrawn (deleted) only if really needed
	if (m_bModified)
	{
		bool bInvalidateGraphs = false;

		if (thePrefs.SetAllStatsColors(m_iStatsColors, m_pdwStatsColors)){
			theApp.emuledlg->ShowTransferRate(true);
			bInvalidateGraphs = true;
		}

		if (thePrefs.GetTrafficOMeterInterval() != (UINT)m_iGraphsUpdate){
			thePrefs.SetTrafficOMeterInterval(m_iGraphsUpdate);
			bInvalidateGraphs = true;
		}
		if (thePrefs.GetStatsInterval() != (UINT)m_iGraphsAvgTime){
			thePrefs.SetStatsInterval(m_iGraphsAvgTime);
			bInvalidateGraphs = true;
		}
		if (thePrefs.GetStatsAverageMinutes() != (UINT)m_iStatsUpdate){
			thePrefs.SetStatsAverageMinutes(m_iStatsUpdate);
			bInvalidateGraphs = true;
		}
		//Xman Xtreme Mod
		if (thePrefs.GetZoomFactor() != m_zoomSlider.GetPos()){
			thePrefs.SetZoomFactor((uint8)m_zoomSlider.GetPos());
			bInvalidateGraphs = true;
		}
		//Xman end

		//Xman smooth-accurate-graph
		thePrefs.usesmoothgraph=IsDlgButtonChecked(IDC_SMOOTH_RADIO)!=0;
		//Xman end

		TCHAR buffer[20];
		GetDlgItem(IDC_CGRAPHSCALE)->GetWindowText(buffer, _countof(buffer));
		UINT statsMax = _tstoi(buffer);
		if (statsMax > thePrefs.GetMaxConnections() + 5)
		{
			if (thePrefs.GetStatsMax() != thePrefs.GetMaxConnections() + 5){
				thePrefs.SetStatsMax(thePrefs.GetMaxConnections() + 5);
				bInvalidateGraphs = true;
			}
			_sntprintf(buffer, _countof(buffer), _T("%d"), thePrefs.GetStatsMax());
			buffer[_countof(buffer) - 1] = _T('\0');
			GetDlgItem(IDC_CGRAPHSCALE)->SetWindowText(buffer);
		}
		else
		{
			if (thePrefs.GetStatsMax() != statsMax){
				thePrefs.SetStatsMax(statsMax);
				bInvalidateGraphs = true;
			}
		}

		int n = m_cratio.GetCurSel();
		UINT uRatio = (n == 5) ? 10 : ((n == 6) ? 20 : n + 1); // Index 5 = 1:10 and 6 = 1:20
		if (thePrefs.GetStatsConnectionsGraphRatio() != uRatio){
			thePrefs.SetStatsConnectionsGraphRatio(uRatio); 
			bInvalidateGraphs = true;
		}

		if (thePrefs.GetFillGraphs() != (IsDlgButtonChecked(IDC_FILL_GRAPHS) == BST_CHECKED)){
			thePrefs.SetFillGraphs(!thePrefs.GetFillGraphs());
			bInvalidateGraphs = true;
		}

		// ==> Source Graph - Stulle
		bool m_bSrcGraph = IsDlgButtonChecked(IDC_SRCGRAPH)!=0;
		if(thePrefs.GetSrcGraph() != m_bSrcGraph){
			thePrefs.m_bSrcGraph = m_bSrcGraph;
			bInvalidateGraphs = true;
		}
		if(GetDlgItem(IDC_STATSHL_MIN)->GetWindowTextLength())
		{
			GetDlgItem(IDC_STATSHL_MIN)->GetWindowText(buffer,20);
			thePrefs.m_iStatsHLMin = (uint16)((_tstoi(buffer)) ? _tstoi(buffer) : 1);
		}
		if(GetDlgItem(IDC_STATSHL_MAX)->GetWindowTextLength())
		{
			GetDlgItem(IDC_STATSHL_MAX)->GetWindowText(buffer,20);
			thePrefs.m_iStatsHLMax = (uint16)((_tstoi(buffer)) ? _tstoi(buffer) : 1);
		}
		thePrefs.m_iStatsHLDif = thePrefs.GetStatsHLMax()-thePrefs.GetStatsHLMin();
		// <== Source Graph - Stulle

		if (bInvalidateGraphs){
			theApp.emuledlg->statisticswnd->UpdateConnectionsGraph(); // Set new Y upper bound and Y ratio for active connections.
			theApp.emuledlg->statisticswnd->Localize();
			theApp.emuledlg->statisticswnd->ShowInterval();
		}
		theApp.emuledlg->statisticswnd->RepaintMeters();
		theApp.emuledlg->statisticswnd->GetDlgItem(IDC_STATTREE)->EnableWindow(thePrefs.GetStatsInterval() > 0);
		SetModified(FALSE);
	}
	return CPropertyPage::OnApply();
}
Пример #10
0
static inline void
StringFormat(TCHAR *buffer, size_t
 size, const TCHAR *fmt, Args&&... args)
{
  _sntprintf(buffer, size, fmt, args...);
}
Пример #11
0
int KTgaBlockLoader::ReadUITex(LPCTSTR pcszUITex, int nLoadStyle, int nFindKind, int TgaInd, int nFrameNum)
{
	int nResult = false;
	int nRetCode = false;
	int nPosed = 0;
	int nIndexCanchangeable = 0;

	KTga32 MyTga;
	LPCTSTR pcszTga;
	TCHAR szTgaName[MAX_PATH];
	szTgaName[0] = _T('\0');

	FILE *fpUiTex = NULL;
	size_t uReadIn;
	UITEXFILEHEADER UiTexFileHeader;

	KAnimateBlock *pAnimate = NULL;
	TCHAR szAnimate[MAX_PATH];
	szAnimate[0] = _T('\0');
	int nBufferSize = 0;

	KTgaBlock *pBlock = NULL;
	TCHAR szName[MAX_PATH];
    TCHAR szFrameName[MAX_PATH];
	szName[0] = _T('\0');
    szFrameName[0] = _T('\0');
	BYTE *pBuffer = NULL;

	UITEXFRAMEDATASTRUCTURE FrameInfo;
	std::vector<UITEXFRAMEDATASTRUCTURE> aFrameVector;

	int i = 0;
	int j = 0;
	int k = 0;

	switch(nLoadStyle) 
	{
	case LOAD_AS_APPEND:
		nPosed = false;
		nIndexCanchangeable = true;
		break;
	case LOAD_AS_REPLACE:
		nPosed = true;
		nIndexCanchangeable = false;
		break;
	default:
		ASSERT(0);
	}

	pcszTga = KTgaBlockLoader::GetSelf().GetTgaName();
	_tcsncpy(szTgaName, pcszTga, sizeof(szTgaName) / sizeof(TCHAR));
	nRetCode = MyTga.CreateFromFile((char *)szTgaName, TRUE);
	KG_PROCESS_ERROR(nRetCode);
	nRetCode = MyTga.ReadAllDataToSelfMemory();
	KG_PROCESS_ERROR(nRetCode);

	fpUiTex = fopen(pcszUITex, "rb");
	KG_PROCESS_ERROR(fpUiTex);

	uReadIn = fread(&UiTexFileHeader, sizeof(UiTexFileHeader), 1, fpUiTex);
	KG_PROCESS_ERROR(uReadIn == 1);

	aFrameVector.reserve(UiTexFileHeader.nFrameCount);
	for (i = 0; i < UiTexFileHeader.nFrameCount; ++i) 
	{
		uReadIn = fread(&FrameInfo, sizeof(FrameInfo), 1, fpUiTex);
		FrameInfo.dwInfo = 0;
		KG_PROCESS_ERROR(uReadIn == 1);
		aFrameVector.push_back(FrameInfo);
	}

	k = 0;
	for (i = 0; i < UiTexFileHeader.nAnimateCount; ++i) 
	{
		int nAnimateFrameCount = 0;
		int nThisAnimateFrame = 0;//¶¯»­Ö¡ÐòºÅ
		uReadIn = fread(&nAnimateFrameCount, sizeof(int), 1, fpUiTex);
		KG_PROCESS_ERROR(uReadIn == 1);

		LPTSTR pcszAnimate = NULL;
		if (k < 0 || k >= m_aNewTgaTxtVector.size())
			_sntprintf(szAnimate, sizeof(szAnimate) / sizeof(TCHAR), "%s:%s%d", pcszUITex, "Animate", i);
		else
		{
			_tcsncpy(szAnimate, m_aNewTgaTxtVector[k].szTxtFile, sizeof(szAnimate)/sizeof(TCHAR));
			pcszAnimate = _tcsrchr(szAnimate, _T('_'));
			if(pcszAnimate)
				*pcszAnimate = _T('\0');
		}
		pAnimate = KAnimateBlock::Create(szAnimate, nIndexCanchangeable, i);
		k += nAnimateFrameCount;
		KG_PROCESS_ERROR(pAnimate); 
		for (j = 0; j < nAnimateFrameCount; ++j)  
		{
			uReadIn = fread(&nThisAnimateFrame, sizeof(int), 1, fpUiTex);
			KG_PROCESS_ERROR(uReadIn == 1);
			KG_PROCESS_ERROR(nThisAnimateFrame < UiTexFileHeader.nFrameCount);
			aFrameVector[nThisAnimateFrame].dwInfo = 1;
			
			if (nThisAnimateFrame >= 0 && nThisAnimateFrame < (int)m_aNewTgaTxtVector.size() && m_aNewTgaTxtVector[nThisAnimateFrame].nTextNum == nThisAnimateFrame)
				_tcsncpy(szName, m_aNewTgaTxtVector[nThisAnimateFrame].szTxtFile, sizeof(szName)/sizeof(TCHAR));
			else				
				_sntprintf(szName, sizeof(szName) / sizeof(TCHAR), "%s_%d", szAnimate, j);
			szName[sizeof(szName) / sizeof(TCHAR) - 1] = _T('\0');
//			if (KTgaManager::GetSelf().IsTgaExist(szName))  
//				continue;
			while (KTgaManager::GetSelf().IsTgaExist(szName))
			{
				TCHAR szNewName[MAX_PATH];
				TCHAR szRelName[MAX_PATH];
				_tcscpy(szNewName, szName);
				LPTSTR pszClip = _tcsrchr((LPTSTR)szNewName, _T('\\'));
				if (pszClip)
				{
					LPTSTR pszTemp = _tcsrchr((LPTSTR)szNewName, _T('/'));
					if (pszTemp)
						pszClip = pszTemp;
				}
				if (pszClip)
					pszClip++;
				else
					pszClip = szNewName;
				_tcscpy(szRelName, pszClip);
				*pszClip = _T('\0');
				_tcscpy(pszClip, _T("(new)"));
				_tcscat(pszClip, szRelName);
				_tcscpy(szName, szNewName);
			}

			nBufferSize = aFrameVector[nThisAnimateFrame].nWidth * aFrameVector[nThisAnimateFrame].nHeight * 4;
			KG_DELETE_ARRAY(pBuffer);
			pBuffer = new BYTE[nBufferSize];
			KG_PROCESS_ERROR(pBuffer);
			MyTga.CopyRectBufferTo(
				pBuffer, nBufferSize, 
				aFrameVector[nThisAnimateFrame].nLeft, aFrameVector[nThisAnimateFrame].nTop, 
				aFrameVector[nThisAnimateFrame].nWidth, aFrameVector[nThisAnimateFrame].nHeight
				);
			pBlock = KTgaBlock::CreateFromBuffer(
				pBuffer, nBufferSize, 
				aFrameVector[nThisAnimateFrame].nWidth, aFrameVector[nThisAnimateFrame].nHeight, 
				aFrameVector[nThisAnimateFrame].nLeft, aFrameVector[nThisAnimateFrame].nTop,
				nIndexCanchangeable, nThisAnimateFrame, nPosed, szName
				);
			KG_PROCESS_ERROR(pBlock);
			if (nFindKind == FIND_ICON_FILE)
			{
				if (nThisAnimateFrame == TgaInd)
				{
					KIconBlock *pIcon = NULL;
					LPCTSTR pcszFrameName = NULL;

                    _tcsncpy(szFrameName, pcszUITex, sizeof(szFrameName) / sizeof(szFrameName[0]));
					pcszFrameName = _tcsrchr(szName, _T('\\'));
					pcszFrameName++;
					m_pIcon = KIconBlock::CreateFromBuffer( 
						pBuffer, nBufferSize, nFrameNum, TgaInd,
						aFrameVector[i].nWidth, aFrameVector[i].nHeight,
                        szName, szFrameName
						);
					nRetCode = KIconManager::GetSelf().Append(m_pIcon);
					KG_PROCESS_ERROR(nRetCode);
					goto Exit1;
				}
			}
			else
			{
				nRetCode = KTgaManager::GetSelf().Append(pBlock);
				KG_PROCESS_ERROR(pBlock);
				nRetCode = pAnimate->AppendFrame(szName);
				KG_PROCESS_ERROR(nRetCode);
			}	
		}
		if (nFindKind == NOT_FIND_ICON_FILE)
		{	
			nRetCode = KAnimateManager::GetSelf().Append(pAnimate);
			KG_PROCESS_ERROR(nRetCode);
		}
	}

	j = 0;
	for (int i = 0; i < UiTexFileHeader.nFrameCount; ++i) 
	{
		if (aFrameVector[i].dwInfo)
			continue;
		aFrameVector[i].dwInfo = 1;

		if (i >= 0 && i < m_aNewTgaTxtVector.size() && m_aNewTgaTxtVector[i].nTextNum == i)
			_tcsncpy(szName, m_aNewTgaTxtVector[i].szTxtFile, sizeof(szName)/sizeof(TCHAR));
		else
			_sntprintf(szName, sizeof(szName) / sizeof(TCHAR), "%s:%s%d", pcszUITex, "Frame", j);
		szName[sizeof(szName) / sizeof(TCHAR) - 1] = _T('\0');
		++j;

		if (KTgaManager::GetSelf().IsTgaExist(szName))  
			continue;
		nBufferSize = aFrameVector[i].nWidth * aFrameVector[i].nHeight * 4;
		KG_DELETE_ARRAY(pBuffer);
		if (nBufferSize == 0)
			continue;
		pBuffer = new BYTE[nBufferSize];
		KG_PROCESS_ERROR(pBuffer);
		MyTga.CopyRectBufferTo(
			pBuffer, nBufferSize, 
			aFrameVector[i].nLeft, aFrameVector[i].nTop, 
			aFrameVector[i].nWidth, aFrameVector[i].nHeight
			);
		pBlock = KTgaBlock::CreateFromBuffer(
			pBuffer, nBufferSize, 
			aFrameVector[i].nWidth, aFrameVector[i].nHeight, 
			aFrameVector[i].nLeft, aFrameVector[i].nTop,
			nIndexCanchangeable, i, nPosed, szName
			);
		if (pBlock)
		{
			if (nFindKind == FIND_ICON_FILE)
			{
				if (i == TgaInd)
				{
					KIconBlock *pIcon = NULL;
					LPCTSTR pcszFrameName = NULL;

					_tcsncpy(szFrameName, pcszUITex, sizeof(szFrameName) / sizeof(szFrameName[0]));
					pcszFrameName = _tcsrchr(szName, _T('\\'));
					pcszFrameName++;
					m_pIcon = KIconBlock::CreateFromBuffer( 
						pBuffer, nBufferSize, nFrameNum, TgaInd,
						aFrameVector[i].nWidth, aFrameVector[i].nHeight,
						szName, szFrameName
						);
					nRetCode = KIconManager::GetSelf().Append(m_pIcon);
					KG_PROCESS_ERROR(nRetCode);
					goto Exit1;
				}
			}
			else
			{
				nRetCode = KTgaManager::GetSelf().Append(pBlock);
				KG_PROCESS_ERROR(pBlock);
			}
		}
	}
	KG_DELETE_ARRAY(pBuffer);
Exit1:
	nResult = true;
Exit0:
	MyTga.Release();
	if (!nResult)
	{   
		if (nLoadStyle == LOAD_AS_REPLACE)
			KSaveManager::GetSelf().Clear();
		KTgaManager::GetSelf().Remove(pBlock);
		KAnimateManager::GetSelf().Remove(pAnimate);
		KG_COM_RELEASE(pBlock);
		KG_COM_RELEASE(pAnimate);

	}
	KG_DELETE_ARRAY(pBuffer);
	if (fpUiTex)
	{
		fclose(fpUiTex);
		fpUiTex = NULL;
	}
	return nResult;
}
Пример #12
0
/* Main window procedure */
static LRESULT CALLBACK
WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch(uMsg) {
        case WM_COMMAND:
            if(HIWORD(wParam) == 0  &&  lParam == 0) {   /* The message came from the menu bar */
                if(LOWORD(wParam) >= 100) {              /* Ignore std. messages like IDCANCEL et al. */
                    TCHAR buffer[64];
                    _sntprintf(buffer, 64, _T("Received WM_COMMAND from menuitem ID %d."), (int) LOWORD(wParam));
                    MessageBox(hWnd, buffer, _T("Click!"), MB_ICONINFORMATION | MB_OK);
                    return 0;
                }
            }
            break;

        case WM_NOTIFY:
        {
            /* Handle notifications for the ReBar control */
            NMHDR* hdr = (NMHDR*) lParam;
            if(hdr->hwndFrom == hwndRebar) {
                switch(hdr->code) {
                    /* Cancel drag'n'drop for the menubar's band, so it is
                     * always on the top just below window caption. */
                    case RBN_BEGINDRAG:
                    {
                        NMREBAR* nm = (NMREBAR*) hdr;
                        if(nm->wID == BAND_MENUBAR)
                            return -1;
                        break;
                    }

                    /* Handle chevron for the menubar's band. */
                    case RBN_CHEVRONPUSHED:
                    {
                        NMREBARCHEVRON* nm = (NMREBARCHEVRON*) hdr;
                        if(nm->wID == BAND_MENUBAR)
                            mcMenubar_HandleRebarChevronPushed(hwndMenubar, nm);
                        break;
                    }
                }
            }
            break;
        }

        case WM_SIZE:
            /* Ensure the ReBar is resized on top of the main window */
            SendMessage(hwndRebar, WM_SIZE, 0, 0);
            break;

        case WM_CREATE:
            CreateMenuBar(hWnd);
            CreateMenuBarSm(hWnd);
            return 0;

        case WM_DESTROY:
            PostQuitMessage(0);
            return 0;
    }

    return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
Пример #13
0
/////////////////////////////////////////////////////////////////////
// 
// Function:    
//
// Description: 
//
/////////////////////////////////////////////////////////////////////
BOOL CAValidateInstall::ValidateExecutable( tstring strExecutable, tstring strDesiredVersion )
{
    DWORD               dwHandle;
    LPVOID              lpData;
    DWORD               dwSize;
    TCHAR               szQuery[256];
    LPVOID              lpVar;
    UINT                uiVarSize;
    VS_FIXEDFILEINFO*   pFileInfo;
    TCHAR               szVersionInfo[24];
    TCHAR               szProductVersion[256];
    TCHAR               szMessage[2048];

    struct LANGANDCODEPAGE {
        WORD wLanguage;
        WORD wCodePage;
    } *lpTranslate;


    _sntprintf(
        szMessage, 
        sizeof(szMessage),
        _T("Validating Executable: '%s' Version: '%s'"),
        strExecutable.c_str(),
        strDesiredVersion.c_str()
    );
    LogMessage(
        INSTALLMESSAGE_INFO,
        NULL, 
        NULL,
        NULL,
        NULL,
        szMessage
    );


    // Get File Version Information
    //
    dwSize = GetFileVersionInfoSize(strExecutable.c_str(), &dwHandle);
    if (dwSize) {
        lpData = (LPVOID)malloc(dwSize);
        if(GetFileVersionInfo(strExecutable.c_str(), dwHandle, dwSize, lpData)) {
            LogMessage(
                INSTALLMESSAGE_INFO,
                NULL, 
                NULL,
                NULL,
                NULL,
                _T("Executable Found")
            );

            // Which language should be used to lookup the structure?
            strcpy(szQuery, _T("\\VarFileInfo\\Translation"));
            VerQueryValue(lpData, szQuery, (LPVOID*)&lpTranslate, &uiVarSize);

            // Version specified as part of the root record.
            if (VerQueryValue(lpData, _T("\\"), (LPVOID*)&pFileInfo, &uiVarSize)) {
                _sntprintf(szVersionInfo, sizeof(szVersionInfo), _T("%d.%d.%d.%d"), 
                    HIWORD(pFileInfo->dwFileVersionMS),
                    LOWORD(pFileInfo->dwFileVersionMS),
                    HIWORD(pFileInfo->dwFileVersionLS),
                    LOWORD(pFileInfo->dwFileVersionLS)
                );
            }

            // Product Version.
            _stprintf(szQuery, _T("\\StringFileInfo\\%04x%04x\\ProductVersion"),
                lpTranslate[0].wLanguage,
                lpTranslate[0].wCodePage
            );
            if (VerQueryValue(lpData, szQuery, &lpVar, &uiVarSize)) {
                uiVarSize = _sntprintf(szProductVersion, sizeof(szProductVersion), _T("%s"), lpVar);
                if ((sizeof(szProductVersion) == uiVarSize) || (-1 == uiVarSize)) {
                    szProductVersion[255] = '\0';
                }
            }

            _sntprintf(
                szMessage, 
                sizeof(szMessage),
                _T("Product Version: '%s'"),
                szProductVersion
            );
            LogMessage(
                INSTALLMESSAGE_INFO,
                NULL, 
                NULL,
                NULL,
                NULL,
                szMessage
            );
            free(lpData);
        }
    }

    if (strDesiredVersion != szProductVersion) {
        return FALSE;
    }
    return TRUE;
}
bool PerfCounterMuninNodePlugin::OpenCounter()
{
  PDH_STATUS status;  

  m_Name = m_SectionName.substr(strlen(PerfCounterMuninNodePlugin::SectionPrefix));

  OSVERSIONINFO osvi;    
  ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
  osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
  if (!GetVersionEx(&osvi) || (osvi.dwPlatformId != VER_PLATFORM_WIN32_NT)) {
	  _Module.LogError("PerfCounter plugin: %s: unknown OS or not NT based", m_Name.c_str());
	  return false; //unknown OS or not NT based
  }

  // Create a PDH query
  status = PdhOpenQuery(NULL, 0, &m_PerfQuery);
  if (status != ERROR_SUCCESS) {
	  _Module.LogError("PerfCounter plugin: %s: PdhOpenQuery error=%x", m_Name.c_str(), status);
	  return false;
  }

  TString objectName = A2TConvert(g_Config.GetValue(m_SectionName, "Object", "LogicalDisk"));
  TString counterName = A2TConvert(g_Config.GetValue(m_SectionName, "Counter", "% Disk Time"));
  
  DWORD counterListLength = 0;  
  DWORD instanceListLength = 0;
  status = PdhEnumObjectItems(NULL, NULL, objectName.c_str(), NULL, &counterListLength, NULL, &instanceListLength, PERF_DETAIL_EXPERT, 0);
  if (status != PDH_MORE_DATA) {
	  _Module.LogError("PerfCounter plugin: %s: PdhEnumObjectItems error=%x", m_Name.c_str(), status);
	  return false;
  }

  TCHAR *counterList = new TCHAR[counterListLength+2];
  TCHAR *instanceList = new TCHAR[instanceListLength+2];
  counterList[0] = NULL;
  instanceList[0] = NULL;
  counterList[1] = NULL;
  instanceList[1] = NULL;

  status = PdhEnumObjectItems(NULL, NULL, objectName.c_str(), counterList, &counterListLength, instanceList, &instanceListLength, PERF_DETAIL_EXPERT, 0);
  if (status != ERROR_SUCCESS) {
    delete [] counterList;
    delete [] instanceList;
	_Module.LogError("PerfCounter plugin: %s: PdhEnumObjectItems error=%x", m_Name.c_str(), status);
    return false;  
  }

  int pos = 0;
  TCHAR *instanceName = instanceList;
  while (instanceName[0] != NULL) {
    std::string counterInstanceName = T2AConvert(instanceName);
    m_CounterNames.push_back(counterInstanceName);
    while (instanceName[0] != NULL)
      instanceName++;
    instanceName++;
  }
  delete [] counterList;
  delete [] instanceList;

  TCHAR counterPath[MAX_PATH] = {0};
  HCOUNTER counterHandle;
  if (!m_CounterNames.empty()) {
    if (g_Config.GetValueB(m_SectionName, "DropTotal", true)) {
      assert(m_CounterNames.back().compare("_Total") == 0);
      // We drop the last instance name as it is _Total
      m_CounterNames.pop_back();
    }

    for (size_t i = 0; i < m_CounterNames.size(); i++) {
      TString instanceNameStr = A2TConvert(m_CounterNames[i]);
      _sntprintf(counterPath, MAX_PATH, _T("\\%s(%s)\\%s"), objectName.c_str(), instanceNameStr.c_str(), counterName.c_str());
      // Associate the uptime counter with the query
      status = PdhAddCounter(m_PerfQuery, counterPath, 0, &counterHandle);
	  if (status != ERROR_SUCCESS) {
		  _Module.LogError("PerfCounter plugin: %s: PDH add counter error=%x", m_Name.c_str(), status);
		  return false;
	  }
      
      m_Counters.push_back(counterHandle);
    }
  } else {
    // A counter with a single instance (Uptime for example)
    m_CounterNames.push_back("0");
    _sntprintf(counterPath, MAX_PATH, _T("\\%s\\%s"), objectName.c_str(), counterName.c_str());
    // Associate the uptime counter with the query
    status = PdhAddCounter(m_PerfQuery, counterPath, 0, &counterHandle);
	if (status != ERROR_SUCCESS) {
		_Module.LogError("PerfCounter plugin: %s: PDH add counter error=%x", m_Name.c_str(), status);
		return false;
	}
    
    m_Counters.push_back(counterHandle);
  }
  
  // Collect init data
  status = PdhCollectQueryData(m_PerfQuery);
  if (status != ERROR_SUCCESS) {
	  if (status == PDH_INVALID_HANDLE) {
		  _Module.LogError("PerfCounter plugin: %s: PDH collect data: PDH_INVALID_HANDLE", m_Name.c_str());
		  return false;
	  }
	  if (status == PDH_NO_DATA) {
		  _Module.LogError("PerfCounter plugin: %s: PDH collect data: PDH_NO_DATA", m_Name.c_str());
		  return false;
	  }
	  _Module.LogError("PerfCounter plugin: %s: PDH collect data error", m_Name.c_str());
	  return false;
  }

  // Setup Counter Format
  m_dwCounterFormat = PDH_FMT_DOUBLE;
  std::string counterFormatStr = g_Config.GetValue(m_SectionName, "CounterFormat", "double");
  if (!counterFormatStr.compare("double")
    || !counterFormatStr.compare("float")) {
    m_dwCounterFormat = PDH_FMT_DOUBLE;

  } else if (!counterFormatStr.compare("int") 
    || !counterFormatStr.compare("long")) {
    m_dwCounterFormat = PDH_FMT_LONG;

  } else if (!counterFormatStr.compare("int64") 
    || !counterFormatStr.compare("longlong") 
    || !counterFormatStr.compare("large")) {
    m_dwCounterFormat = PDH_FMT_LARGE;

  } else {
	  _Module.LogError("PerfCounter plugin: %s: Unknown CounterFormat", m_Name.c_str());
	  assert(!"Unknown CounterFormat!");
  }

  m_CounterMultiply = g_Config.GetValueF(m_SectionName, "CounterMultiply", 1.0);

  return true;
}
Пример #15
0
static void UpdateList(void){
  int i;
 ItemIndex = 0;

  UpLimit= NumberOfAirspaces;
  LowLimit =0;
  FullFlag=false;
  if (TypeFilterIdx>0) {


    if(TypeFilterIdx == AIRSPACECLASSCOUNT+1)
    {
        qsort(AirspaceSelectInfo, NumberOfAirspaces,
               sizeof(AirspaceSelectInfo_t), AirspaceDisabledCompare);
      for (i=0; i<(int)NumberOfAirspaces; i++){
        if (AirspaceSelectInfo[i].airspace->Enabled()  ){
          UpLimit = i;
          break;
        }
    }
    }
    else
    {
      qsort(AirspaceSelectInfo, NumberOfAirspaces,
          sizeof(AirspaceSelectInfo_t), AirspaceTypeCompare);
      for (i=0; i<(int)NumberOfAirspaces; i++){
        if (!(AirspaceSelectInfo[i].Type == TypeFilterIdx-1)){
          UpLimit = i;
          break;
        }
      }
    }
  }

  if (DistanceFilterIdx != 0){

    qsort(AirspaceSelectInfo, UpLimit,
        sizeof(AirspaceSelectInfo_t), AirspaceDistanceCompare);
    for (i=0; i<(int)UpLimit; i++){
      if (AirspaceSelectInfo[i].Distance > DistanceFilter[DistanceFilterIdx]){
        UpLimit = i;
        break;
      }
    }
  }

  if (DirectionFilterIdx != 0){

    qsort(AirspaceSelectInfo, UpLimit,
        sizeof(AirspaceSelectInfo_t), AirspaceDirectionCompare);
    for (i=0; i<UpLimit; i++){
      if (AirspaceSelectInfo[i].DirectionErr > 18){
        UpLimit = i;
        break;
      }
    }
  }


  TCHAR sTmp[EXT_SEARCH_SIZE+1];
  TCHAR wname[EXT_SEARCH_SIZE+1];
  LowLimit = UpLimit;
  qsort(AirspaceSelectInfo, UpLimit,
      sizeof(AirspaceSelectInfo_t), AirspaceNameCompare);

  LK_tcsncpy(sTmp,sNameFilter, NAMEFILTERLEN);
  CharUpper(sTmp);
  int iFilterLen = _tcslen(sNameFilter);

  if (iFilterLen<GC_SUB_STRING_THRESHOLD)
  {
  for (i=0; i<UpLimit; i++){
    // compare entire name which may be more than 4 chars

      LKASSERT(i>=0 && i< NumberOfAirspaces);
	  if(AirspaceSelectInfo[i].airspace->Comment() != NULL)
		_sntprintf(wname,EXT_SEARCH_SIZE,_T("%s"),AirspaceSelectInfo[i].airspace->Comment());
	  else
	    _sntprintf(wname,EXT_NAMESIZE, _T("%s"),AirspaceSelectInfo[i].airspace->Name());

      CharUpper(wname);

    if (_tcsnicmp(wname,sTmp,iFilterLen) >= 0) {
      LowLimit = i;
      break;
    }
  }

  if (_tcscmp(sTmp, TEXT("")) != 0) { // if it's blanks, then leave UpLimit at end of list
    for (; i<UpLimit; i++){

        LKASSERT(i>=0 && i< NumberOfAirspaces);
	  if(AirspaceSelectInfo[i].airspace->Comment() != NULL)
		_sntprintf(wname,EXT_SEARCH_SIZE,_T("%s"),AirspaceSelectInfo[i].airspace->Comment());
	  else
	    _sntprintf(wname,EXT_NAMESIZE, _T("%s"),AirspaceSelectInfo[i].airspace->Name());

      CharUpper(wname);

      if (_tcsnicmp(wname,sTmp,iFilterLen) != 0) {
        UpLimit = i;
        break;
      }
    }
  }
  } else { // iFilterLen>3, fulltext search 100502
      FullFlag=true;
      int matches=0;
      // the AirspaceSelectInfo list has been sorted by filters, and then sorted by name. 0-UpLimit is the size.
      // now we create a secondary index pointing to this list
      for (i=0, matches=0; i<UpLimit; i++) {

          LKASSERT(i>=0 && i< NumberOfAirspaces);
		  if(AirspaceSelectInfo[i].airspace->Comment() != NULL)
			_sntprintf(wname,EXT_SEARCH_SIZE,_T("%s"),AirspaceSelectInfo[i].airspace->Comment());
		  else
		    _sntprintf(wname,EXT_NAMESIZE, _T("%s"),AirspaceSelectInfo[i].airspace->Name());

              CharUpper(wname);

              if ( _tcsstr(  wname,sTmp ) ) {
                      StrIndex[matches++]=i;
              }
      }
      // No need to set flag if no results
      if (matches>0) {
              LowLimit=0;
              UpLimit=matches;
/*
              for (i=0; i<UpLimit; i++)
                      StartupStore(_T("StrIndex[%d] = %d <%s>\n"), i, StrIndex[i], WayPointList[WayPointSelectInfo[StrIndex[i]].Index].Name);
*/
      } else {
              LowLimit=0;
              UpLimit=0;
      }

  }

  wAirspaceList->ResetList();
  wAirspaceList->Redraw();

}
Пример #16
0
int OpenDebugLog()
{
#if defined (FBA_DEBUG)
 #if defined (APP_DEBUG_LOG)

    time_t nTime;
	tm* tmTime;

	time(&nTime);
	tmTime = localtime(&nTime);

	{
		// Initialise the debug log file

  #ifdef _UNICODE
		DebugLog = _tfopen(_T("zzBurnDebug.html"), _T("wb"));

		if (ftell(DebugLog) == 0) {
			WRITE_UNICODE_BOM(DebugLog);

			_ftprintf(DebugLog, _T("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">"));
			_ftprintf(DebugLog, _T("<html><head><meta http-equiv=Content-Type content=\"text/html; charset=unicode\"></head><body><pre>"));
		}
  #else
		DebugLog = _tfopen(_T("zzBurnDebug.html"), _T("wt"));

		if (ftell(DebugLog) == 0) {
			_ftprintf(DebugLog, _T("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">"));
			_ftprintf(DebugLog, _T("<html><head><meta http-equiv=Content-Type content=\"text/html; charset=windows-%i\"></head><body><pre>"), GetACP());
		}
  #endif

		_ftprintf(DebugLog, _T("</font><font size=larger color=#000000>"));
		_ftprintf(DebugLog, _T("Debug log created by ") _T(APP_TITLE) _T(" v%.20s on %s\n<br>"), szAppBurnVer, _tasctime(tmTime));
	}
 #endif

	{
		// Initialise the debug console

		COORD DebugBufferSize = { 80, 1000 };

		{

			// Since AttachConsole is only present in Windows XP, import it manually

#if _WIN32_WINNT >= 0x0500 && defined (_MSC_VER)
// #error Manually importing AttachConsole() function, but compiling with _WIN32_WINNT >= 0x0500
			if (!AttachConsole(ATTACH_PARENT_PROCESS)) {
				AllocConsole();
			}
#else
 #define ATTACH_PARENT_PROCESS ((DWORD)-1)

			BOOL (WINAPI* pAttachConsole)(DWORD dwProcessId) = NULL;
			HINSTANCE hKernel32DLL = LoadLibrary(_T("kernel32.dll"));

			if (hKernel32DLL) {
				pAttachConsole = (BOOL (WINAPI*)(DWORD))GetProcAddress(hKernel32DLL, "AttachConsole");
			}
			if (pAttachConsole) {
				if (!pAttachConsole(ATTACH_PARENT_PROCESS)) {
					AllocConsole();
				}
			} else {
				AllocConsole();
			}
			if (hKernel32DLL) {
				FreeLibrary(hKernel32DLL);
			}

 #undef ATTACH_PARENT_PROCESS
#endif

		}

      DWORD ignore;
		DebugBuffer = CreateConsoleScreenBuffer(GENERIC_WRITE, FILE_SHARE_READ, NULL, CONSOLE_TEXTMODE_BUFFER, NULL);
		SetConsoleScreenBufferSize(DebugBuffer, DebugBufferSize);
		SetConsoleActiveScreenBuffer(DebugBuffer);
		SetConsoleTitle(_T(APP_TITLE) _T(" Debug console"));

		SetConsoleTextAttribute(DebugBuffer, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY);
		_sntprintf(szConsoleBuffer, 1024, _T("Welcome to the ") _T(APP_TITLE) _T(" debug console.\n"));
		WriteConsole(DebugBuffer, szConsoleBuffer, _tcslen(szConsoleBuffer), &ignore, NULL);

		SetConsoleTextAttribute(DebugBuffer, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
		if (DebugLog) {
			_sntprintf(szConsoleBuffer, 1024, _T("Debug messages are logged in zzBurnDebug.html"));
			if (!DebugLog || bEchoLog) {
				_sntprintf(szConsoleBuffer + _tcslen(szConsoleBuffer), 1024 - _tcslen(szConsoleBuffer), _T(", and echod to this console"));
			}
			_sntprintf(szConsoleBuffer + _tcslen(szConsoleBuffer), 1024 - _tcslen(szConsoleBuffer), _T(".\n\n"));
		} else {
			_sntprintf(szConsoleBuffer, 1024, _T("Debug messages are echod to this console.\n\n"));
		}
		WriteConsole(DebugBuffer, szConsoleBuffer, _tcslen(szConsoleBuffer), &ignore, NULL);
	}

	nPrevConsoleStatus = -1;

	bprintf = AppDebugPrintf;							// Redirect Burn library debug to our function
#endif

	return 0;
}
// OUT TCHAR* tFullPath : provided pointer have be at least MAX_PATH TCHAR
BOOL CDllSideBySideAssembyFinder::FindSideBySideAssemby(TCHAR* ImportingModulePath,TCHAR* tWorkingDirectory,TCHAR* tDllName,OUT TCHAR* tFullPath)
{
    *tFullPath=0;
    if (ImportingModulePath == NULL)
        return FALSE;
    if (*ImportingModulePath == NULL)
        return FALSE;

    CPeManifestAssembly PeManifest;
    if (!PeManifest.Parse(ImportingModulePath))
        return FALSE;

    int iCount = PeManifest.GetDependenciesCount();
    if(iCount==0)
    {
        // no dependencies have been found in the manifest.
        return FALSE;
    }
    else
    {
        // get windows dir
        TCHAR WindowsDir[MAX_PATH];
        ::GetWindowsDirectory(WindowsDir, MAX_PATH);
        TCHAR ImportingModuleDirectory[MAX_PATH];
        CStdFileOperations::GetFilePath(ImportingModulePath,ImportingModuleDirectory,MAX_PATH);
        TCHAR ModuleNameWithoutExt[MAX_PATH];
        _tcscpy(ModuleNameWithoutExt,tDllName);
        CStdFileOperations::RemoveFileExt(ModuleNameWithoutExt);
        

        CPeManifestAssemblyIdentity* pIdentity = PeManifest.GetFirstDependency();
        while( pIdentity )
        {
            TCHAR ImportedDllFullPath[MAX_PATH];
            *ImportedDllFullPath = 0;

            //pIdentity->GetName()
            //pIdentity->GetProcessorArchitecture();
            //pIdentity->GetPublicKeyToken();
            //pIdentity->GetType();
            //pIdentity->GetPublicLanguage();
            //pIdentity->GetVersion();
            _tcscpy(ImportedDllFullPath,pIdentity->GetDependencyFullPathWithBackSlash());
            _tcscat(ImportedDllFullPath,tDllName);
            
            if (CStdFileOperations::DoesFileExists(ImportedDllFullPath))
            {
                _tcscpy(tFullPath,ImportedDllFullPath);
                return TRUE;
            }
            // else


            //-----------------------------------------------------------
            // < user's language-culture>
            // Side-by-side searches WinSxS 
            // with language-culture\moduleName.dll
            // with language-culture\moduleName\moduleName.dll

            // < user's language>
            // Side-by-side searches WinSxS 
            // with language\moduleName.dll
            // with language\moduleName\moduleName.dll

            // < system's language-culture>
            //Side-by-side searches WinSxS for the system's language-culture version.
            // with en-us\moduleName.dll
            // with en-us\moduleName\moduleName.dll

            // < system's language>
            //Side-by-side searches WinSxS for the system's language version.
            // with en\moduleName.dll
            // with en\moduleName\moduleName.dll

            // < no language >
            //Side-by-side searches WinSxS for the no language version.
            // with \moduleName.dll
            // with \moduleName\moduleName.dll
            //--------------------------------------------------

            // with language-culture
            TCHAR* Language = _tcsdup(pIdentity->GetPublicLanguage());
            TCHAR* Tmp;

            if (*Language)
            {

                // with language-culture\moduleName.dll
                _tcscpy(ImportedDllFullPath,ImportingModuleDirectory);
                _tcscat(ImportedDllFullPath,Language);
                _tcscat(ImportedDllFullPath,_T("\\"));
                _tcscat(ImportedDllFullPath,tDllName);
                if (CStdFileOperations::DoesFileExists(ImportedDllFullPath))
                {
                    _tcscpy(tFullPath,ImportedDllFullPath);
                    return TRUE;
                }

                // with language-culture\moduleName\moduleName.dll
                _tcscpy(ImportedDllFullPath,ImportingModuleDirectory);
                _tcscat(ImportedDllFullPath,Language);
                _tcscat(ImportedDllFullPath,_T("\\"));
                _tcscat(ImportedDllFullPath,ModuleNameWithoutExt);
                _tcscat(ImportedDllFullPath,_T("\\"));
                _tcscat(ImportedDllFullPath,tDllName);
                if (CStdFileOperations::DoesFileExists(ImportedDllFullPath))
                {
                    _tcscpy(tFullPath,ImportedDllFullPath);
                    return TRUE;
                }

                // with language only
                Tmp=_tcschr(Language,'-');
                if(Tmp)
                    *Tmp=0;

// FIX ME XXX to find
//// create winsxs path
//_sntprintf(ImportedDllFullPath,
//            MAX_PATH,
//            _T("%s\\winsxs\\%s_%s_%s_%s_%s_%s\\"),
//            WindowsDir,
//            pIdentity->GetProcessorArchitecture(),
//            pIdentity->GetName(),
//            pIdentity->GetPublicKeyToken(),
//            pIdentity->GetVersion(),
//            Language,
//            XXX
//            );

                // create winsxs path
                _sntprintf(ImportedDllFullPath,
                            MAX_PATH,
                            _T("%s\\winsxs\\%s_%s_%s_%s_%s_%s"),
                            WindowsDir,
                            pIdentity->GetProcessorArchitecture(),
                            pIdentity->GetName(),
                            pIdentity->GetPublicKeyToken(),
                            pIdentity->GetVersion(),
                            Language,
                            _T("*")
                            );


                WIN32_FIND_DATA DirectoryInfos;
                HANDLE hFind = ::FindFirstFile(ImportedDllFullPath,&DirectoryInfos);
                if ( hFind != INVALID_HANDLE_VALUE)
                {
                    ::FindClose(hFind);

                    _sntprintf(ImportedDllFullPath,
                                MAX_PATH,
                                _T("%s\\winsxs\\%s\\"),
                                WindowsDir,
                                DirectoryInfos.cFileName
                                );
// end of FIX ME XXX to find
                    _tcscat(ImportedDllFullPath,tDllName);
                    if (CStdFileOperations::DoesFileExists(ImportedDllFullPath))
                    {
                        _tcscpy(tFullPath,ImportedDllFullPath);
                        return TRUE;
                    }
                }


                // with language\moduleName.dll
                _tcscpy(ImportedDllFullPath,ImportingModuleDirectory);
                _tcscat(ImportedDllFullPath,Language);
                _tcscat(ImportedDllFullPath,_T("\\"));
                _tcscat(ImportedDllFullPath,tDllName);
                if (CStdFileOperations::DoesFileExists(ImportedDllFullPath))
                {
                    _tcscpy(tFullPath,ImportedDllFullPath);
                    return TRUE;
                }

                // with language\moduleName\moduleName.dll
                _tcscpy(ImportedDllFullPath,ImportingModuleDirectory);
                _tcscat(ImportedDllFullPath,Language);
                _tcscat(ImportedDllFullPath,_T("\\"));
                _tcscat(ImportedDllFullPath,ModuleNameWithoutExt);
                _tcscat(ImportedDllFullPath,_T("\\"));
                _tcscat(ImportedDllFullPath,tDllName);
                if (CStdFileOperations::DoesFileExists(ImportedDllFullPath))
                {
                    _tcscpy(tFullPath,ImportedDllFullPath);
                    return TRUE;
                }
            }

            // with \moduleName\moduleName.dll
            _tcscpy(ImportedDllFullPath,ImportingModuleDirectory);
            _tcscat(ImportedDllFullPath,ModuleNameWithoutExt);
            _tcscat(ImportedDllFullPath,_T("\\"));
            _tcscat(ImportedDllFullPath,tDllName);
            if (CStdFileOperations::DoesFileExists(ImportedDllFullPath))
            {
                _tcscpy(tFullPath,ImportedDllFullPath);
                return TRUE;
            }

            pIdentity = PeManifest.GetNextDependency();
        }
    }
    return FALSE;
}
Пример #18
0
INT_PTR CALLBACK ConfigDlgProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
    case WM_INITDIALOG:
        {
            HWND hTree = GetDlgItem(hDlg, IDC_TREE1);
            TreeView_DeleteAllItems(hTree);
            TVINSERTSTRUCT tvins;
            ::memset(&tvins, 0, sizeof(tvins));
            tvins.item.state = TVIS_EXPANDED;
            tvins.item.mask = TVIF_TEXT | TVIF_STATE;

            tvins.item.pszText = _T("CPU bus devices");
            HTREEITEM itemCpu = TreeView_InsertItem(hTree, &tvins);
            const CBusDevice** device1 = g_pBoard->GetCPUBusDevices();
            ConfigDlg_ListBusDevices(hTree, device1, itemCpu);

            tvins.item.pszText = _T("PPU bus devices");
            HTREEITEM itemPpu = TreeView_InsertItem(hTree, &tvins);
            const CBusDevice** device2 = g_pBoard->GetPPUBusDevices();
            ConfigDlg_ListBusDevices(hTree, device2, itemPpu);

            TreeView_Expand(hTree, itemCpu, TVE_EXPAND);
            TreeView_Expand(hTree, itemPpu, TVE_EXPAND);
        }
        break;
    case WM_NOTIFY:
        if (((LPNMHDR)lParam)->code == TVN_SELCHANGED)
        {
            LPNMTREEVIEW pnmtv = (LPNMTREEVIEW)lParam;
            const CBusDevice* pDevice = reinterpret_cast<const CBusDevice*>(pnmtv->itemNew.lParam);
            HWND hList = GetDlgItem(hDlg, IDC_LIST1);
            ::SendMessage(hList, LB_RESETCONTENT, 0, 0);
            if (pDevice != NULL)
            {
                const WORD * pRanges = pDevice->GetAddressRanges();
                TCHAR buffer[16];
                while (*pRanges != 0)
                {
                    WORD start = *pRanges;  pRanges++;
                    WORD length = *pRanges;  pRanges++;
                    _sntprintf(buffer, 16, _T("%06o-%06o"), start, start + length - 1);
                    ::SendMessage(hList, LB_INSERTSTRING, (WPARAM) - 1, (LPARAM)buffer);
                }
            }
        }
        break;
    case WM_COMMAND:
        switch (LOWORD(wParam))
        {
        case IDCANCEL:
            EndDialog(hDlg, LOWORD(wParam));
            return (INT_PTR)TRUE;
        default:
            return (INT_PTR)FALSE;
        }
        break;
    }
    return (INT_PTR) FALSE;
}
Пример #19
0
//效验输入
bool CDlgLogon::CheckLogonInput(bool bShowError)
{
	//定义变量
	UINT uControlID=0;
	CString strBuffer;

	try
	{
		//屏幕像素
		RECT reWindowSize;
		GetDesktopWindow()->GetWindowRect(&reWindowSize);
		INT nHeight =reWindowSize.bottom-reWindowSize.top;
		INT nWidth =reWindowSize.right-reWindowSize.left;
		
		//判断像素
		if(nWidth<LESS_SCREEN_W || nHeight<LESS_SCREEN_H)
		{
			TCHAR szInfo[255]=TEXT("");
			_sntprintf(szInfo,CountArray(szInfo),TEXT("屏幕像素需要在%d*%d或以上才可以正常游戏!"),LESS_SCREEN_W,LESS_SCREEN_H);
			throw szInfo;
		}

		//登录服务器
		GetDlgItemText(IDC_SERVER,m_strLogonServer);
		m_strLogonServer.TrimLeft();
		m_strLogonServer.TrimRight();
		if (m_strLogonServer.IsEmpty())
		{
			uControlID=IDC_SERVER;
			throw TEXT("登录服务器不能为空,请重新选择或者输入登录服务器!");
		}

		//登录帐号
		switch (m_LogonMode)
		{
		case LogonMode_Accounts:		//帐号登录
			{
				GetDlgItemText(IDC_ACCOUNTS,strBuffer);
				strBuffer.TrimLeft();
				strBuffer.TrimRight();
				if (strBuffer.IsEmpty())
				{
					uControlID=IDC_ACCOUNTS;
					throw TEXT("用户登录帐号不能为空,请重新输入登录帐号!");
				}
				lstrcpyn(m_szAccounts,strBuffer,CountArray(m_szAccounts));
				break;
			}
		case LogonMode_UserID:			//ID 登录
			{
				GetDlgItemText(IDC_USER_ID,strBuffer);
				strBuffer.TrimLeft();
				strBuffer.TrimRight();
				m_dwUserID=atoi(strBuffer);
				if (m_dwUserID==0L)
				{
					uControlID=IDC_USER_ID;
					throw TEXT("用户登录 ID 不能为空,请重新输入登录 ID !");
				}
				break;
			}
		}

		//用户密码
		if (m_bChangePassWord==true)
		{
			m_bChangePassWord=false;
			GetDlgItemText(IDC_PASSWORD,m_szPassword,CountArray(m_szPassword));
		}
		if (m_szPassword[0]==0)
		{
			uControlID=IDC_PASSWORD;
			throw TEXT("登录密码不能为空,请重新输入登录密码!");
		}

		//代理类型
		CComboBox * pComProxyType=(CComboBox *)GetDlgItem(IDC_PROXY_TYPE);
		enProxyServerType ProxyServerType=(enProxyServerType)pComProxyType->GetItemData(pComProxyType->GetCurSel());

		//代理信息
		tagProxyServerInfo ProxyServerInfo;
		ZeroMemory(&ProxyServerInfo,sizeof(ProxyServerInfo));
		ProxyServerInfo.wProxyPort=GetDlgItemInt(IDC_PROXY_PORT);
		GetDlgItemText(IDC_PROXY_USER,ProxyServerInfo.szUserName,CountArray(ProxyServerInfo.szUserName));
		GetDlgItemText(IDC_PROXY_PASS,ProxyServerInfo.szPassword,CountArray(ProxyServerInfo.szPassword));
		GetDlgItemText(IDC_PROXY_SERVER,ProxyServerInfo.szProxyServer,CountArray(ProxyServerInfo.szProxyServer));

		//效验代理
		if (ProxyServerType!=ProxyType_None)
		{
			//代理地址
			if (ProxyServerInfo.szProxyServer[0]==0)
			{
				ShowInformation(TEXT("代理服务器地址不能为空,请重新输入!"),0,MB_ICONINFORMATION);
				if (m_bNetOption==false) SwitchNetOption(true);
				m_edProxyServer.SetFocus();
				return false;
			}

			//代理端口
			if (ProxyServerInfo.wProxyPort==0)
			{
				ShowInformation(TEXT("请输入代理服务器端口号,例如:1080!"),0,MB_ICONINFORMATION);
				if (m_bNetOption==false) SwitchNetOption(true);
				m_edProxyPort.SetFocus();
				return false;
			}
		}

		//保存配置
		g_GlobalOption.m_ProxyServerType=ProxyServerType;
		g_GlobalOption.m_ProxyServerInfo=ProxyServerInfo;

		return true;
	}
	catch (LPCTSTR pszError)
	{
		if (bShowError)
		{
			ShowWindow(SW_SHOW);
			BringWindowToTop();
			ShowInformation(pszError,0,MB_ICONQUESTION);
			if (uControlID!=0) GetDlgItem(uControlID)->SetFocus();
		}

	}
	return false;
}
Пример #20
0
LONG CMiniDumper::TopLevelFilter(struct _EXCEPTION_POINTERS* pExceptionInfo)
{
	LONG lRetValue = EXCEPTION_CONTINUE_SEARCH;
	TCHAR szResult[MAX_PATH + 1024] = {0};
	MINIDUMPWRITEDUMP pfnMiniDumpWriteDump = NULL;
	HMODULE hDll = GetDebugHelperDll((FARPROC*)&pfnMiniDumpWriteDump, true);
	if (hDll)
	{
		if (pfnMiniDumpWriteDump)
		{
			// Ask user if they want to save a dump file
			// Do *NOT* localize that string (in fact, do not use MFC to load it)!
			if (MessageBox(NULL, _T("eMule crashed :-(\r\n\r\nA diagnostic file can be created which will help the author to resolve this problem. This file will be saved on your Disk (and not sent).\r\n\r\nDo you want to create this file now?"), m_szAppName, MB_ICONSTOP | MB_YESNO) == IDYES)
			{
				// Create full path for DUMP file
				TCHAR szDumpPath[MAX_PATH];
				_tcsncpy(szDumpPath, m_szDumpDir, _countof(szDumpPath) - 1);
				szDumpPath[_countof(szDumpPath) - 1] = _T('\0');
				size_t uDumpPathLen = _tcslen(szDumpPath);

				TCHAR szBaseName[MAX_PATH];
				_tcsncpy(szBaseName, m_szAppName, _countof(szBaseName) - 1);
				szBaseName[_countof(szBaseName) - 1] = _T('\0');
				size_t uBaseNameLen = _tcslen(szBaseName);

				time_t tNow = time(NULL);
				_tcsftime(szBaseName + uBaseNameLen, _countof(szBaseName) - uBaseNameLen, _T("_%Y%m%d-%H%M%S"), localtime(&tNow));
				szBaseName[_countof(szBaseName) - 1] = _T('\0');

				// Replace spaces and dots in file name.
				LPTSTR psz = szBaseName;
				while (*psz != _T('\0')) {
					if (*psz == _T('.'))
						*psz = _T('-');
					else if (*psz == _T(' '))
						*psz = _T('_');
					psz++;
				}
				if (uDumpPathLen < _countof(szDumpPath) - 1) {
					_tcsncat(szDumpPath, szBaseName, _countof(szDumpPath) - uDumpPathLen - 1);
					szDumpPath[_countof(szDumpPath) - 1] = _T('\0');
					uDumpPathLen = _tcslen(szDumpPath);
					if (uDumpPathLen < _countof(szDumpPath) - 1) {
						_tcsncat(szDumpPath, _T(".dmp"), _countof(szDumpPath) - uDumpPathLen - 1);
						szDumpPath[_countof(szDumpPath) - 1] = _T('\0');
					}
				}

				HANDLE hFile = CreateFile(szDumpPath, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
				if (hFile != INVALID_HANDLE_VALUE)
				{
					_MINIDUMP_EXCEPTION_INFORMATION ExInfo = {0};
					ExInfo.ThreadId = GetCurrentThreadId();
					ExInfo.ExceptionPointers = pExceptionInfo;
					ExInfo.ClientPointers = NULL;

					BOOL bOK = (*pfnMiniDumpWriteDump)(GetCurrentProcess(), GetCurrentProcessId(), hFile, MiniDumpNormal, &ExInfo, NULL, NULL);
					if (bOK)
					{
						// Do *NOT* localize that string (in fact, do not use MFC to load it)!
						//Xman Xtreme Mod
						/*
						_sntprintf(szResult, _countof(szResult) - 1, _T("Saved dump file to \"%s\".\r\n\r\nPlease send this file together with a detailed bug report to [email protected] !\r\n\r\nThank you for helping to improve eMule."), szDumpPath);
						*/
						_sntprintf(szResult, _countof(szResult) - 1, _T("Saved dump file to \"%s\".\r\n\r\nPlease send this file together with a detailed bug report to [email protected] !\r\n\r\nThank you for helping to improve eMule."), szDumpPath);
						//Xman end
						szResult[_countof(szResult) - 1] = _T('\0');
						lRetValue = EXCEPTION_EXECUTE_HANDLER;
					}
					else
					{
						// Do *NOT* localize that string (in fact, do not use MFC to load it)!
						_sntprintf(szResult, _countof(szResult) - 1, _T("Failed to save dump file to \"%s\".\r\n\r\nError: %u"), szDumpPath, GetLastError());
						szResult[_countof(szResult) - 1] = _T('\0');
					}
					CloseHandle(hFile);
				}
				else
				{
					// Do *NOT* localize that string (in fact, do not use MFC to load it)!
					_sntprintf(szResult, _countof(szResult) - 1, _T("Failed to create dump file \"%s\".\r\n\r\nError: %u"), szDumpPath, GetLastError());
					szResult[_countof(szResult) - 1] = _T('\0');
				}
			}
		}
		FreeLibrary(hDll);
		hDll = NULL;
		pfnMiniDumpWriteDump = NULL;
	}

	if (szResult[0] != _T('\0'))
		MessageBox(NULL, szResult, m_szAppName, MB_ICONINFORMATION | MB_OK);

#ifndef _DEBUG
	// Exit the process only in release builds, so that in debug builds the exceptio is passed to a possible
	// installed debugger
	ExitProcess(0);
#else
	return lRetValue;
#endif
}
Пример #21
0
/** 
 * @brief Connects to the device
 * 
 * @param d Device handle
 * @param errBufSize The size of the buffer for error string
 * @param errBuf The buffer for error string
 * 
 * @return Operation status
 */
bool CDevIMI::Connect(PDeviceDescriptor_t d, unsigned errBufSize, TCHAR errBuf[])
{
  if(_connected)
    if(!Disconnect(d, errBufSize, errBuf))
      return false;
  
  _connected = false;
  memset(&_info, 0, sizeof(_info));
  _serialNumber = 0;
  _parser.Reset();
  
  // check connectivity
  const TMsg *msg = 0;
  for(unsigned i=0; i<IMICOMM_CONNECT_RETRIES_COUNT && (!msg || msg->msgID != MSG_CFG_HELLO); i++) {
    if(Send(d, errBufSize, errBuf, MSG_CFG_HELLO))
      msg = Receive(d, errBufSize, errBuf, 200, 0);
  }
  if(msg) {
    if(msg->msgID == MSG_CFG_HELLO) {
      _serialNumber = msg->sn;
    }
    else {
      // LKTOKEN  _@M1414_ = "Device not responsive!"
      _sntprintf(errBuf, errBufSize, _T("%s"), gettext(_T("_@M1414_")));
      return false;
    }
  }
  else if(errBuf[0] == '\0') {
    // LKTOKEN  _@M1414_ = "Device not responsive!"
    _sntprintf(errBuf, errBufSize, _T("%s"), gettext(_T("_@M1414_")));
    return false;
  }
  
  // configure baudrate
  unsigned long baudRate = d->Com->GetBaudrate();
  if(baudRate == 0U) {
      baudRate = 4800U;
  }
  if(!Send(d, errBufSize, errBuf, MSG_CFG_STARTCONFIG, 0, 0, IMICOMM_BIGPARAM1(baudRate), IMICOMM_BIGPARAM2(baudRate)))
    return false;
  
  // get device info
  msg = 0;
  for(int i = 0; i < 5 && (!msg || msg->msgID != MSG_CFG_DEVICEINFO); i++) {
    if(Send(d, errBufSize, errBuf, MSG_CFG_DEVICEINFO))
      msg = Receive(d, errBufSize, errBuf, 400, sizeof(TDeviceInfo));
  }
  if(msg) {
    if(msg->msgID == MSG_CFG_DEVICEINFO) {
      if(msg->payloadSize == sizeof(TDeviceInfo)) {
        memcpy(&_info, msg->payload, sizeof(TDeviceInfo));
      }
      else if(msg->payloadSize == 16) {
        // old version of the structure
        memset(&_info, 0, sizeof(TDeviceInfo));
        memcpy(&_info, msg->payload, 16);
      }
      _connected = true;
      return true;
    }
  }
  else if(errBuf[0] == '\0') {
    // LKTOKEN  _@M1414_ = "Device not responsive!"
    _sntprintf(errBuf, errBufSize, _T("%s"), gettext(_T("_@M1414_")));
    return false;
  }
  
  return false;
}
Пример #22
0
bool ether_init(void)
{
	TCHAR buf[256];

	// Do nothing if no Ethernet device specified
	const char *name = PrefsFindString("ether");
	if (name == NULL)
		return false;

	ether_multi_mode = PrefsFindInt32("ethermulticastmode");
	ether_use_permanent = PrefsFindBool("etherpermanentaddress");

	// Determine Ethernet device type
	net_if_type = -1;
	if (PrefsFindBool("routerenabled") || strcmp(name, "router") == 0)
		net_if_type = NET_IF_ROUTER;
	else if (strcmp(name, "slirp") == 0)
		net_if_type = NET_IF_SLIRP;
	else if (strcmp(name, "tap") == 0)
		net_if_type = NET_IF_TAP;
	else
		net_if_type = NET_IF_B2ETHER;

	// Initialize NAT-Router
	if (net_if_type == NET_IF_ROUTER) {
		if (!router_init())
			net_if_type = NET_IF_FAKE;
	}

	// Initialize slirp library
	if (net_if_type == NET_IF_SLIRP) {
		if (slirp_init() < 0) {
			WarningAlert(GetString(STR_SLIRP_NO_DNS_FOUND_WARN));
			return false;
		}
	}

	// Open ethernet device
	decltype(tstr(std::declval<const char*>())) dev_name;
	switch (net_if_type) {
	case NET_IF_B2ETHER:
		dev_name = tstr(PrefsFindString("etherguid"));
		if (dev_name == NULL || strcmp(name, "b2ether") != 0)
			dev_name = tstr(name);
		break;
	case NET_IF_TAP:
		dev_name = tstr(PrefsFindString("etherguid"));
		break;
	}
	if (net_if_type == NET_IF_B2ETHER) {
		if (dev_name == NULL) {
			WarningAlert("No ethernet device GUID specified. Ethernet is not available.");
			goto open_error;
		}

		fd = PacketOpenAdapter( dev_name.get(), ether_multi_mode );
		if (!fd) {
			_sntprintf(buf, lengthof(buf), TEXT("Could not open ethernet adapter %s."), dev_name.get());
			WarningAlert(buf);
			goto open_error;
		}

		// Get Ethernet address
		if(!PacketGetMAC(fd,ether_addr,ether_use_permanent)) {
			_sntprintf(buf, lengthof(buf), TEXT("Could not get hardware address of device %s. Ethernet is not available."), dev_name.get());
			WarningAlert(buf);
			goto open_error;
		}
		D(bug("Real ethernet address %02x %02x %02x %02x %02x %02x\n", ether_addr[0], ether_addr[1], ether_addr[2], ether_addr[3], ether_addr[4], ether_addr[5]));

		const char *ether_fake_address;
		ether_fake_address = PrefsFindString("etherfakeaddress");
		if(ether_fake_address && strlen(ether_fake_address) == 12) {
			char sm[10];
			strcpy( sm, "0x00" );
			for( int i=0; i<6; i++ ) {
				sm[2] = ether_fake_address[i*2];
				sm[3] = ether_fake_address[i*2+1];
				ether_addr[i] = (uint8)strtoul(sm,0,0);
			}
			D(bug("Fake ethernet address %02x %02x %02x %02x %02x %02x\n", ether_addr[0], ether_addr[1], ether_addr[2], ether_addr[3], ether_addr[4], ether_addr[5]));
		}
	}
	else if (net_if_type == NET_IF_TAP) {
		if (dev_name == NULL) {
			WarningAlert("No ethernet device GUID specified. Ethernet is not available.");
			goto open_error;
		}

		fd = tap_open_adapter(dev_name.get());
		if (!fd) {
			_sntprintf(buf, lengthof(buf), TEXT("Could not open ethernet adapter %s."), dev_name.get());
			WarningAlert(buf);
			goto open_error;
		}

		if (!tap_check_version(fd)) {
			_sntprintf(buf, lengthof(buf), TEXT("Minimal TAP-Win32 version supported is %d.%d."), TAP_VERSION_MIN_MAJOR, TAP_VERSION_MIN_MINOR);
			WarningAlert(buf);
			goto open_error;
		}

		if (!tap_set_status(fd, true)) {
			WarningAlert("Could not set media status to connected.");
			goto open_error;
		}

		if (!tap_get_mac(fd, ether_addr)) {
			_sntprintf(buf, lengthof(buf), TEXT("Could not get hardware address of device %s. Ethernet is not available."), dev_name.get());
			WarningAlert(buf);
			goto open_error;
		}
		D(bug("Real ethernet address %02x %02x %02x %02x %02x %02x\n", ether_addr[0], ether_addr[1], ether_addr[2], ether_addr[3], ether_addr[4], ether_addr[5]));

		const char *ether_fake_address;
		ether_fake_address = PrefsFindString("etherfakeaddress");
		if (ether_fake_address && strlen(ether_fake_address) == 12) {
			char sm[10];
			strcpy( sm, "0x00" );
			for( int i=0; i<6; i++ ) {
				sm[2] = ether_fake_address[i*2];
				sm[3] = ether_fake_address[i*2+1];
				ether_addr[i] = (uint8)strtoul(sm,0,0);
			}
		}
#if 1
		/*
		  If we bridge the underlying ethernet connection and the TAP
		  device altogether, we have to use a fake address.
		 */
		else {
			ether_addr[0] = 0x52;
			ether_addr[1] = 0x54;
			ether_addr[2] = 0x00;
		}
#endif
		D(bug("Fake ethernet address %02x %02x %02x %02x %02x %02x\n", ether_addr[0], ether_addr[1], ether_addr[2], ether_addr[3], ether_addr[4], ether_addr[5]));
	}
	else if (net_if_type == NET_IF_SLIRP) {
		ether_addr[0] = 0x52;
		ether_addr[1] = 0x54;
		ether_addr[2] = 0x00;
		ether_addr[3] = 0x12;
		ether_addr[4] = 0x34;
		ether_addr[5] = 0x56;
		D(bug("Ethernet address %02x %02x %02x %02x %02x %02x\n", ether_addr[0], ether_addr[1], ether_addr[2], ether_addr[3], ether_addr[4], ether_addr[5]));
	}
	else {
		memcpy( ether_addr, router_mac_addr, 6 );
		D(bug("Fake ethernet address (same as router) %02x %02x %02x %02x %02x %02x\n", ether_addr[0], ether_addr[1], ether_addr[2], ether_addr[3], ether_addr[4], ether_addr[5]));
	}

	// Start packet reception thread
	int_ack = CreateSemaphore( 0, 0, 1, NULL);
	if(!int_ack) {
		WarningAlert("WARNING: Cannot create int_ack semaphore");
		goto open_error;
	}

	// nonsignaled
	int_sig = CreateSemaphore( 0, 0, 1, NULL);
	if(!int_sig) {
		WarningAlert("WARNING: Cannot create int_sig semaphore");
		goto open_error;
	}

	int_sig2 = CreateSemaphore( 0, 0, 1, NULL);
	if(!int_sig2) {
		WarningAlert("WARNING: Cannot create int_sig2 semaphore");
		goto open_error;
	}

	int_send_now = CreateSemaphore( 0, 0, 1, NULL);
	if(!int_send_now) {
		WarningAlert("WARNING: Cannot create int_send_now semaphore");
		goto open_error;
	}

	init_queue();

	if(!allocate_read_packets()) goto open_error;

	// No need to enter wait state if we can avoid it.
	// These all terminate fast.

	InitializeCriticalSectionAndSpinCount( &fetch_csection, 5000 );
	InitializeCriticalSectionAndSpinCount( &queue_csection, 5000 );
	InitializeCriticalSectionAndSpinCount( &send_csection, 5000 );
	InitializeCriticalSectionAndSpinCount( &wpool_csection, 5000 );

	ether_th = (HANDLE)_beginthreadex( 0, 0, ether_thread_feed_int, 0, 0, &ether_tid );
	if (!ether_th) {
		D(bug("Failed to create ethernet thread\n"));
		goto open_error;
	}
	thread_active = true;

	unsigned int dummy;
	unsigned int (WINAPI *receive_func)(void *);
	switch (net_if_type) {
	case NET_IF_SLIRP:
	  receive_func = slirp_receive_func;
	  break;
	default:
	  receive_func = ether_thread_get_packets_nt;
	  break;
	}
	ether_th2 = (HANDLE)_beginthreadex( 0, 0, receive_func, 0, 0, &dummy );
	ether_th1 = (HANDLE)_beginthreadex( 0, 0, ether_thread_write_packets, 0, 0, &dummy );

	// Everything OK
	return true;

 open_error:
	if (thread_active) {
		TerminateThread(ether_th,0);
		ether_th = 0;
		if (int_ack)
			CloseHandle(int_ack);
		int_ack = 0;
		if(int_sig)
			CloseHandle(int_sig);
		int_sig = 0;
		if(int_sig2)
			CloseHandle(int_sig2);
		int_sig2 = 0;
		if(int_send_now)
			CloseHandle(int_send_now);
		int_send_now = 0;
		thread_active = false;
	}
	if (fd) {
		switch (net_if_type) {
		case NET_IF_B2ETHER:
			PacketCloseAdapter(fd);
			break;
		case NET_IF_TAP:
			tap_close_adapter(fd);
			break;
		}
		fd = 0;
	}
	return false;
}
Пример #23
0
// !!UNC
void init_posix_emu(void)
{
	if(!validate_stat_struct) {
		ErrorAlert( "Invalid struct my_stat -- edit posix_emu.h" );
		QuitEmulator();
	}

#if DEBUG_EXTFS
	debug_extfs = PrefsFindInt16("debugextfs");

	debug_extfs = DB_EXTFS_LOUD;

	if(debug_extfs != DB_EXTFS_NONE) {
		extfs_log_open( EXTFS_LOG_FILE_NAME );
	}
#endif

	// We cannot use ExtFS "RootPath" because of the virtual desktop.
	if(PrefsFindBool("enableextfs")) {
		PrefsReplaceString("extfs", "");
	} else {
		PrefsRemoveItem("extfs");
		D(bug("extfs disabled by user\n"));
#if DEBUG_EXTFS
		extfs_log_close();
#endif
		return;
	}

	const char *extdrives = PrefsFindString("extdrives");

	// Set up drive list.
	size_t outinx = 0;
	for( TCHAR letter = TEXT('A'); letter <= TEXT('Z'); letter++ ) {
		if(extdrives && !strchr(extdrives,letter)) continue;
		TCHAR rootdir[20];
		_sntprintf( rootdir, lengthof(rootdir), TEXT("%c:\\"), letter );
		use_streams[ letter - 'A' ] = false;
		switch(GetDriveType(rootdir)) {
			case DRIVE_FIXED:
			case DRIVE_REMOTE:
			case DRIVE_RAMDISK:
				// TODO: NTFS AFP?
				// fall
			case DRIVE_REMOVABLE:
			case DRIVE_CDROM:
				if(outinx < lengthof(host_drive_list)) {
					host_drive_list[outinx] = letter;
					outinx += 2;
				}
		}
	}

	// Set up virtual desktop root.
	// TODO: this should be customizable.
	GetModuleFileName( NULL, virtual_root, lengthof(virtual_root) );
	TCHAR *p = _tcsrchr( virtual_root, TEXT('\\') );
	if(p) {
		_tcscpy( ++p, desktop_name );
	} else {
		// should never happen
		_sntprintf( virtual_root, lengthof(virtual_root), TEXT("C:\\%s"), desktop_name );
	}
	CreateDirectory( virtual_root, 0 );

	// Set up an icon looking like "My Computer"
	// Can be overwritten just like any other folder custom icon.
	if(my_access(custom_icon_name,0) != 0) {
		int fd = my_creat( custom_icon_name, 0 );
		if(fd >= 0) {
			my_close(fd);
			fd = open_rfork( custom_icon_name, O_RDWR|O_CREAT );
			if(fd >= 0) {
				my_write( fd, my_comp_icon, sizeof(my_comp_icon) );
				my_close(fd);
				static uint8 host_finfo[SIZEOF_FInfo];
				uint32 finfo = Host2MacAddr(host_finfo);
				get_finfo(custom_icon_name, finfo, 0, false);
				WriteMacInt16(finfo + fdFlags, kIsInvisible);
				set_finfo(custom_icon_name, finfo, 0, false);
				get_finfo(my_computer, finfo, 0, true);
				WriteMacInt16(finfo + fdFlags, ReadMacInt16(finfo + fdFlags) | kHasCustomIcon);
				set_finfo(my_computer, finfo, 0, true);
			} else {
				my_remove(custom_icon_name);
			}
		}
	}
}
Пример #24
0
BOOL CMuleToolbarCtrl::OnCommand(WPARAM wParam, LPARAM /*lParam*/)
{
	switch (wParam)
	{
		case MP_SELECTTOOLBARBITMAPDIR:{
			TCHAR buffer[MAX_PATH];
			_sntprintf(buffer, _countof(buffer), _T("%s"), thePrefs.GetMuleDirectory(EMULE_TOOLBARDIR));
			buffer[_countof(buffer) - 1] = _T('\0');
			if(SelectDir(m_hWnd, buffer, GetResString(IDS_SELECTTOOLBARBITMAPDIR)))
				thePrefs.SetMuleDirectory(EMULE_TOOLBARDIR, buffer);
			break;
		}
		case MP_CUSTOMIZETOOLBAR:
			Customize();
			break;

		case MP_SELECTTOOLBARBITMAP:
		{
			// we could also load "*.jpg" here, but because of the typical non solid background of JPGs this
			// doesn't make sense here.
			CString strFilter=GetResString(IDS_LOADFILTER_EMTOOLBAR)+ _T(" (");
			for (int f = 0; f < _countof(s_apszTBFiles); f++){
				if (f > 0)
					strFilter += _T(';');
				strFilter += s_apszTBFiles[f];
			}
			strFilter += _T(")|");
			for (int f = 0; f < _countof(s_apszTBFiles); f++){
				if (f > 0)
					strFilter += _T(';');
				strFilter += s_apszTBFiles[f];
			}
			strFilter += _T("||");
			CFileDialog dialog(TRUE, EMULTB_BASEEXT _T(".bmp"), NULL, OFN_HIDEREADONLY | OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST, strFilter, NULL, 0);
			if (IDOK == dialog.DoModal())
				if(thePrefs.GetToolbarBitmapSettings()!=dialog.GetPathName())
				{
					ChangeToolbarBitmap(dialog.GetPathName(), true);
					thePrefs.SetToolbarBitmapSettings(dialog.GetPathName());
				}
			break;
		}

		case MP_LARGEICONS:
			m_sizBtnBmp.cx = m_sizBtnBmp.cy = 32;
			ForceRecalcLayout();
			ChangeToolbarBitmap(thePrefs.GetToolbarBitmapSettings(), true);
			thePrefs.SetToolbarIconSize(m_sizBtnBmp);
			break;

       	case MP_SMALLICONS:
			m_sizBtnBmp.cx = m_sizBtnBmp.cy = 16;
			ForceRecalcLayout();
			ChangeToolbarBitmap(thePrefs.GetToolbarBitmapSettings(), true);
			thePrefs.SetToolbarIconSize(m_sizBtnBmp);
			break;

		case MP_NOTEXTLABELS:
			ForceRecalcLayout();
			ChangeTextLabelStyle(NoLabels, true);
			thePrefs.SetToolbarLabelSettings(NoLabels);
			break;

		case MP_TEXTLABELS:
			ForceRecalcLayout();
			ChangeTextLabelStyle(LabelsBelow, true);
			thePrefs.SetToolbarLabelSettings(LabelsBelow);
			break;

		case MP_TEXTLABELSONRIGHT:
			ForceRecalcLayout();
			ChangeTextLabelStyle(LabelsRight, true);
			thePrefs.SetToolbarLabelSettings(LabelsRight);
			break;

		case MP_SELECT_SKIN_DIR:{
			TCHAR buffer[MAX_PATH];
			_sntprintf(buffer, _countof(buffer), _T("%s"), thePrefs.GetMuleDirectory(EMULE_SKINDIR, false));
			buffer[_countof(buffer) - 1] = _T('\0');
			if(SelectDir(m_hWnd, buffer, GetResString(IDS_SELSKINPROFILEDIR)))
				thePrefs.SetMuleDirectory(EMULE_SKINDIR, buffer);
			break;
		}
		case MP_SELECT_SKIN_FILE:
		{
			CString strFilter=GetResString(IDS_LOADFILTER_EMSKINFILES) + _T(" (");
			for (int f = 0; f < _countof(s_apszSkinFiles); f++){
				if (f > 0)
					strFilter += _T(';');
				strFilter += s_apszSkinFiles[f];
			}
			strFilter += _T(")|");
			for (int f = 0; f < _countof(s_apszSkinFiles); f++){
				if (f > 0)
					strFilter += _T(';');
				strFilter += s_apszSkinFiles[f];
			}
			strFilter += _T("||");
			CFileDialog dialog(TRUE, EMULSKIN_BASEEXT _T(".ini"), NULL, OFN_HIDEREADONLY | OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST, strFilter, NULL, 0);
			if (dialog.DoModal() == IDOK)
			{
				if (thePrefs.GetSkinProfile().CompareNoCase(dialog.GetPathName()) != 0)
					theApp.ApplySkin(dialog.GetPathName());
			}
			break;
		}

		default:
			if (wParam >= MP_TOOLBARBITMAP && wParam < MP_TOOLBARBITMAP + MAX_TOOLBAR_FILES)
			{
				if (thePrefs.GetToolbarBitmapSettings().CompareNoCase(m_astrToolbarPaths[wParam-MP_TOOLBARBITMAP]) != 0)
				{
					ChangeToolbarBitmap(m_astrToolbarPaths[wParam-MP_TOOLBARBITMAP], true);
					thePrefs.SetToolbarBitmapSettings(m_astrToolbarPaths[wParam-MP_TOOLBARBITMAP]);
				}
			}
			else if (wParam >= MP_SKIN_PROFILE && wParam < MP_SKIN_PROFILE + MAX_SKIN_FILES)
			{
				if (thePrefs.GetSkinProfile().CompareNoCase(m_astrSkinPaths[wParam - MP_SKIN_PROFILE]) != 0)
					theApp.ApplySkin(m_astrSkinPaths[wParam - MP_SKIN_PROFILE]);
			}
	}

	return true;
}
Пример #25
0
//获取参数
bool CDlgServerItem::GetModuleInitParameter(tagGameServerInfo * pGameServerInfo, bool bAutoMode)
{
	//效验参数
	ASSERT(pGameServerInfo!=NULL);
	if (pGameServerInfo==NULL) return false;

	//游戏模块
	CGameServiceManagerHelper GameServiceManager;
	GameServiceManager.SetModuleCreateInfo(pGameServerInfo->szServerDLLName,GAME_SERVICE_CREATE_NAME);

	//创建判断
	if (pGameServerInfo->dwNativeVersion==0)
	{
		//构造提示
		TCHAR szString[128]=TEXT("");
		_sntprintf(szString,CountArray(szString),TEXT("[ %s ] 游戏服务器组件还没有安装,请先安装对应的游戏服务器"),pGameServerInfo->szGameName);

		//提示消息
		if (bAutoMode==true) CTraceService::TraceString(szString,TraceLevel_Exception);
		else AfxMessageBox(szString,MB_ICONERROR);

		return false;
	}

	//更新判断
	if (pGameServerInfo->dwNativeVersion!=pGameServerInfo->dwServerVersion)
	{
		//构造提示
		TCHAR szString[128]=TEXT("");
		_sntprintf(szString,CountArray(szString),TEXT("[ %s ] 游戏服务器组件已经更新了,不能继续用于启动房间"),pGameServerInfo->szGameName);

		//提示消息
		if (bAutoMode==true) CTraceService::TraceString(szString,TraceLevel_Exception);
		else AfxMessageBox(szString,MB_ICONERROR);

		return false;
	}

	//加载模块
	if (GameServiceManager.CreateInstance()==false)
	{
		//构造提示
		TCHAR szString[128]=TEXT("");
		_sntprintf(szString,CountArray(szString),TEXT("[ %s ] 服务组件不存在或者加载失败,请重新安装服务组件"),pGameServerInfo->szGameName);

		//提示消息
		if (bAutoMode==true) CTraceService::TraceString(szString,TraceLevel_Exception);
		else AfxMessageBox(szString,MB_ICONERROR);

		return false;
	}

	//模块属性
	GameServiceManager->GetServiceAttrib(m_ModuleInitParameter.GameServiceAttrib);

	//挂接属性
	m_ModuleInitParameter.GameServiceOption.wKindID=pGameServerInfo->wKindID;
	m_ModuleInitParameter.GameServiceOption.wNodeID=pGameServerInfo->wNodeID;
	m_ModuleInitParameter.GameServiceOption.wSortID=pGameServerInfo->wSortID;
	m_ModuleInitParameter.GameServiceOption.wServerID=pGameServerInfo->wServerID;

	//税收配置
	m_ModuleInitParameter.GameServiceOption.lCellScore=pGameServerInfo->lCellScore;
	m_ModuleInitParameter.GameServiceOption.wRevenueRatio=pGameServerInfo->wRevenueRatio;
	m_ModuleInitParameter.GameServiceOption.lServiceScore=pGameServerInfo->lServiceScore;

	//房间配置
	m_ModuleInitParameter.GameServiceOption.lRestrictScore=pGameServerInfo->lRestrictScore;
	m_ModuleInitParameter.GameServiceOption.lMinTableScore=pGameServerInfo->lMinTableScore;
	m_ModuleInitParameter.GameServiceOption.lMinEnterScore=pGameServerInfo->lMinEnterScore;
	m_ModuleInitParameter.GameServiceOption.lMaxEnterScore=pGameServerInfo->lMaxEnterScore;

	//会员限制
	m_ModuleInitParameter.GameServiceOption.cbMinEnterMember=pGameServerInfo->cbMinEnterMember;
	m_ModuleInitParameter.GameServiceOption.cbMaxEnterMember=pGameServerInfo->cbMaxEnterMember;

	//房间配置
	m_ModuleInitParameter.GameServiceOption.dwServerRule=pGameServerInfo->dwServerRule;
	m_ModuleInitParameter.GameServiceOption.dwAttachUserRight=pGameServerInfo->dwAttachUserRight;

	//房间属性
	m_ModuleInitParameter.GameServiceOption.wMaxPlayer=pGameServerInfo->wMaxPlayer;
	m_ModuleInitParameter.GameServiceOption.wTableCount=pGameServerInfo->wTableCount;
	m_ModuleInitParameter.GameServiceOption.wServerPort=pGameServerInfo->wServerPort;
	m_ModuleInitParameter.GameServiceOption.wServerType=pGameServerInfo->wServerType;
	lstrcpyn(m_ModuleInitParameter.GameServiceOption.szServerName,pGameServerInfo->szServerName,LEN_SERVER);

	//分组属性
	m_ModuleInitParameter.GameServiceOption.cbDistributeRule=pGameServerInfo->cbDistributeRule;
	m_ModuleInitParameter.GameServiceOption.wMinDistributeUser=pGameServerInfo->wMinDistributeUser;
	m_ModuleInitParameter.GameServiceOption.wMaxDistributeUser=pGameServerInfo->wMaxDistributeUser;
	m_ModuleInitParameter.GameServiceOption.wDistributeTimeSpace=pGameServerInfo->wDistributeTimeSpace;
	m_ModuleInitParameter.GameServiceOption.wDistributeDrawCount=pGameServerInfo->wDistributeDrawCount;
	m_ModuleInitParameter.GameServiceOption.wDistributeStartDelay=pGameServerInfo->wDistributeStartDelay;

	//连接信息
	lstrcpyn(m_ModuleInitParameter.GameServiceOption.szDataBaseName,pGameServerInfo->szDataBaseName,CountArray(m_ModuleInitParameter.GameServiceOption.szDataBaseName));
	lstrcpyn(m_ModuleInitParameter.GameServiceOption.szDataBaseAddr,pGameServerInfo->szDataBaseAddr,CountArray(m_ModuleInitParameter.GameServiceOption.szDataBaseAddr));

	//数据设置
	UINT uCustomRuleSize=sizeof(m_ModuleInitParameter.GameServiceOption.cbCustomRule);
	CopyMemory(m_ModuleInitParameter.GameServiceOption.cbCustomRule,pGameServerInfo->cbCustomRule,uCustomRuleSize);

	return true;
}
static void
setup_info( struct joystick_info *info, int action )
{
  size_t i;

  switch( action ) {

  case 1:
    info->type = &( settings_current.joystick_1_output );
    info->button[0].setting = &( settings_current.joystick_1_fire_1  );
    info->button[1].setting = &( settings_current.joystick_1_fire_2  );
    info->button[2].setting = &( settings_current.joystick_1_fire_3  );
    info->button[3].setting = &( settings_current.joystick_1_fire_4  );
    info->button[4].setting = &( settings_current.joystick_1_fire_5  );
    info->button[5].setting = &( settings_current.joystick_1_fire_6  );
    info->button[6].setting = &( settings_current.joystick_1_fire_7  );
    info->button[7].setting = &( settings_current.joystick_1_fire_8  );
    info->button[8].setting = &( settings_current.joystick_1_fire_9  );
    info->button[9].setting = &( settings_current.joystick_1_fire_10 );
    info->button[10].setting = &( settings_current.joystick_1_fire_11 );
    info->button[11].setting = &( settings_current.joystick_1_fire_12 );
    info->button[12].setting = &( settings_current.joystick_1_fire_13 );
    info->button[13].setting = &( settings_current.joystick_1_fire_14 );
    info->button[14].setting = &( settings_current.joystick_1_fire_15 );
    for( i = 0; i < NUM_JOY_BUTTONS; i++ )
      _sntprintf( info->button[i].name, 80, "Button %lu",
                  (unsigned long)i + 1 );
    break;

  case 2:
    info->type = &( settings_current.joystick_2_output );
    info->button[0].setting = &( settings_current.joystick_2_fire_1  );
    info->button[1].setting = &( settings_current.joystick_2_fire_2  );
    info->button[2].setting = &( settings_current.joystick_2_fire_3  );
    info->button[3].setting = &( settings_current.joystick_2_fire_4  );
    info->button[4].setting = &( settings_current.joystick_2_fire_5  );
    info->button[5].setting = &( settings_current.joystick_2_fire_6  );
    info->button[6].setting = &( settings_current.joystick_2_fire_7  );
    info->button[7].setting = &( settings_current.joystick_2_fire_8  );
    info->button[8].setting = &( settings_current.joystick_2_fire_9  );
    info->button[9].setting = &( settings_current.joystick_2_fire_10 );
    info->button[10].setting = &( settings_current.joystick_2_fire_11 );
    info->button[11].setting = &( settings_current.joystick_2_fire_12 );
    info->button[12].setting = &( settings_current.joystick_2_fire_13 );
    info->button[13].setting = &( settings_current.joystick_2_fire_14 );
    info->button[14].setting = &( settings_current.joystick_2_fire_15 );
    for( i = 0; i < NUM_JOY_BUTTONS; i++ )
      _sntprintf( info->button[i].name, 80, "Button %lu",
                  (unsigned long)i + 1 );
    break;

  case 3:
    info->type = &( settings_current.joystick_keyboard_output );
    info->button[0].setting = &( settings_current.joystick_keyboard_up  );
    _sntprintf( info->button[0].name, 80, "Button for UP" );
    info->button[1].setting = &( settings_current.joystick_keyboard_down  );
    _sntprintf( info->button[1].name, 80, "Button for DOWN" );
    info->button[2].setting = &( settings_current.joystick_keyboard_left  );
    _sntprintf( info->button[2].name, 80, "Button for LEFT" );
    info->button[3].setting = &( settings_current.joystick_keyboard_right  );
    _sntprintf( info->button[3].name, 80, "Button for RIGHT" );
    info->button[4].setting = &( settings_current.joystick_keyboard_fire  );
    _sntprintf( info->button[4].name, 80, "Button for FIRE" );
    for( i = 5; i < NUM_JOY_BUTTONS; i++ ) info->button[i].setting = NULL;
    break;

  }
}
Пример #27
0
BOOL CALLBACK DlgProc(HWND hwnd,UINT message,WPARAM wParam,LPARAM /* lParam */)
{
	static CUT_FTPClient ftpClient;
	static CUH_Control history;
	static int align = TA_LEFT;
	static int textColor = RGB(0,0,0);
	static int backColor = RGB(255,255,255);
	static HFONT hFont;
	HWND	hwndCheck1;
	int		state;
	LPSTR	pbuf;
	BOOL bTrans = TRUE;


	switch(message)
	{

	case WM_INITDIALOG:
		{


			// set the window icon
			SendMessage(hwnd, WM_SETICON, ICON_SMALL, (LPARAM)LoadIcon(g_hInstance, MAKEINTRESOURCE(IDI_ICON1)));
			SetDlgItemInt(hwnd,IDC_PORT,21, FALSE);



			//attach the history window to the control
			history.AttachHistoryWindow(hwnd,IDC_HISTORY);
			//setup the history window
			history.SetHistoryLength(500);
			hFont = CreateFont(14,0,0,0,500,0,0,0,0,0,0,0,0,_T("Courier New"));
			history.SetFont(hFont);
			SetDlgItemText(hwnd,IDC_EDIT,_T("localhost"));
			SetDlgItemText(hwnd,IDC_EDIT2,_T("anonymous"));// User
			SetDlgItemText(hwnd,IDC_EDIT3,_T("*****@*****.**")); // Password
			SetDlgItemText(hwnd,IDC_EDIT4,_T("")); // account
			SetDlgItemText(hwnd,IDC_QUOTE_DATA,_T("HELP"));

			// the default is to use secure SSL
			CheckDlgButton (hwnd,IDC_SECURE_SSL,BST_CHECKED);

			// The default file transfer structure is file

			CheckRadioButton(hwnd,IDC_RADIO1,IDC_RADIO3,IDC_RADIO1);



			return 1;
		}

	case WM_NCDESTROY:
		{
			//delete the font
			DeleteObject(hFont);
			return 0;
		}

	case WM_COMMAND:
		{

			switch(LOWORD(wParam))
			{

				//connect to an FTP site
			case IDC_CONNECT:
				{

					SetCursor(LoadCursor(NULL, IDC_WAIT));

					history.SetTextColor(RGB(0,0,255));
					history.AddLine("============================================");
					history.SetTextColor(RGB(0,0,0));

					_TCHAR addr[256];
					_TCHAR user [256];
					_TCHAR pass [256];
					_TCHAR account[256];
					int retcode = 11;
					GetDlgItemText(hwnd, IDC_EDIT,addr,256);
					GetDlgItemText(hwnd, IDC_EDIT2,user,256);
					GetDlgItemText(hwnd, IDC_EDIT3,pass,256);
					GetDlgItemText(hwnd, IDC_EDIT4,account,256);

					if (_tcslen(addr) > 0)
					{

						ftpClient.setsMode(IsDlgButtonChecked(hwnd, IDC_SECURE_SSL) ? CUT_FTPClient::FTPES : CUT_FTPClient::FTP);

						ftpClient.SetControlPort (GetDlgItemInt(hwnd,IDC_PORT, &bTrans, FALSE));
						retcode = ftpClient.FTPConnect(addr,user,pass,account);
						if( retcode == UTE_SUCCESS){
							history.AddLine("Connect Success");
							int index = 0;

							// v4.2 changed - was while(1)
							for(;;){
								pbuf = (LPSTR)ftpClient.GetMultiLineResponse(index);
								index++;
								if(pbuf != NULL)
									history.AddLine(pbuf);
								else
									break;
							}
						}
						else{
							// ***************** Change to alarm color ************
							history.SetTextColor(RGB(255,0,0));
							history.AddLine(ftpClient.GetLastResponse ());
							history.AddLine(CUT_ERR::GetErrorString (retcode));
							history.SetTextColor(RGB(0,0,0));
							// change back to black text color
						}
					}

					SetCursor(LoadCursor(NULL, IDC_ARROW));

					return 1;
				}

				//disconnect from an FTP site
			case IDC_DISCONNECT:
				{
					SetCursor(LoadCursor(NULL, IDC_WAIT));

					history.SetTextColor(RGB(0,0,255));
					history.AddLine("============================================");
					history.SetTextColor(RGB(0,0,0));

					if(ftpClient.Close() == UTE_SUCCESS)
						history.AddLine("Disconnect Successful");
					else{
						history.SetTextColor(RGB(255,0,0));
						history.AddLine("Disconnect Failed");
						history.SetTextColor(RGB(0,0,0));
					}
					SetCursor(LoadCursor(NULL, IDC_ARROW));
					return 1;
				}
			case IDC_QUOTE:
				{
					_TCHAR quote[MAX_PATH];
					int retcode = 0;
					GetDlgItemText(hwnd, IDC_QUOTE_DATA,quote,MAX_PATH-1);
					if ((retcode = ftpClient.Quote(quote)) == UTE_SUCCESS)
					{
						int index = 0;

						// v4.2 changed - was while(1)
						for(;;){
							pbuf = (LPSTR)ftpClient.GetMultiLineResponse(index);
							index++;
							if(pbuf != NULL)
								history.AddLine(pbuf);
							else
								break;
						}

					}else{
						history.AddLine(ftpClient.GetLastResponse ());
						history.AddLine(CUT_ERR::GetErrorString (retcode));
					}
					return 1;
				}


				// Send a file to the remote host
			case IDC_SENDFILE:
				{

					SetCursor(LoadCursor(NULL, IDC_WAIT));

					history.SetTextColor(RGB(0,0,255));
					history.AddLine("============================================");
					history.SetTextColor(RGB(0,0,0));

					int		retCode;
					_TCHAR  filetosend[256];
					_TCHAR    fileToSave[256];

					GetDlgItemText(hwnd, IDC_FILENAME,filetosend,256);
					GetDlgItemText(hwnd, IDC_SAVEAS,fileToSave,256);

					retCode = ftpClient.SendFile(filetosend, fileToSave);

					if (retCode == UTE_SUCCESS)
						history.AddLine("Send File Successful");
					else{
						history.SetTextColor(RGB(255,0,0));
						history.AddLine("Send File Failed!");
						history.SetTextColor(RGB(0,0,0));
					}

					SetCursor(LoadCursor(NULL, IDC_ARROW));
					return 1;
				}
			case IDC_TEST_REST:
				{
					_TCHAR	filetoget[MAX_PATH];
					_TCHAR    filetosave[MAX_PATH];


					GetDlgItemText(hwnd, IDC_FILENAME,filetoget,MAX_PATH);
					GetDlgItemText(hwnd, IDC_SAVEAS,filetosave,MAX_PATH);

					int retCode = ftpClient.ResumeReceiveFile(filetoget,filetosave);
					if (retCode == UTE_SUCCESS)
						history.AddLine("Receive file");
					else{
						history.SetTextColor(RGB(255,0,0));
						history.AddLine( CUT_ERR::GetErrorString (retCode));
						history.SetTextColor(RGB(0,0,0));
					}
					return 1;
				}
				// Get file from the remote host
			case IDC_RETRFILE:
				{

					SetCursor(LoadCursor(NULL, IDC_WAIT));

					history.SetTextColor(RGB(0,0,255));
					history.AddLine("============================================");
					history.SetTextColor(RGB(0,0,0));

					int		retCode;
					_TCHAR	filetoget[MAX_PATH];
					_TCHAR  filetosave[MAX_PATH];
					_TCHAR	buf[MAX_PATH];

					GetDlgItemText(hwnd, IDC_FILENAME,filetoget,MAX_PATH);
					GetDlgItemText(hwnd, IDC_SAVEAS,filetosave,MAX_PATH);

					if(*filetoget == '\0') {
						history.AddLine("No file name entered");
						return 1;
					}

					if(*filetosave == ('\0')) {
						_tcscpy(filetosave, filetoget);
					}

					retCode = ftpClient.ReceiveFile(filetoget, filetosave);

					if (retCode == UTE_SUCCESS)
					{
						history.AddLine("Receive File Successful");
						_sntprintf(buf, sizeof(buf),_T("File was saved to %s"),filetosave);
						history.AddLine(buf );
					}

					else
					{
						history.SetTextColor(RGB(255,0,0));
						history.AddLine(CUT_ERR::GetErrorString (retCode));
						history.SetTextColor(RGB(0,0,0));
					}

					SetCursor(LoadCursor(NULL, IDC_ARROW));
					return 1;
				}

				// the FILE transfer structure was selected
			case IDC_RADIO1:
				CheckRadioButton(hwnd,IDC_RADIO1,IDC_RADIO3,IDC_RADIO1);
				ftpClient.SetTransferStructure(0);
				break;

				// The RECORD transfer structure was selected
			case IDC_RADIO2:
				CheckRadioButton(hwnd,IDC_RADIO1,IDC_RADIO3,IDC_RADIO2);
				ftpClient.SetTransferStructure(1);
				break;

			case IDC_RADIO3:
				// The PAGE transfer structure was selected
				CheckRadioButton(hwnd,IDC_RADIO1,IDC_RADIO3,IDC_RADIO3);
				ftpClient.SetTransferStructure(2);
				break;

				// Setting the fire wall mode on or of from when set PASV command will be sent each time we need to call
				// LIST command
				// Not all servers support the firewall mode
			case IDC_FIREWALL:
				hwndCheck1 = GetDlgItem(hwnd,IDC_FIREWALL);
				state = (int)SendMessage(hwndCheck1,BM_GETSTATE,0,0l);
				if(state&BST_CHECKED)
					ftpClient.SetFireWallMode(TRUE);
				else
					ftpClient.SetFireWallMode(FALSE);
				break;

				// Select either Image or ASCII for file Transfer type

			case IDC_TRANSFER_TYPE:
				hwndCheck1 = GetDlgItem(hwnd,IDC_TRANSFER_MODE);
				state = (int)SendMessage(hwndCheck1,BM_GETSTATE,0,0l);
				if(state&BST_CHECKED)
					ftpClient.SetTransferType(1);  // if checked then it is 1 = Image
				else
					ftpClient.SetTransferType(0); // if not Selected then it is 0 = ASCII
				break;

				// GEt the directory information
			case IDC_LIST:
				{

					SetCursor(LoadCursor(NULL, IDC_WAIT));

					history.SetTextColor(RGB(0,0,255));
					history.AddLine("============================================");
					history.SetTextColor(RGB(0,0,0));


					CUT_DIRINFO di;
					char entry[256];
					int RetCode = 0;

					RetCode = ftpClient.GetDirInfo((char*)NULL);


					if (RetCode == UTE_SUCCESS)
					{
						int count = ftpClient.GetDirInfoCount();
						history.AddLine("Current Dir:");
						for(int t=0;t<count;t++){
							ftpClient.GetDirEntry(t,&di);
							_snprintf(entry, sizeof(entry),"%s  %ld %2.2d/%2.2d/%2.2d %2.2d:%2.2d",
								di.fileName,di.fileSize,di.year,di.month,
								di.day,di.hour,di.minute);

							history.AddLine(entry);
						}

					}
					else
					{	history.SetTextColor(RGB(255,0,0));
					history.AddLine(CUT_ERR::GetErrorString (RetCode));
					history.SetTextColor(RGB(0,0,0));
					}


					SetCursor(LoadCursor(NULL, IDC_ARROW));
					return 1;
				}

				// Call the ChDir command  to change the directory
			case 	IDC_CHANGEDIR:
				{

					SetCursor(LoadCursor(NULL, IDC_WAIT));

					history.SetTextColor(RGB(0,0,255));
					history.AddLine(_T("============================================"));
					history.SetTextColor(RGB(0,0,0));

					CUT_DIRINFO di;
					char entry[256];
					_TCHAR dir[256];
					int valRet;
					GetDlgItemText(hwnd, IDC_DIRCHANGE,dir,256);
					if (_tcslen(dir)> 0)
					{
						valRet = ftpClient.ChDir(dir);
						if (valRet  != UTE_SUCCESS){
							history.SetTextColor(RGB(255,0,0));
							history.AddLine(CUT_ERR::GetErrorString (valRet));
							history.SetTextColor(RGB(0,0,0));
						}
						else {
							ftpClient.GetDirInfo((char*)NULL);
							int count = ftpClient.GetDirInfoCount();
							for(int t=0;t<count;t++){
								ftpClient.GetDirEntry(t,&di);
								_snprintf(entry, sizeof(entry),"%s  %ld %2.2d/%2.2d/%2.2d %2.2d:%2.2d",
									di.fileName,di.fileSize,di.year,di.month,
									di.day,di.hour,di.minute);
								history.AddLine(entry);
							}
						}

					}	// User did not  enter any string in the edit box
					else
					{
						_snprintf(entry, sizeof(entry)," Please Enter a directory Name");
						history.SetTextColor(RGB(255,0,0));
						history.AddLine(entry);
						history.SetTextColor(RGB(0,0,0));
					}
					SetCursor(LoadCursor(NULL, IDC_ARROW));
					return 1;
				}

			case IDC_ABOUT:
				{
					DialogBox(g_hInstance, MAKEINTRESOURCE(IDD_ABOUT), hwnd, (DLGPROC )AboutProc);
					return 1;
				}

				//exit the program
			case IDC_EXIT:
				{
					EndDialog(hwnd,0);
					return 1;
				}
			}
			return 0;
		}

	case WM_CLOSE:
		{
			EndDialog(hwnd,0);
			return 1;
		}
	}

	return 0;
}
Пример #28
0
bool CWebServer::CallCGI(CWebClientSocket* pClient, CStringA& hdr, CStringA& body, CStringA& mime)
{
	CString path = pClient->m_path, redir = path;
	if (!ToLocalPath(path, redir)) {
		return false;
	}
	CString ext = CPath(path).GetExtension().MakeLower();
	CPath dir(path);
	dir.RemoveFileSpec();

	CString cgi;
	if (!m_cgi.Lookup(ext, cgi) || !CPath(cgi).FileExists()) {
		return false;
	}

	HANDLE hProcess = GetCurrentProcess();
	HANDLE hChildStdinRd, hChildStdinWr, hChildStdinWrDup = NULL;
	HANDLE hChildStdoutRd, hChildStdoutWr, hChildStdoutRdDup = NULL;

	SECURITY_ATTRIBUTES saAttr;
	ZeroMemory(&saAttr, sizeof(saAttr));
	saAttr.nLength = sizeof(saAttr);
	saAttr.bInheritHandle = TRUE;

	if (CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0)) {
		BOOL fSuccess = DuplicateHandle(hProcess, hChildStdoutRd, hProcess, &hChildStdoutRdDup, 0, FALSE, DUPLICATE_SAME_ACCESS);
		UNUSED_ALWAYS(fSuccess);
		CloseHandle(hChildStdoutRd);
	}

	if (CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0)) {
		BOOL fSuccess = DuplicateHandle(hProcess, hChildStdinWr, hProcess, &hChildStdinWrDup, 0, FALSE, DUPLICATE_SAME_ACCESS);
		UNUSED_ALWAYS(fSuccess);
		CloseHandle(hChildStdinWr);
	}

	STARTUPINFO siStartInfo;
	ZeroMemory(&siStartInfo, sizeof(siStartInfo));
	siStartInfo.cb = sizeof(siStartInfo);
	siStartInfo.hStdError = hChildStdoutWr;
	siStartInfo.hStdOutput = hChildStdoutWr;
	siStartInfo.hStdInput = hChildStdinRd;
	siStartInfo.dwFlags |= STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
	siStartInfo.wShowWindow = SW_HIDE;

	PROCESS_INFORMATION piProcInfo;
	ZeroMemory(&piProcInfo, sizeof(piProcInfo));

	CStringA envstr;

	LPVOID lpvEnv = GetEnvironmentStrings();
	if (lpvEnv) {
		CString str;

		CAtlList<CString> env;
		for (LPTSTR lpszVariable = (LPTSTR)lpvEnv; *lpszVariable; lpszVariable += _tcslen(lpszVariable)+1)
			if (lpszVariable != (LPTSTR)lpvEnv) {
				env.AddTail(lpszVariable);
			}

		env.AddTail(_T("GATEWAY_INTERFACE=CGI/1.1"));
		env.AddTail(_T("SERVER_SOFTWARE=Media Player Classic - Home Cinema/1.6.2.x"));
		env.AddTail(_T("SERVER_PROTOCOL=") + pClient->m_ver);
		env.AddTail(_T("REQUEST_METHOD=") + pClient->m_cmd);
		env.AddTail(_T("PATH_INFO=") + redir);
		env.AddTail(_T("PATH_TRANSLATED=") + path);
		env.AddTail(_T("SCRIPT_NAME=") + redir);
		env.AddTail(_T("QUERY_STRING=") + pClient->m_query);

		if (pClient->m_hdrlines.Lookup(_T("content-type"), str)) {
			env.AddTail(_T("CONTENT_TYPE=") + str);
		}
		if (pClient->m_hdrlines.Lookup(_T("content-length"), str)) {
			env.AddTail(_T("CONTENT_LENGTH=") + str);
		}

		POSITION pos = pClient->m_hdrlines.GetStartPosition();
		while (pos) {
			CString key = pClient->m_hdrlines.GetKeyAt(pos);
			CString value = pClient->m_hdrlines.GetNextValue(pos);
			key.Replace(_T("-"), _T("_"));
			key.MakeUpper();
			env.AddTail(_T("HTTP_") + key + _T("=") + value);
		}

		CString name;
		UINT port;

		if (pClient->GetPeerName(name, port)) {
			str.Format(_T("%d"), port);
			env.AddTail(_T("REMOTE_ADDR=")+name);
			env.AddTail(_T("REMOTE_HOST=")+name);
			env.AddTail(_T("REMOTE_PORT=")+str);
		}

		if (pClient->GetSockName(name, port)) {
			str.Format(_T("%d"), port);
			env.AddTail(_T("SERVER_NAME=")+name);
			env.AddTail(_T("SERVER_PORT=")+str);
		}

		env.AddTail(_T("\0"));

		str = Implode(env, '\0');
		envstr = CStringA(str, str.GetLength());

		FreeEnvironmentStrings((LPTSTR)lpvEnv);
	}

	TCHAR* cmdln = DNew TCHAR[32768];
	_sntprintf(cmdln, 32768, _T("\"%s\" \"%s\""), cgi, path);

	if (hChildStdinRd && hChildStdoutWr)
		if (CreateProcess(
					NULL, cmdln, NULL, NULL, TRUE, 0,
					envstr.GetLength() ? (LPVOID)(LPCSTR)envstr : NULL,
					dir, &siStartInfo, &piProcInfo)) {
			DWORD ThreadId;
			CreateThread(NULL, 0, KillCGI, (LPVOID)piProcInfo.hProcess, 0, &ThreadId);

			static const int BUFFSIZE = 1024;
			DWORD dwRead, dwWritten = 0;

			int i = 0, len = pClient->m_data.GetLength();
			for (; i < len; i += dwWritten)
				if (!WriteFile(hChildStdinWrDup, (LPCSTR)pClient->m_data + i, min(len - i, BUFFSIZE), &dwWritten, NULL)) {
					break;
				}

			CloseHandle(hChildStdinWrDup);
			CloseHandle(hChildStdoutWr);

			body.Empty();

			CStringA buff;
			while (i == len && ReadFile(hChildStdoutRdDup, buff.GetBuffer(BUFFSIZE), BUFFSIZE, &dwRead, NULL) && dwRead) {
				buff.ReleaseBufferSetLength(dwRead);
				body += buff;
			}

			int hdrend = body.Find("\r\n\r\n");
			if (hdrend >= 0) {
				hdr = body.Left(hdrend+2);
				body = body.Mid(hdrend+4);
			}

			CloseHandle(hChildStdinRd);
			CloseHandle(hChildStdoutRdDup);

			CloseHandle(piProcInfo.hProcess);
			CloseHandle(piProcInfo.hThread);
		} else {
			body = _T("CGI Error");
		}

	delete [] cmdln;

	return true;
}
Пример #29
0
void CJabberProto::OnIqResultGetSearchFields( HXML iqNode )
{
	if  ( !searchHandleDlg )
		return;

	LPCTSTR type = xmlGetAttrValue( iqNode, _T("type"));
	if ( !type )
		return;

	if ( !lstrcmp( type, _T("result"))) {
		HXML queryNode = xmlGetNthChild( iqNode, _T("query"), 1 );
		HXML xNode = xmlGetChildByTag( queryNode, "x", "xmlns", _T(JABBER_FEAT_DATA_FORMS));

		ShowWindow(searchHandleDlg,SW_HIDE);
		if ( xNode ) {
			//1. Form
			PostMessage( searchHandleDlg, WM_USER+11, ( WPARAM )xi.copyNode( xNode ), ( LPARAM )0 );
			HXML xcNode = xmlGetNthChild( xNode, _T("instructions"), 1 );
			if ( xcNode )
				SetDlgItemText( searchHandleDlg, IDC_INSTRUCTIONS, xmlGetText( xcNode ));
		}
		else {
			int Order=0;
			for ( int i = 0; ; i++ ) {
				HXML chNode = xmlGetChild( queryNode, i );
				if ( !chNode )
					break;

				if ( !_tcsicmp( xmlGetName( chNode ), _T("instructions")) && xmlGetText( chNode ))
					SetDlgItemText(searchHandleDlg,IDC_INSTRUCTIONS,TranslateTS(xmlGetText( chNode )));
				else if ( xmlGetName( chNode ) ) {
					Data *MyData=(Data*)malloc(sizeof(Data));
					memset(MyData,0,sizeof(Data));

					MyData->Label = mir_tstrdup( xmlGetName( chNode ));
					MyData->Var = mir_tstrdup( xmlGetName( chNode ));
					MyData->defValue = mir_tstrdup(xmlGetText( chNode ));
					MyData->Order = Order;
					if (MyData->defValue) MyData->bReadOnly = TRUE;
					PostMessage(searchHandleDlg,WM_USER+10,(WPARAM)FALSE,(LPARAM)MyData);
					Order++;
		}	}	}
		const TCHAR* szFrom = xmlGetAttrValue( iqNode, _T("from"));
		if (szFrom)
			SearchAddToRecent(szFrom,searchHandleDlg);
		PostMessage(searchHandleDlg,WM_USER+10,(WPARAM)0,(LPARAM)0);
		ShowWindow(searchHandleDlg,SW_SHOW);
	}
	else if ( !lstrcmp( type, _T("error"))) {
		const TCHAR* code=NULL;
		const TCHAR* description=NULL;
		TCHAR buff[255];
		HXML errorNode = xmlGetChild( iqNode, "error");
		if ( errorNode ) {
			code = xmlGetAttrValue( errorNode, _T("code"));
			description=xmlGetText( errorNode );
		}
		_sntprintf(buff,SIZEOF(buff),TranslateT("Error %s %s\r\nPlease select other server"),code ? code : _T(""),description?description:_T(""));
		SetDlgItemText(searchHandleDlg,IDC_INSTRUCTIONS,buff);
	}
	else SetDlgItemText( searchHandleDlg, IDC_INSTRUCTIONS, TranslateT( "Error Unknown reply recieved\r\nPlease select other server" ));
}
Пример #30
0
bool GetGUIDs(std::vector<std::basic_string<TCHAR>>& guids)
{
	LONG status;
	HKEY control_net_key;
	DWORD len;
	DWORD cSubKeys = 0;

	status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, NETWORK_CONNECTIONS_KEY, 0, KEY_READ | KEY_QUERY_VALUE, &control_net_key);

	if (status != ERROR_SUCCESS)
		return false;

	status = RegQueryInfoKey(control_net_key, nullptr, nullptr, nullptr, &cSubKeys, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr);

	if (status != ERROR_SUCCESS)
		return false;

	for (DWORD i = 0; i < cSubKeys; i++)
	{
		TCHAR enum_name[256];
		TCHAR connection_string[256];
		HKEY connection_key;
		TCHAR name_data[256];
		DWORD name_type;
		const TCHAR name_string[] = _T("Name");

		len = sizeof(enum_name);
		status = RegEnumKeyEx(control_net_key, i, enum_name,
			&len, nullptr, nullptr, nullptr, nullptr);

		if (status != ERROR_SUCCESS)
			continue;

		_sntprintf(connection_string, sizeof(connection_string),
			_T("%s\\%s\\Connection"), NETWORK_CONNECTIONS_KEY, enum_name);

		status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, connection_string,
			0, KEY_READ, &connection_key);

		if (status == ERROR_SUCCESS)
		{
			len = sizeof(name_data);
			status = RegQueryValueEx(connection_key, name_string, nullptr,
				&name_type, (LPBYTE)name_data, &len);

			if (status != ERROR_SUCCESS || name_type != REG_SZ)
			{
				continue;
			}
			else
			{
				if (IsTAPDevice(enum_name))
				{
					guids.push_back(enum_name);
				}
			}

			RegCloseKey(connection_key);
		}
	}

	RegCloseKey(control_net_key);

	return !guids.empty();
}