Example #1
0
CStdString CSysInfo::GetKernelVersion()
{
#if defined (_LINUX)
  struct utsname un;
  if (uname(&un)==0)
  {
    CStdString strKernel;
    strKernel.Format("%s %s %s %s", un.sysname, un.release, un.version, un.machine);
    return strKernel;
  }

  return "";
#else
  OSVERSIONINFOEX osvi;
  SYSTEM_INFO si;

  ZeroMemory(&si, sizeof(SYSTEM_INFO));
  ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));

  GetSystemInfo(&si);

  osvi.dwOSVersionInfoSize = sizeof(osvi);
  CStdString strKernel = "Windows ";

  if (GetVersionEx((OSVERSIONINFO *)&osvi))
  {
    if ( osvi.dwMajorVersion == 6 )
    {
      if (osvi.dwMinorVersion == 0)
      {
        if( osvi.wProductType == VER_NT_WORKSTATION )
          strKernel.append("Vista");
        else
          strKernel.append("Server 2008");
      } else if (osvi.dwMinorVersion == 1)
      {
        if( osvi.wProductType == VER_NT_WORKSTATION )
          strKernel.append("7");
        else
          strKernel.append("Server 2008 R2");
      }

      if ( si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_AMD64 || si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_IA64)
        strKernel.append(", 64-bit Native");
      else if (si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_INTEL )
      {
        BOOL bIsWow = FALSE;;
        if(IsWow64Process(GetCurrentProcess(), &bIsWow))
        {
          if (bIsWow)
          {
            GetNativeSystemInfo(&si);
            if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64 || si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_IA64)
             strKernel.append(", 64-bit (WoW)");
          }
          else
          {
            strKernel.append(", 32-bit");
          }
        }
        else
          strKernel.append(", 32-bit");
      }
    }
    else if ( osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2 )
    {
      if( osvi.wProductType == VER_NT_WORKSTATION && si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_AMD64)
      {
        strKernel.append("XP Professional x64 Edition");
      }
    }
    else if ( osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1 )
    {
      strKernel.append("XP ");
      if( osvi.wSuiteMask & VER_SUITE_PERSONAL )
        strKernel.append("Home Edition" );
      else
        strKernel.append("Professional" );
    }
    else if ( osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0 )
    {
      strKernel.append("2000");
    }

    if( _tcslen(osvi.szCSDVersion) > 0 )
    {
      strKernel.append(" ");
      strKernel.append(osvi.szCSDVersion);
    }
    CStdString strBuild;
    strBuild.Format(" build %d",osvi.dwBuildNumber);
    strKernel += strBuild;
  }
  return strKernel;
#endif
}
Example #2
0
static bool
ScanDirectories(File::Visitor &visitor, bool recursive,
                const TCHAR* sPath, const TCHAR* filter = _T("*"))
{
#ifdef HAVE_POSIX
  DIR *dir = opendir(sPath);
  if (dir == NULL)
    return false;

  TCHAR FileName[MAX_PATH];
  _tcscpy(FileName, sPath);
  size_t FileNameLength = _tcslen(FileName);
  FileName[FileNameLength++] = '/';

  struct dirent *ent;
  while ((ent = readdir(dir)) != NULL) {
    // omit '.', '..' and any other files/directories starting with '.'
    if (*ent->d_name == _T('.'))
      continue;

    _tcscpy(FileName + FileNameLength, ent->d_name);

    struct stat st;
    if (stat(FileName, &st) < 0)
      continue;

    if (S_ISDIR(st.st_mode) && recursive)
      ScanDirectories(visitor, true, FileName, filter);
    else {
      int flags = 0;
#ifdef FNM_CASEFOLD
      flags = FNM_CASEFOLD;
#endif
      if (S_ISREG(st.st_mode) && fnmatch(filter, ent->d_name, flags) == 0)
        visitor.Visit(FileName, ent->d_name);
    }
  }

  closedir(dir);
#else /* !HAVE_POSIX */
  TCHAR DirPath[MAX_PATH];
  TCHAR FileName[MAX_PATH];

  if (sPath) {
    // e.g. "/test/data/something"
    _tcscpy(DirPath, sPath);
    _tcscpy(FileName, sPath);
  } else {
    DirPath[0] = 0;
    FileName[0] = 0;
  }

  // Scan for files in "/test/data/something"
  ScanFiles(visitor, FileName, filter);

  // If we are not scanning recursive we are done now
  if (!recursive)
    return true;

  // "test/data/something/"
  _tcscat(DirPath, _T(DIR_SEPARATOR_S));
  // "test/data/something/*"
  _tcscat(FileName, _T(DIR_SEPARATOR_S "*"));

  // Find the first file
  WIN32_FIND_DATA FindFileData;
  HANDLE hFind = FindFirstFile(FileName, &FindFileData);

  // If no file found -> return false
  if (hFind == INVALID_HANDLE_VALUE)
    return false;

  // Loop through remaining files
  while (true) {
    if (!IsDots(FindFileData.cFileName) &&
        (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
      // "test/data/something/"
      _tcscpy(FileName, DirPath);
      // "test/data/something/SUBFOLDER"
      _tcscat(FileName, FindFileData.cFileName);
      // Scan subfolder for matching files too
      ScanDirectories(visitor, true, FileName, filter);
    }

    // Look for next file/folder
    if (!FindNextFile(hFind, &FindFileData)) {
      if (GetLastError() == ERROR_NO_MORE_FILES)
        // No more files/folders
        // -> Jump out of the loop
        break;
      else {
        // Some error occured
        // -> Close the handle and return false
        FindClose(hFind);
        return false;
      }
    }
  }
  // Close the file handle
  FindClose(hFind);

#endif /* !HAVE_POSIX */

  return true;
}
Example #3
0
//// Эта функция пайп не закрывает!
//void CGuiServer::GuiServerThreadCommand(HANDLE hPipe)
BOOL CGuiServer::GuiServerCommand(LPVOID pInst, CESERVER_REQ* pIn, CESERVER_REQ* &ppReply, DWORD &pcbReplySize, DWORD &pcbMaxReplySize, LPARAM lParam)
{
	BOOL lbRc = FALSE;
	CGuiServer* pGSrv = (CGuiServer*)lParam;

	if (!pGSrv)
	{
		_ASSERTE(((CGuiServer*)lParam)!=NULL);
		pGSrv = &gpConEmu->m_GuiServer;
	}

	if (pIn->hdr.bAsync)
		pGSrv->mp_GuiServer->BreakConnection(pInst);

	gpSetCls->debugLogCommand(pIn, TRUE, timeGetTime(), 0, pGSrv ? pGSrv->ms_ServerPipe : NULL);

	#ifdef _DEBUG
	UINT nDataSize = pIn->hdr.cbSize - sizeof(CESERVER_REQ_HDR);
	#endif
	// Все данные из пайпа получены, обрабатываем команду и возвращаем (если нужно) результат

	#ifdef ALLOW_WINE_MSG
	if (gbIsWine)
	{
		wchar_t szMsg[128];
		msprintf(szMsg, countof(szMsg), L"CGuiServer::GuiServerCommand.\nGUI TID=%u\nSrcPID=%u, SrcTID=%u, Cmd=%u",
			GetCurrentThreadId(), pIn->hdr.nSrcPID, pIn->hdr.nSrcThreadId, pIn->hdr.nCmd);
		MessageBox(szMsg, MB_ICONINFORMATION);
	}
	#endif

	switch (pIn->hdr.nCmd)
	{
		case CECMD_NEWCMD:
		{
			// Приходит из другой копии ConEmu.exe, когда она запущена с ключом /single, /showhide, /showhideTSA
			DEBUGSTRCMD(L"GUI recieved CECMD_NEWCMD\n");

			if (pIn->NewCmd.isAdvLogging && !gpSetCls->isAdvLogging)
			{
				gpSetCls->isAdvLogging = pIn->NewCmd.isAdvLogging;
				gpConEmu->CreateLog();
			}

			if (gpSetCls->isAdvLogging && (pIn->NewCmd.isAdvLogging > gpSetCls->isAdvLogging))
			{
				wchar_t szLogLevel[80];
				_wsprintf(szLogLevel, SKIPLEN(countof(szLogLevel)) L"Changing log level! Old=%u, New=%u", (UINT)gpSetCls->isAdvLogging, (UINT)pIn->NewCmd.isAdvLogging);
				gpConEmu->LogString(szLogLevel);
				gpSetCls->isAdvLogging = pIn->NewCmd.isAdvLogging;
			}

			if (gpSetCls->isAdvLogging)
			{
				size_t cchAll = 120 + _tcslen(pIn->NewCmd.szConEmu) + _tcslen(pIn->NewCmd.szCurDir) + _tcslen(pIn->NewCmd.szCommand);
				wchar_t* pszInfo = (wchar_t*)malloc(cchAll*sizeof(*pszInfo));
				if (pszInfo)
				{
					_wsprintf(pszInfo, SKIPLEN(cchAll) L"CECMD_NEWCMD: Wnd=x%08X, Act=%u, ConEmu=%s, Dir=%s, Cmd=%s",
						(DWORD)(DWORD_PTR)pIn->NewCmd.hFromConWnd, pIn->NewCmd.ShowHide,
						pIn->NewCmd.szConEmu, pIn->NewCmd.szCurDir, pIn->NewCmd.szCommand);
					gpConEmu->LogString(pszInfo);
					free(pszInfo);
				}
			}

			BOOL bAccepted = FALSE;

			if (pIn->NewCmd.szConEmu[0])
			{
				bAccepted = (lstrcmpi(gpConEmu->ms_ConEmuExeDir, pIn->NewCmd.szConEmu) == 0);
			}
			else
			{
				bAccepted = TRUE;
			}

			if (bAccepted)
			{
				bool bCreateTab = (pIn->NewCmd.ShowHide == sih_None || pIn->NewCmd.ShowHide == sih_StartDetached)
					// Issue 1275: When minimized into TSA (on all VCon are closed) we need to restore and run new tab
					|| (pIn->NewCmd.szCommand[0] && !CVConGroup::isVConExists(0));
				gpConEmu->DoMinimizeRestore(bCreateTab ? sih_SetForeground : pIn->NewCmd.ShowHide);

				// Может быть пусто
				if (bCreateTab && pIn->NewCmd.szCommand[0])
				{
					RConStartArgs *pArgs = new RConStartArgs;
					pArgs->Detached = (pIn->NewCmd.ShowHide == sih_StartDetached) ? crb_On : crb_Off;
					pArgs->pszSpecialCmd = lstrdup(pIn->NewCmd.szCommand);
					if (pIn->NewCmd.szCurDir[0] == 0)
					{
						_ASSERTE(pIn->NewCmd.szCurDir[0] != 0);
					}
					else
					{
						pArgs->pszStartupDir = lstrdup(pIn->NewCmd.szCurDir);
					}

					if (gpSetCls->IsMulti() || CVConGroup::isDetached())
					{
						gpConEmu->PostCreateCon(pArgs);
					}
					else
					{
						// Если хотят в одном окне - только одну консоль
						gpConEmu->CreateWnd(pArgs);
						SafeDelete(pArgs);
					}
				}
				else
				{
					_ASSERTE(pIn->NewCmd.ShowHide==sih_ShowMinimize || pIn->NewCmd.ShowHide==sih_ShowHideTSA || pIn->NewCmd.ShowHide==sih_Show);
				}
			}

			pcbReplySize = sizeof(CESERVER_REQ_HDR)+sizeof(BYTE);
			lbRc = ExecuteNewCmd(ppReply, pcbMaxReplySize, pIn->hdr.nCmd, pcbReplySize);
			if (lbRc)
			{
				ppReply->Data[0] = bAccepted;
			}

			break;
		} //CECMD_NEWCMD

		case CECMD_TABSCMD:
		{
			// 0: спрятать/показать табы, 1: перейти на следующую, 2: перейти на предыдущую, 3: commit switch
			DEBUGSTRCMD(L"GUI recieved CECMD_TABSCMD\n");
			_ASSERTE(nDataSize>=1);
			DWORD nTabCmd = pIn->Data[0];
			gpConEmu->TabCommand((ConEmuTabCommand)nTabCmd);

			pcbReplySize = sizeof(CESERVER_REQ_HDR)+sizeof(BYTE);
			if (ExecuteNewCmd(ppReply, pcbMaxReplySize, pIn->hdr.nCmd, pcbReplySize))
			{
				lbRc = TRUE;
				ppReply->Data[0] = TRUE;
			}
			break;
		} // CECMD_TABSCMD

		#if 0
		case CECMD_GETALLTABS:
		{
			int nConCount = gpConEmu->GetConCount();
			int nActiveCon = gpConEmu->ActiveConNum();
			size_t cchMax = nConCount*16;
			size_t cchCount = 0;
			CVirtualConsole* pVCon;
			CESERVER_REQ_GETALLTABS::TabInfo* pTabs = (CESERVER_REQ_GETALLTABS::TabInfo*)calloc(cchMax, sizeof(*pTabs));
			for (int V = 0; (pVCon = gpConEmu->GetVCon(V)) != NULL; V++)
			{
				if (!pTabs)
				{
					_ASSERTE(pTabs!=NULL);
					break;
				}

				CRealConsole* pRCon = pVCon->RCon();
				if (!pRCon)
					continue;

				ConEmuTab tab;
				wchar_t szModified[4];
				for (int T = 0; pRCon->GetTab(T, &tab); T++)
				{
					if (cchCount >= cchMax)
					{
						pTabs = (CESERVER_REQ_GETALLTABS::TabInfo*)realloc(pTabs, (cchMax+32)*sizeof(*pTabs));
						if (!pTabs)
						{
							_ASSERTE(pTabs!=NULL);
							break;
						}
						cchMax += 32;
						_ASSERTE(cchCount<cchMax);
					}

					pTabs[cchCount].ActiveConsole == (V == nActiveCon);
					pTabs[cchCount].ActiveTab == (tab.Current != 0);
					pTabs[cchCount].Disabled = ((tab.Type & fwt_Disabled) == fwt_Disabled);
					pTabs[cchCount].ConsoleIdx = V;
					pTabs[cchCount].TabIdx = T;

					// Text
					wcscpy_c(szModified, tab.Modified ? L" * " : L"   ");
					if (V == nActiveCon)
					{
						if (T < 9)
							_wsprintf(pTabs[cchCount].Title, SKIPLEN(countof(pTabs[cchCount].Title)) L"[%i/&%i]%s", V+1, T+1, szModified);
						else if (T == 9)
							_wsprintf(pTabs[cchCount].Title, SKIPLEN(countof(pTabs[cchCount].Title)) L"[%i/1&0]%s", V+1, szModified);
						else
							_wsprintf(pTabs[cchCount].Title, SKIPLEN(countof(pTabs[cchCount].Title)) L"[%i/%i]%s", V+1, T+1, szModified);
					}
					else
					{
						_wsprintf(pTabs[cchCount].Title, SKIPLEN(countof(pTabs[cchCount].Title)) L"[%i/%i]%s", V+1, T+1, szModified);
					}

					cchCount++;
				}
			}
			if (cchCount && pTabs)
			{
				pcbReplySize = sizeof(CESERVER_REQ_HDR)+sizeof(CESERVER_REQ_GETALLTABS)+((cchCount-1)*sizeof(CESERVER_REQ_GETALLTABS::TabInfo));
				if (ExecuteNewCmd(ppReply, pcbMaxReplySize, pIn->hdr.nCmd, pcbReplySize))
				{
					lbRc = TRUE;
					ppReply->GetAllTabs.Count = cchCount;
					memmove(ppReply->GetAllTabs.Tabs, pTabs, cchCount*sizeof(*pTabs));
				}
			}
			SafeFree(pTabs);
			break;
		} // CECMD_GETALLTABS

		case CECMD_ACTIVATETAB:
		{
			BOOL lbTabOk = FALSE;
			CVirtualConsole *pVCon = gpConEmu->GetVCon(pIn->dwData[0]);
			if (pVCon && pVCon->RCon())
			{
				lbTabOk = pVCon->RCon()->ActivateFarWindow(pIn->dwData[1]);
			}

			pcbReplySize = sizeof(CESERVER_REQ_HDR)+sizeof(DWORD);
			if (ExecuteNewCmd(ppReply, pcbMaxReplySize, pIn->hdr.nCmd, pcbReplySize))
			{
				lbRc = TRUE;
				ppReply->dwData[0] = lbTabOk;
			}
			break;
		} // CECMD_ACTIVATETAB
		#endif

		case CECMD_ATTACH2GUI:
		{
			MCHKHEAP;

			// Получен запрос на Attach из сервера
			pcbReplySize = sizeof(CESERVER_REQ_HDR)+sizeof(CESERVER_REQ_SRVSTARTSTOPRET);
			if (!ExecuteNewCmd(ppReply, pcbMaxReplySize, pIn->hdr.nCmd, pcbReplySize))
				goto wrap;
			//CESERVER_REQ* pOut = ExecuteNewCmd(CECMD_ATTACH2GUI, sizeof(CESERVER_REQ_HDR)+sizeof(CESERVER_REQ_STARTSTOPRET));

			CVConGroup::AttachRequested(pIn->StartStop.hWnd, &(pIn->StartStop), &(ppReply->SrvStartStopRet));

			_ASSERTE((ppReply->StartStopRet.nBufferHeight == 0) || ((int)ppReply->StartStopRet.nBufferHeight > (pIn->StartStop.sbi.srWindow.Bottom-pIn->StartStop.sbi.srWindow.Top)));

			MCHKHEAP;

			lbRc = TRUE;
			//ExecuteFreeResult(pOut);
			break;
		} // CECMD_ATTACH2GUI

		case CECMD_SRVSTARTSTOP:
		{
			MCHKHEAP;

			// SRVSTART не приходит если запускается cmd под админом

			pcbReplySize = sizeof(CESERVER_REQ_HDR)+sizeof(CESERVER_REQ_SRVSTARTSTOPRET);
			if (!ExecuteNewCmd(ppReply, pcbMaxReplySize, pIn->hdr.nCmd, pcbReplySize))
				goto wrap;

			if (pIn->SrvStartStop.Started == srv_Started)
			{
				// Запущен процесс сервера
				HWND hConWnd = (HWND)pIn->dwData[1];
				_ASSERTE(hConWnd && IsWindow(hConWnd));

				DWORD nStartTick = timeGetTime();

				//LRESULT l = 0;
				//DWORD_PTR dwRc = 0;
				//2010-05-21 Поскольку это критично - лучше ждать до упора, хотя может быть DeadLock?
				//l = SendMessageTimeout(ghWnd, gpConEmu->mn_MsgSrvStarted, (WPARAM)hConWnd, pIn->hdr.nSrcPID,
				//	SMTO_BLOCK, 5000, &dwRc);

				//111002 - вернуть должен HWND окна отрисовки (дочернее окно ConEmu)
				MsgSrvStartedArg arg = {hConWnd, pIn->hdr.nSrcPID, pIn->SrvStartStop.dwKeybLayout, nStartTick};
				SendMessage(ghWnd, gpConEmu->mn_MsgSrvStarted, 0, (LPARAM)&arg);
				HWND hWndDC = arg.hWndDc;
				HWND hWndBack = arg.hWndBack;
				_ASSERTE(hWndDC!=NULL);

				#ifdef _DEBUG
				DWORD dwErr = GetLastError(), nEndTick = timeGetTime(), nDelta = nEndTick - nStartTick;
				if (hWndDC && nDelta >= EXECUTE_CMD_WARN_TIMEOUT)
				{
					if (!IsDebuggerPresent())
					{
						//_ASSERTE(nDelta <= EXECUTE_CMD_WARN_TIMEOUT || (pIn->hdr.nCmd == CECMD_CMDSTARTSTOP && nDelta <= EXECUTE_CMD_WARN_TIMEOUT2));
						_ASSERTEX(nDelta <= EXECUTE_CMD_WARN_TIMEOUT);
					}
				}
				#endif

				//pIn->dwData[0] = (DWORD)ghWnd; //-V205
				//pIn->dwData[1] = (DWORD)dwRc; //-V205
				//pIn->dwData[0] = (l == 0) ? 0 : 1;
				ppReply->SrvStartStopRet.Info.hWnd = ghWnd;
				ppReply->SrvStartStopRet.Info.hWndDc = hWndDC;
				ppReply->SrvStartStopRet.Info.hWndBack = hWndBack;
				ppReply->SrvStartStopRet.Info.dwPID = GetCurrentProcessId();
				// Limited logging of console contents (same output as processed by CECF_ProcessAnsi)
				gpConEmu->GetAnsiLogInfo(ppReply->SrvStartStopRet.AnsiLog);
				// Return GUI info, let it be in one place
				gpConEmu->GetGuiInfo(ppReply->SrvStartStopRet.GuiMapping);
			}
			else if (pIn->SrvStartStop.Started == srv_Stopped)
			{
				// Процесс сервера завершается
				CRealConsole* pRCon = NULL;
				CVConGuard VCon;

				for (size_t i = 0;; i++)
				{
					if (!CVConGroup::GetVCon(i, &VCon))
						break;

					pRCon = VCon->RCon();
					if (pRCon && (pRCon->GetServerPID(true) == pIn->hdr.nSrcPID || pRCon->GetServerPID(false) == pIn->hdr.nSrcPID))
					{
						break;
					}
					pRCon = NULL;
				}

				if (pRCon)
					pRCon->OnServerClosing(pIn->hdr.nSrcPID);

				//pIn->dwData[0] = 1;
			}
			else
			{
				_ASSERTE((pIn->dwData[0] == 1) || (pIn->dwData[0] == 101));
			}

			MCHKHEAP;

			lbRc = TRUE;
			//// Отправляем
			//fSuccess = WriteFile(
			//               hPipe,        // handle to pipe
			//               pOut,         // buffer to write from
			//               pOut->hdr.cbSize,  // number of bytes to write
			//               &cbWritten,   // number of bytes written
			//               NULL);        // not overlapped I/O

			//ExecuteFreeResult(pOut);
			break;
		} // CECMD_SRVSTARTSTOP

		case CECMD_ASSERT:
		{
			DWORD nBtn = MessageBox(NULL, pIn->AssertInfo.szDebugInfo, pIn->AssertInfo.szTitle, pIn->AssertInfo.nBtns);

			pcbReplySize = sizeof(CESERVER_REQ_HDR)+sizeof(DWORD);
			if (ExecuteNewCmd(ppReply, pcbMaxReplySize, pIn->hdr.nCmd, pcbReplySize))
			{
				lbRc = TRUE;
				ppReply->dwData[0] = nBtn;
			}

			//ExecutePrepareCmd(&pIn->hdr, CECMD_ASSERT, sizeof(CESERVER_REQ_HDR) + sizeof(DWORD));
			//pIn->dwData[0] = nBtn;
			//// Отправляем
			//fSuccess = WriteFile(
			//               hPipe,        // handle to pipe
			//               pIn,         // buffer to write from
			//               pIn->hdr.cbSize,  // number of bytes to write
			//               &cbWritten,   // number of bytes written
			//               NULL);        // not overlapped I/O
			break;
		} // CECMD_ASSERT

		case CECMD_ATTACHGUIAPP:
		{
			pcbReplySize = sizeof(CESERVER_REQ_HDR)+sizeof(CESERVER_REQ_ATTACHGUIAPP);
			if (!ExecuteNewCmd(ppReply, pcbMaxReplySize, pIn->hdr.nCmd, pcbReplySize))
				goto wrap;
			ppReply->AttachGuiApp = pIn->AttachGuiApp;

			//CESERVER_REQ Out;
			//ExecutePrepareCmd(&Out.hdr, CECMD_ATTACHGUIAPP, sizeof(CESERVER_REQ_HDR)+sizeof(Out.AttachGuiApp));
			//Out.AttachGuiApp = pIn->AttachGuiApp;

			#ifdef SHOW_GUIATTACH_START
			if (pIn->AttachGuiApp.hWindow == NULL)
			{
				wchar_t szDbg[1024];
				_wsprintf(szDbg, SKIPLEN(countof(szDbg)) L"AttachGuiApp requested from:\n%s\nPID=%u", pIn->AttachGuiApp.sAppFilePathName, pIn->AttachGuiApp.nPID);
				//MBoxA(szDbg);
				MessageBox(NULL, szDbg, L"ConEmu", MB_SYSTEMMODAL);
			}
			#endif

			// Уведомить ожидающую вкладку
			CRealConsole* pRCon = gpConEmu->AttachRequestedGui(pIn->AttachGuiApp.nServerPID, pIn->AttachGuiApp.sAppFilePathName, pIn->AttachGuiApp.nPID);
			if (pRCon)
			{
				CVConGuard VCon(pRCon->VCon());
				RECT rcPrev = ppReply->AttachGuiApp.rcWindow;
				HWND hBack = pRCon->VCon()->GetBack();

				//// Размер должен быть независим от возможности наличия прокрутки в VCon
				//GetWindowRect(hBack, &ppReply->AttachGuiApp.rcWindow);
				//ppReply->AttachGuiApp.rcWindow.right -= ppReply->AttachGuiApp.rcWindow.left;
				//ppReply->AttachGuiApp.rcWindow.bottom -= ppReply->AttachGuiApp.rcWindow.top;
				//ppReply->AttachGuiApp.rcWindow.left = ppReply->AttachGuiApp.rcWindow.top = 0;
				////MapWindowPoints(NULL, hBack, (LPPOINT)&ppReply->AttachGuiApp.rcWindow, 2);
				//pRCon->CorrectGuiChildRect(ppReply->AttachGuiApp.nStyle, ppReply->AttachGuiApp.nStyleEx, ppReply->AttachGuiApp.rcWindow);

				// Уведомить RCon и ConEmuC, что гуй подцепился
				// Вызывается два раза. Первый (при запуске exe) ahGuiWnd==NULL, второй - после фактического создания окна
				pRCon->SetGuiMode(pIn->AttachGuiApp.nFlags, pIn->AttachGuiApp.hAppWindow, pIn->AttachGuiApp.Styles.nStyle, pIn->AttachGuiApp.Styles.nStyleEx, pIn->AttachGuiApp.sAppFilePathName, pIn->AttachGuiApp.nPID, pIn->hdr.nBits, rcPrev);

				ppReply->AttachGuiApp.nFlags = agaf_Success | (pRCon->isActive(false) ? 0 : agaf_Inactive);
				ppReply->AttachGuiApp.nServerPID = pRCon->GetServerPID();
				ppReply->AttachGuiApp.nPID = ppReply->AttachGuiApp.nServerPID;
				ppReply->AttachGuiApp.hConEmuDc = pRCon->GetView();
				ppReply->AttachGuiApp.hConEmuBack = hBack;
				ppReply->AttachGuiApp.hConEmuWnd = ghWnd;
				ppReply->AttachGuiApp.hAppWindow = pIn->AttachGuiApp.hAppWindow;
				ppReply->AttachGuiApp.hSrvConWnd = pRCon->ConWnd();
				ppReply->AttachGuiApp.hkl = (DWORD)(LONG)(LONG_PTR)GetKeyboardLayout(gpConEmu->mn_MainThreadId);
				ZeroStruct(ppReply->AttachGuiApp.Styles.Shifts);
				CRealConsole::CorrectGuiChildRect(pIn->AttachGuiApp.Styles.nStyle, pIn->AttachGuiApp.Styles.nStyleEx, ppReply->AttachGuiApp.Styles.Shifts, pIn->AttachGuiApp.sAppFilePathName);
			}
			else
			{
				ppReply->AttachGuiApp.nFlags = agaf_Fail;
				_ASSERTE(FALSE && "No one tab is waiting for ChildGui process");
			}

			lbRc = TRUE;

			//// Отправляем
			//fSuccess = WriteFile(
			//               hPipe,        // handle to pipe
			//               &Out,         // buffer to write from
			//               Out.hdr.cbSize,  // number of bytes to write
			//               &cbWritten,   // number of bytes written
			//               NULL);        // not overlapped I/O
			break;
		} // CECMD_ATTACHGUIAPP

		case CECMD_GUICLIENTSHIFT:
		{
			pcbReplySize = sizeof(CESERVER_REQ_HDR)+sizeof(GuiStylesAndShifts);
			if (!ExecuteNewCmd(ppReply, pcbMaxReplySize, pIn->hdr.nCmd, pcbReplySize))
				goto wrap;
			ppReply->GuiAppShifts = pIn->GuiAppShifts;

			ZeroStruct(ppReply->GuiAppShifts.Shifts);
			CRealConsole::CorrectGuiChildRect(pIn->GuiAppShifts.nStyle, pIn->GuiAppShifts.nStyleEx, ppReply->GuiAppShifts.Shifts, pIn->GuiAppShifts.szExeName);

			lbRc = TRUE;
			break;
		} // CECMD_GUICLIENTSHIFT

		case CECMD_GUIMACRO:
		{
			// Допустимо, если GuiMacro пытаются выполнить извне
			CVConGuard VCon; CVConGroup::GetActiveVCon(&VCon);

			DWORD nFarPluginPID = VCon->RCon()->GetFarPID(true);
			LPWSTR pszResult = ConEmuMacro::ExecuteMacro(pIn->GuiMacro.sMacro, VCon->RCon(), (nFarPluginPID==pIn->hdr.nSrcPID));

			int nLen = pszResult ? _tcslen(pszResult) : 0;

			pcbReplySize = sizeof(CESERVER_REQ_HDR)+sizeof(CESERVER_REQ_GUIMACRO)+nLen*sizeof(wchar_t);
			if (!ExecuteNewCmd(ppReply, pcbMaxReplySize, pIn->hdr.nCmd, pcbReplySize))
				goto wrap;

			if (pszResult)
			{
				lstrcpy(ppReply->GuiMacro.sMacro, pszResult);
				ppReply->GuiMacro.nSucceeded = 1;
				free(pszResult);
			}
			else
			{
				ppReply->GuiMacro.sMacro[0] = 0;
				ppReply->GuiMacro.nSucceeded = 0;
			}

			lbRc = TRUE;
			break;
		} // CECMD_GUIMACRO

		case CECMD_CMDSTARTSTOP:
		{
			CRealServer* pRSrv = NULL;
			CVConGuard VCon;
			if (CVConGroup::GetVConBySrvPID(pIn->hdr.nSrcPID, &VCon))
				pRSrv = &VCon->RCon()->m_RConServer;
			if (pRSrv)
			{
				CESERVER_REQ* pOut = pRSrv->cmdStartStop(pInst, pIn, pIn->DataSize());
				if (pOut)
				{
					DWORD nDataSize = pOut->DataSize();
					pcbReplySize = pOut->hdr.cbSize;
					if (ExecuteNewCmd(ppReply, pcbMaxReplySize, pOut->hdr.nCmd, pcbReplySize))
					{
						if (nDataSize > 0)
						{
							memmove(ppReply->Data, pOut->Data, nDataSize);
						}
						lbRc = TRUE;
					}
					ExecuteFreeResult(pOut);
				}
			}
			break;
		} // CECMD_CMDSTARTSTOP

		//case CECMD_DEFTERMSTARTED:
		//{
		//	if (gpConEmu->mp_DefTrm)
		//		gpConEmu->mp_DefTrm->OnDefTermStarted(pIn);

		//	pcbReplySize = sizeof(CESERVER_REQ_HDR);
		//	if (!ExecuteNewCmd(ppReply, pcbMaxReplySize, pIn->hdr.nCmd, pcbReplySize))
		//		goto wrap;
		//	lbRc = TRUE;
		//	break;
		//} // CECMD_DEFTERMSTARTED

		default:
			_ASSERTE(FALSE && "Command was not handled in CGuiServer::GuiServerCommand");
	}

	//// Освободить память
	//if (pIn && (LPVOID)pIn != (LPVOID)&in)
	//{
	//	free(pIn); pIn = NULL;
	//}
wrap:
	return lbRc;
}
void CLanguageManager::LoadFromFile(ELanguageType language)
{
#ifdef EDITOR_MODE
    BEYONDENGINE_UNUSED_PARAM(language);
    m_languageMap.clear();
    TString filePath = CResourceManager::GetInstance()->GetResourcePath(eRT_Resource);
    filePath.append(_T("/LanguageConfig.xml"));
    if (CFilePathTool::GetInstance()->Exists(filePath.c_str()))
    {
        rapidxml::file<> fdoc(filePath.c_str());
        rapidxml::xml_document<> doc;
        try
        {
            doc.parse<rapidxml::parse_default>(fdoc.data());
            doc.m_pszFilePath = filePath.c_str();
        }
        catch (rapidxml::parse_error &e)
        {
            TCHAR info[MAX_PATH];
            _stprintf(info, _T("Load file :%s Failed! error :%s"), filePath.c_str(), e.what());
            MessageBox(BEYONDENGINE_HWND, info, _T("Load File Failed"), MB_OK | MB_ICONERROR);
        }
        uint32_t uCounter = 0;
        rapidxml::xml_node<>* pRootNode = doc.first_node("Language");
        rapidxml::xml_node<>* pLanguageNode = pRootNode->first_node("LanguageNode");
        while (pLanguageNode != nullptr)
        {
            uCounter++;
            TString strEnum = pLanguageNode->first_attribute("Enum")->value();
            BEATS_ASSERT(!strEnum.empty());
            if (pLanguageNode->first_attribute("Tag"))
            {
                TString strTag = pLanguageNode->first_attribute("Tag")->value();
                m_languageTagMap[strEnum] = strTag;
            }
            BEATS_ASSERT(m_languageMap.find(strEnum) == m_languageMap.end());
            std::map<ELanguageType, TString>& curMap = m_languageMap[strEnum];
            rapidxml::xml_node<>* pLanguageValueNode = pLanguageNode->first_node();
            while (pLanguageValueNode != nullptr)
            {
                TString languageTypeStr = pLanguageValueNode->name();
                ELanguageType languageType = eLT_Count;
                for (int j = 0; j < eLT_Count; ++j)
                {
                    if (pszLanguageTypeString[j] == languageTypeStr)
                    {
                        languageType = (ELanguageType)j;
                        break;
                    }
                }
                BEATS_ASSERT(curMap.find(languageType) == curMap.end());
                const TCHAR* pszValue = pLanguageValueNode->first_attribute("Value")->value();
                BEATS_ASSERT(_tcslen(pszValue) > 0);
                curMap[languageType] = pszValue;
                pLanguageValueNode = pLanguageValueNode->next_sibling();
            }
            pLanguageNode = pLanguageNode->next_sibling();
        }
        BEATS_ASSERT((uint32_t)_ttoi(pRootNode->first_attribute("Count")->value()) == uCounter);
    }
#else
    TString filePath = CResourceManager::GetInstance()->GetResourcePath(eRT_Language);
    filePath.append(_T("/")).append(pszLanguageTypeString[language]).append(_T(".bin"));
    bool bFindLanguageFile = CFilePathTool::GetInstance()->Exists(filePath.c_str());
    BEATS_ASSERT(bFindLanguageFile, "Can't Find language file %s", filePath.c_str());
    if (bFindLanguageFile)
    {
        int count = 0;
        CSerializer tmp(filePath.c_str());
        tmp >> count;
        m_texts.clear();
        for (int i = 0; i < count; ++i)
        {
            ELanguageTextType textId = (ELanguageTextType)i;
            std::string strValue;
            tmp >> strValue;
            m_texts.emplace(textId, strValue);
        }
        tmp >> count;
        for (int i = 0; i < count; ++i)
        {
            uint32_t key;
            tmp >> key;
            BEATS_ASSERT(m_texts.find((ELanguageTextType)key) == m_texts.end());
            tmp >> m_texts[(ELanguageTextType)key];
        }
    }
#endif
}
Example #5
0
// Split a string usinf a particular delimiter, split result are copied into lpBuffer
// in the "double null terminated string" format as the following figure shows:
// xxx\0xxxx\0xx\0xxx\0\0
//
// For example, if the delimiter is ",", then string "ab,cd,e" will be
// splitted into "ab\0cd\0e\0\0", this string format can be parsed into an array
// of sub strings easily using user defined functions or CIni::ParseStringArray.
DWORD CIni::__StringSplit(LPCTSTR lpString, LPTSTR lpBuffer, DWORD dwBufSize, LPCTSTR lpDelimiter, BOOL bTrimString)
{
	if (lpString == NULL || lpBuffer == NULL || dwBufSize == 0)
		return 0;	

	DWORD dwCopied = 0;
	*lpBuffer = _T('\0');
	if (*lpString == _T('\0'))
		return 0;

	// If lpDelimiter is NULL, use the default delimiter ",", if delimiter length
	// is 0, then return whole string
	if (lpDelimiter != NULL && *lpDelimiter == _T('\0'))
	{
		_tcsncpy(lpBuffer, lpString, dwBufSize - 1);
		return _tcslen(lpBuffer);
	}

	LPTSTR pszDel = (lpDelimiter == NULL) ? _tcsdup(DEF_PROFILE_DELIMITER) : _tcsdup(lpDelimiter);
	const DWORD DEL_LEN = _tcslen(pszDel);
	LPTSTR lpTarget = lpBuffer;

	// Search through lpString for delimiter matches, and extract sub strings out
	LPCTSTR lpPos = lpString;
	LPCTSTR lpEnd = _tcsstr(lpPos, pszDel);

	while (lpEnd != NULL)
	{
		LPTSTR pszSeg = __StrDupEx(lpPos, lpEnd);
		if (bTrimString)
			__TrimString(pszSeg);

		const DWORD SEG_LEN = _tcslen(pszSeg);
		const DWORD COPY_LEN = min(SEG_LEN, dwBufSize - dwCopied);

		// Need to avoid buffer overflow
		if (COPY_LEN > 0)
		{
			dwCopied += COPY_LEN + 1;
			_tcsncpy(lpTarget, pszSeg, COPY_LEN);
			lpTarget[COPY_LEN] = _T('\0');
			lpTarget = &lpTarget[SEG_LEN + 1];
		}
		delete [] pszSeg;
		lpPos = &lpEnd[DEL_LEN]; // Advance the pointer for next search		
		lpEnd = _tcsstr(lpPos, pszDel);
	}

	// The last part of string, there may not be the trailing delimiter, so we
	// need to take care of this part, too
	LPTSTR pszSeg = _tcsdup(lpPos);
	if (bTrimString)
		__TrimString(pszSeg);

	const DWORD SEG_LEN = _tcslen(pszSeg);
	const DWORD COPY_LEN = min(SEG_LEN, dwBufSize - dwCopied);

	if (COPY_LEN > 0)
	{
		dwCopied += COPY_LEN + 1;
		_tcsncpy(lpTarget, pszSeg, COPY_LEN);
		lpTarget[COPY_LEN] = _T('\0');
	}

	delete [] pszSeg;
	lpBuffer[dwCopied] = _T('\0');
	delete [] pszDel;
	return dwCopied;
}
Example #6
0
/*
---------------------------------------------------------
   TestHash2
---------------------------------------------------------
*/
PassFail TestHash2(TestInfo *pTestInfo)
{                  
	TEST_DECLARE;
	SQLRETURN		returncode;      
	SQLHENV			henv = 0;
	SQLHDBC			hdbc = 0;
	SQLHSTMT		hstmt= 0;
	SQLUSMALLINT	ParamStatusArray[ARRAY_SIZE];
	SQLUSMALLINT	expParamStatusArray[ARRAY_SIZE];
	SQLUSMALLINT	lastExpParamStatusArray[ARRAY_SIZE];
	SQLULEN			lastParamsProcessed=ARRAY_SIZE, ParamsProcessed = 0;
	SQLLEN			rowcount = 0, expRowcount = 0, lastExpRowcount = 0;
	int				i,j,k,counter = 1, loopcount = 0;
	TCHAR			buffer[256];

	typedef struct {
    		TCHAR	num[15];	SQLLEN numLenOrInd;
    		TCHAR	val[15];	SQLLEN valLenOrInd;
	}nameStruct;
	nameStruct  nameArray1[ARRAY_SIZE];

	SQLUINTEGER mode = 1; 
	SQLUINTEGER startnode = 2;
	SQLUINTEGER streams_per_node = 4;
	SQLUINTEGER delay_error = 1;
	SQLUINTEGER suggested_rowset_size=0;

	SQLTCHAR *sqlDrvInsert = (SQLTCHAR*)_T("PLANLOADTABLE HASH2_TABLE");
	SQLTCHAR *dropTbl = (SQLTCHAR *)_T("DROP TABLE HASH2_TABLE cascade");
	SQLTCHAR *crtTbl = (SQLTCHAR *)_T("CREATE TABLE HASH2_TABLE (A int NOT NULL NOT DROPPABLE, B varchar(10), PRIMARY KEY (A))");
	SQLTCHAR *insTbl = (SQLTCHAR *)_T("INSERT INTO HASH2_TABLE values (?,?)");
//	SQLTCHAR *selTbl = (SQLTCHAR *)_T("SELECT * HASH2_TABLE");

	//==================================================================================================
	LogMsg(LINEBEFORE+SHORTTIMESTAMP,_T("Begin testing feature => Hash2.\n"));
	TEST_INIT;

	returncode = SQLAllocEnv(&henv);
	if(!CHECKRC(SQL_SUCCESS,returncode,"SQLAllocEnv"))
	{
		LogAllErrors(henv,hdbc,hstmt);
		TEST_FAILED;
		TEST_RETURN;
	}

	returncode = SQLAllocConnect( henv, &hdbc);
	if(!CHECKRC(SQL_SUCCESS,returncode,"SQLAllocConnect"))
	{
		LogAllErrors(henv,hdbc,hstmt);
		TEST_FAILED;
		TEST_RETURN;
	}

	returncode = SQLSetConnectAttr(hdbc, SQL_ATTR_AUTOCOMMIT, (SQLPOINTER)SQL_AUTOCOMMIT_ON,0);
	if(!CHECKRC(SQL_SUCCESS,returncode,"SQLSetConnectAttr"))
	{
		LogAllErrors(henv,hdbc,hstmt);
		TEST_FAILED;
		TEST_RETURN;
	}

	//==================================================================================================
	// Set Mode to Loader
	returncode = SQLSetConnectAttr(hdbc, SQL_MODE_LOADER, (void *) mode, 0);
	if(!CHECKRC(SQL_SUCCESS,returncode,"SQL_MODE_LOADER"))
	{
		LogAllErrors(henv,hdbc,hstmt);
		TEST_FAILED;
		TEST_RETURN;
	}

	// Set Start mode
	returncode = SQLSetConnectAttr(hdbc,  SQL_START_NODE,  (void *) startnode,  0);
	if(!CHECKRC(SQL_SUCCESS,returncode,"SQL_START_NODE"))
	{
		LogAllErrors(henv,hdbc,hstmt);
		TEST_FAILED;
		TEST_RETURN;
	}

	// Set Desired Streams Per Node
	returncode = SQLSetConnectAttr(hdbc,  SQL_STREAMS_PER_SEG,  (void *) streams_per_node,  0);
	if(!CHECKRC(SQL_SUCCESS,returncode,"SQL_STREAMS_PER_SEG"))
	{
		LogAllErrors(henv,hdbc,hstmt);
		TEST_FAILED;
		TEST_RETURN;
	}

	// Set delay_error mode
	returncode = SQLSetConnectAttr(hdbc,  SQL_LOADER_DELAYERROR, (void *) delay_error, 0);
	if(!CHECKRC(SQL_SUCCESS,returncode,"SQL_LOADER_DELAYERROR"))
	{
		LogAllErrors(henv,hdbc,hstmt);
		TEST_FAILED;
		TEST_RETURN;
	}
	//==================================================================================================

	returncode = SQLConnect(hdbc,
					   (SQLTCHAR*)pTestInfo->DataSource,(SWORD)_tcslen(pTestInfo->DataSource),
					   (SQLTCHAR*)pTestInfo->UserID,(SWORD)_tcslen(pTestInfo->UserID),
					   (SQLTCHAR*)pTestInfo->Password,(SWORD)_tcslen(pTestInfo->Password)
					   );
	if(!CHECKRC(SQL_SUCCESS,returncode,"SQLConnect"))
	{
		LogAllErrors(henv,hdbc,hstmt);
		TEST_FAILED;
		TEST_RETURN;
	}

	returncode = SQLAllocStmt(hdbc, &hstmt);
	if(!CHECKRC(SQL_SUCCESS,returncode,"SQLConnect"))
	{
		LogAllErrors(henv,hdbc,hstmt);
		TEST_FAILED;
		TEST_RETURN;
	}

	returncode = SQLExecDirect(hstmt, dropTbl, SQL_NTS);
	returncode = SQLExecDirect(hstmt, crtTbl, SQL_NTS);
	if(!CHECKRC(SQL_SUCCESS,returncode,"SQLExecDirect"))
	{
		LogAllErrors(henv,hdbc,hstmt);
		TEST_FAILED;
		TEST_RETURN;
	}

	returncode = SQLPrepare(hstmt, (SQLTCHAR *) sqlDrvInsert, SQL_NTS);
	if (returncode != SQL_SUCCESS) {
		LogMsg(ERRMSG,_T("PLANLOADTABLE is expected to return SQL_SUCCESS, actual is %d\n"), returncode);
		LogAllErrors(henv,hdbc,hstmt);
		TEST_FAILED;
		TEST_RETURN;
	}

	returncode = SQLGetConnectAttr(hdbc, SQL_ATTR_SUG_ROWSET_SIZE, &suggested_rowset_size, 0, NULL);
	if(!CHECKRC(SQL_SUCCESS,returncode,"SQL_ATTR_SUG_ROWSET_SIZE"))
	{
		LogAllErrors(henv,hdbc,hstmt);
		TEST_FAILED;
		TEST_RETURN;
	}
	LogMsg(LINEAFTER,_T("suggested_rowset_size=%d\n"), suggested_rowset_size);

	//==================================================================================================
	// Set the SQL_ATTR_PARAM_BIND_TYPE statement attribute to use row-wise binding.
	returncode = SQLSetStmtAttr(hstmt, SQL_ATTR_PARAM_BIND_TYPE, (void *)sizeof(nameStruct), 0);
	if(!CHECKRC(SQL_SUCCESS,returncode,"SQL_ATTR_PARAM_BIND_TYPE"))
	{
		LogAllErrors(henv,hdbc,hstmt);
		TEST_FAILED;
		TEST_RETURN;
	}
	// Specify the number of elements in each parameter array.
	returncode = SQLSetStmtAttr(hstmt, SQL_ATTR_PARAMSET_SIZE, (void *)ARRAY_SIZE, 0);
	if(!CHECKRC(SQL_SUCCESS,returncode,"SQL_ATTR_PARAMSET_SIZE"))
	{
		LogAllErrors(henv,hdbc,hstmt);
		TEST_FAILED;
		TEST_RETURN;
	}
	// Specify an array in which to return the status of each set of parameters.
	returncode = SQLSetStmtAttr(hstmt, SQL_ATTR_PARAM_STATUS_PTR, ParamStatusArray, 0);
	if(!CHECKRC(SQL_SUCCESS,returncode,"SQL_ATTR_PARAM_STATUS_PTR"))
	{
		LogAllErrors(henv,hdbc,hstmt);
		TEST_FAILED;
		TEST_RETURN;
	}
	// Specify an SQLUINTEGER value in which to return the number of sets of parameters processed.
	returncode = SQLSetStmtAttr(hstmt, SQL_ATTR_PARAMS_PROCESSED_PTR, &ParamsProcessed, 0);
	if(!CHECKRC(SQL_SUCCESS,returncode,"SQL_ATTR_PARAMS_PROCESSED_PTR"))
	{
		LogAllErrors(henv,hdbc,hstmt);
		TEST_FAILED;
		TEST_RETURN;
	}

	returncode = SQLPrepare(hstmt, insTbl, SQL_NTS);
	if(!CHECKRC(SQL_SUCCESS,returncode,"SQLPrepare"))
	{
		LogAllErrors(henv,hdbc,hstmt);
		TEST_FAILED;
		TEST_RETURN;
	}

	returncode = SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_TCHAR, SQL_INTEGER, 10, 0,
                 &nameArray1[0].num, 300, &nameArray1[0].numLenOrInd);
	if(!CHECKRC(SQL_SUCCESS,returncode,"SQLBindParameter"))
	{
		LogAllErrors(henv,hdbc,hstmt);
		TEST_FAILED;
		TEST_RETURN;
	}
	returncode = SQLBindParameter(hstmt, 2, SQL_PARAM_INPUT, SQL_C_TCHAR, SQL_WCHAR, 10, 0,
                 &nameArray1[0].val, 300, &nameArray1[0].valLenOrInd);
	if(!CHECKRC(SQL_SUCCESS,returncode,"SQLBindParameter"))
	{
		LogAllErrors(henv,hdbc,hstmt);
		TEST_FAILED;
		TEST_RETURN;
	}

	for (j=0; j<ARRAY_SIZE; j++) {
		lastExpParamStatusArray[j] = SQL_PARAM_SUCCESS;
		expParamStatusArray[j] = SQL_PARAM_SUCCESS;
	}

	//==================================================================================================
	TESTCASE_BEGIN("Test the positive functionality of Hash2, with delay_error mode ON.\n");
	loopcount = 4;
	k = 0;
	while ( k < (loopcount+1)) {
		expRowcount = 0;

		if (k==loopcount) { //Send a dummy rowsets to get the status array of the previous rowsets in delay-mode
			LogMsg(LINEAFTER,_T("Insert dummy rowsets with size=0\n"));
			returncode = SQLSetStmtAttr(hstmt, SQL_ATTR_PARAMSET_SIZE, (void *)0, 0);
			if(!CHECKRC(SQL_SUCCESS,returncode,"SQL_ATTR_PARAMSET_SIZE"))
			{
				LogAllErrors(henv,hdbc,hstmt);
				TEST_FAILED;
				TEST_RETURN;
			}
		}
		else {
			_stprintf(buffer, _T("Data inserted: "));
			for (j=0; j<ARRAY_SIZE; j++) {
				if ((j+1)%(3+2*k) == 0) {
					counter--;
					expParamStatusArray[j] = SQL_PARAM_ERROR;
				}
				else {
					expParamStatusArray[j] = SQL_PARAM_SUCCESS;
					expRowcount++;
				}
				_stprintf(nameArray1[j].num,_T("%d"),counter++);
				nameArray1[j].numLenOrInd = SQL_NTS;
				_stprintf(nameArray1[j].val,_T("%s"),_T("chochet"));
				nameArray1[j].valLenOrInd = SQL_NTS;
				_tcscat(buffer,nameArray1[j].num);
				_tcscat(buffer,_T(" "));
			}
			_tcscat(buffer,_T("\n"));
		}
		LogMsg(NONE,_T("%s\n"), buffer);

		returncode = SQLExecute(hstmt);
		if (delay_error == 1 && k != 0) {
			if(returncode != SQL_SUCCESS_WITH_INFO)
			{
				LogMsg(ERRMSG,_T("SQLExecute: returncode expected: SQL_SUCCESS_WITH_INFO, actual: %d at line=%d\n"), returncode, __LINE__);
				LogAllErrors(henv,hdbc,hstmt);
				TEST_FAILED;
				TEST_RETURN;
			}
		}
		else {
			if(returncode != SQL_SUCCESS)
			{
				LogMsg(ERRMSG,_T("SQLExecute: returncode expected: SQL_SUCCESS, actual: %d at line=%d\n"), returncode, __LINE__);
				LogAllErrors(henv,hdbc,hstmt);
				TEST_FAILED;
				TEST_RETURN;
			}
		}

		if ((k == loopcount && ParamsProcessed != 0) || (k != loopcount && ParamsProcessed != ARRAY_SIZE)) {
			LogMsg(ERRMSG,_T("ParamsProcessed is not the same as rowset size from client, at line=%d\n"), __LINE__);
			TEST_FAILED;
		}

		returncode = SQLRowCount(hstmt, &rowcount);
		if(!CHECKRC(SQL_SUCCESS,returncode,"SQLRowCount"))
		{
			LogAllErrors(henv,hdbc,hstmt);
			TEST_FAILED;
		}

		if (delay_error == 1) {
			if (lastExpRowcount != rowcount) {
				TEST_FAILED;
				LogMsg(ERRMSG,_T("Expected Rowcount=%d, Actual Rowcount=%d\n"), expRowcount, rowcount);
			}
			lastExpRowcount = expRowcount;

			LogMsg(NONE,_T("\n%d last rows processed, %d current rows processed, rowcount=%d\n"), lastParamsProcessed, ParamsProcessed, rowcount);
			for (i = 0; i < (int)lastParamsProcessed; i++) {
   				LogMsg(NONE,_T("Parameter Set  Status\n"));
				LogMsg(NONE,_T("-------------  -------------\n"));
				if (ParamStatusArray[i] != lastExpParamStatusArray[i]) {
					TEST_FAILED;
					LogMsg(ERRMSG,_T("Param status array at row #%d is expected: %d, actual %d\n"), i, lastExpParamStatusArray[i], ParamStatusArray[i]);
					continue;
				}
				switch (ParamStatusArray[i]) {
					case SQL_PARAM_SUCCESS:
					case SQL_PARAM_SUCCESS_WITH_INFO:
         					LogMsg(NONE,_T("%13d  Success\n"), i);
         					break;

      					case SQL_PARAM_ERROR:
         					LogMsg(NONE,_T("%13d  Error  <-------\n"), i);
         					break;

      					case SQL_PARAM_UNUSED:
        					LogMsg(NONE,_T("%13d  Not processed\n"), i);
        					break;

     					case SQL_PARAM_DIAG_UNAVAILABLE:
         					LogMsg(NONE,_T("%13d  Unknown\n"), i);
         					break;
   				}
			}
			LogMsg(NONE,_T("\n============================================================\n"));
			lastParamsProcessed = ParamsProcessed;
			for (j=0; j<ARRAY_SIZE; j++) {
				lastExpParamStatusArray[j] = expParamStatusArray[j];
			}
		}
		else {
			if (expRowcount != rowcount) {
				TEST_FAILED;
				LogMsg(ERRMSG,_T("Expected Rowcount=%d, Actual Rowcount=%d\n"), expRowcount, rowcount);
			}

			LogMsg(NONE,_T("\n%d current rows processed, rowcount=%d\n"), ParamsProcessed, rowcount);
			for (i = 0; i < (int)ParamsProcessed; i++) {
   				LogMsg(NONE,_T("Parameter Set  Status\n"));
				LogMsg(NONE,_T("-------------  -------------\n"));
				if (ParamStatusArray[i] != expParamStatusArray[i]) {
					TEST_FAILED;
					LogMsg(ERRMSG,_T("Param status array at row #%d is expected: %d, actual %d\n"), i, expParamStatusArray[i], ParamStatusArray[i]);
					continue;
				}
				switch (ParamStatusArray[i]) {
					case SQL_PARAM_SUCCESS:
					case SQL_PARAM_SUCCESS_WITH_INFO:
         					LogMsg(NONE,_T("%13d  Success\n"), i);
         					break;

      					case SQL_PARAM_ERROR:
         					LogMsg(NONE,_T("%13d  Error  <-------\n"), i);
         					break;

      					case SQL_PARAM_UNUSED:
        					LogMsg(NONE,_T("%13d  Not processed\n"), i);
        					break;

     					case SQL_PARAM_DIAG_UNAVAILABLE:
         					LogMsg(NONE,_T("%13d  Unknown\n"), i);
         					break;
   				}
			}
			LogMsg(NONE,_T("\n============================================================\n"));
		}
		k++;
	}
	TESTCASE_END;

	SQLFreeStmt( hstmt, SQL_CLOSE );
	SQLFreeStmt( hstmt, SQL_UNBIND );
	SQLDisconnect( hdbc );
	SQLFreeConnect( hdbc );
	SQLFreeEnv( henv );

	//==================================================================================================
	LogMsg(SHORTTIMESTAMP+LINEAFTER,_T("End testing feature => Hash2.\n"));
	TEST_RETURN;
}
Example #7
0
static int
ParseKeyFilenameLine(connection_t *c, TCHAR *keyfilename, size_t keyfilenamesize, char *line)
{
  const int STATE_INITIAL = 0;
  const int STATE_READING_QUOTED_PARM = 1;
  const int STATE_READING_UNQUOTED_PARM = 2;
  int i=0;
  unsigned int j=0;
  int state = STATE_INITIAL;
  int backslash=0;
  TCHAR temp_filename[MAX_PATH];

  while(line[i] != '\0')
    {
      if (state == STATE_INITIAL)
        {
          if (line[i] == '\"')
            {
              state=STATE_READING_QUOTED_PARM;
            }
          else if ((line[i] == 0x0A) || (line[i] == 0x0D))
            break;
          else if ((line[i] == ';') || (line[i] == '#'))
            break;
          else if ((line[i] != ' ') && (line[i] != '\t'))
            {
              if (line[i] == '\\')
                {
                  if(!backslash)
                    {
                      keyfilename[j++]=line[i];
                      state=STATE_READING_UNQUOTED_PARM;
                      backslash=1;
                    }
                  else
                    {
                      backslash=0;
                    }
                }
              else
                {
                  if (backslash) backslash=0;
                  keyfilename[j++]=line[i];
                  state=STATE_READING_UNQUOTED_PARM;
                }
            }
        }

      else if (state == STATE_READING_QUOTED_PARM)
        {
          if (line[i] == '\"')
            break;
          if ((line[i] == 0x0A) || (line[i] == 0x0D))
            break;
          if (line[i] == '\\')
            {
              if (!backslash)
                {
                  keyfilename[j++]=line[i];
                  backslash=1;
                }
              else
                {
                  backslash=0;
                }
            }
          else
            {
              if (backslash) backslash=0;
              keyfilename[j++]=line[i];
            }
        }

      else if (state == STATE_READING_UNQUOTED_PARM)
        {
          if (line[i] == '\"')
            break;
          if ((line[i] == 0x0A) || (line[i] == 0x0D))
            break;
          if ((line[i] == ';') || (line[i] == '#'))
            break;
          if (line[i] == ' ')
            break;
          if (line[i] == '\t')
            break;
          if (line[i] == '\\')
            {
              if (!backslash)
                {
                  keyfilename[j++]=line[i];
                  backslash=1;
                }
              else
                {
                  backslash=0;
                }
            }
          else
            {
              if (backslash) backslash=0;
              keyfilename[j++]=line[i];
            }
        }

      if (j >= (keyfilenamesize - 1))
        {
          /* key filename to long */
          ShowLocalizedMsg(IDS_ERR_KEY_FILENAME_TO_LONG);
          return(0);
        }
      i++;
    }
  keyfilename[j]='\0';

  /* Prepend filename with configdir path if needed */
  if ((keyfilename[0] != '\\') && (keyfilename[0] != '/') && (keyfilename[1] != ':'))
    {
      _tcsncpy(temp_filename, c->config_dir, _countof(temp_filename));
      if (temp_filename[_tcslen(temp_filename) - 1] != '\\')
        _tcscat(temp_filename, _T("\\"));
      _tcsncat(temp_filename, keyfilename,
              _countof(temp_filename) - _tcslen(temp_filename) - 1);
      _tcsncpy(keyfilename, temp_filename, keyfilenamesize - 1);
    }

  return(1);
}
Example #8
0
/* gets the list of mechanisms */
int _sasl_load_plugins(const add_plugin_list_t *entrypoints,
		       const sasl_callback_t *getpath_cb,
		       const sasl_callback_t *verifyfile_cb)
{
    int result;
    TCHAR cur_dir[PATH_MAX], full_name[PATH_MAX+2], prefix[PATH_MAX+2];
				/* 1 for '\\' 1 for trailing '\0' */
    TCHAR * pattern;
    TCHAR c;
    int pos;
    int retCode = SASL_OK;
    char *utf8path = NULL;
    TCHAR *path=NULL;
    int position;
    const add_plugin_list_t *cur_ep;
    struct _stat statbuf;		/* filesystem entry information */
    intptr_t fhandle;			/* file handle for _findnext function */
    struct _tfinddata_t finddata;	/* data returned by _findnext() */
    size_t prefix_len;
    
    /* for static plugins */
    add_plugin_t *add_plugin;
    _sasl_plug_type type;
    _sasl_plug_rec *p;

    if (! entrypoints
	|| ! getpath_cb
	|| getpath_cb->id != SASL_CB_GETPATH
	|| ! getpath_cb->proc
	|| ! verifyfile_cb
	|| verifyfile_cb->id != SASL_CB_VERIFYFILE
	|| ! verifyfile_cb->proc)
	return SASL_BADPARAM;

    /* do all the static plugins first */

    for (cur_ep = entrypoints; cur_ep->entryname; cur_ep++) {

        /* What type of plugin are we looking for? */
        if (!strcmp(cur_ep->entryname, "sasl_server_plug_init")) {
            type = SERVER;
            add_plugin = (add_plugin_t *)sasl_server_add_plugin;
        }
        else if (!strcmp(cur_ep->entryname, "sasl_client_plug_init")) {
            type = CLIENT;
            add_plugin = (add_plugin_t *)sasl_client_add_plugin;
        }
        else if (!strcmp(cur_ep->entryname, "sasl_auxprop_plug_init")) {
            type = AUXPROP;
            add_plugin = (add_plugin_t *)sasl_auxprop_add_plugin;
        }
        else if (!strcmp(cur_ep->entryname, "sasl_canonuser_init")) {
            type = CANONUSER;
            add_plugin = (add_plugin_t *)sasl_canonuser_add_plugin;
        }
        else {
            /* What are we looking for then? */
            return SASL_FAIL;
        }
        for (p = _sasl_static_plugins; p->type; p++) {
            if (type == p->type)
                result = add_plugin(p->name, p->plug);
        }
    }

    /* get the path to the plugins */
    result = ((sasl_getpath_t *)(getpath_cb->proc))(getpath_cb->context,
						    &utf8path);
    if (result != SASL_OK) return result;
    if (!utf8path) return SASL_FAIL;

    if (sizeof(TCHAR) == sizeof(char)) {
        path = (TCHAR*)utf8path;
    }
    else {
        path = _sasl_utf8_to_wchar(utf8path);
        if (!path) return SASL_FAIL;
    }

    if (_tcslen(path) >= PATH_MAX) { /* no you can't buffer overrun */
	    retCode = SASL_FAIL;
        goto cleanup;
    }

    position=0;
    do {
	pos=0;
	do {
	    c=path[position];
	    position++;
	    cur_dir[pos]=c;
	    pos++;
	} while ((c!=PATHS_DELIMITER) && (c!=0));
	cur_dir[pos-1]='\0';


/* : check to make sure that a valid directory name was passed in */
	if (_tstat (cur_dir, &statbuf) < 0) {
	    continue;
	}
	if ((statbuf.st_mode & S_IFDIR) == 0) {
	    continue;
	}

    _tcscpy(prefix, cur_dir);
	prefix_len = _tcslen (prefix);

/* : Don't append trailing \ unless required */
	if (prefix[prefix_len-1] != '\\') {
        _tcscat(prefix,_T("\\"));
	    prefix_len++;
	}

	pattern = prefix;

/* : Check that we have enough space for "*.dll" */
	if ((prefix_len + DLL_MASK_LEN) > (sizeof(prefix) / sizeof(TCHAR) - 1)) {
	    _sasl_log(NULL, SASL_LOG_WARN, "plugin search mask is too big");
            continue;
	}

	_tcscat (prefix + prefix_len, _T("*") DLL_SUFFIX);

        fhandle = _tfindfirst (pattern, &finddata);
        if (fhandle == -1) {	/* no matching files */
            continue;
        }

/* : Truncate "*.dll" */
	prefix[prefix_len] = '\0';

	do {
	    size_t length;
	    void *library;
	    char *c;
	    char plugname[PATH_MAX];
	    int entries;

	    length = _tcslen(finddata.name);
	    if (length < 5) { /* At least <Ch>.dll */
		continue; /* can not possibly be what we're looking for */
	    }

/* : Check for overflow */
	    if (length + prefix_len >= PATH_MAX) continue; /* too big */

	    if (_tcscmp(finddata.name + (length - _tcslen(DLL_SUFFIX)), DLL_SUFFIX) != 0) {
		continue;
	    }

/* : Check that it is not a directory */
	    if ((finddata.attrib & _A_SUBDIR) == _A_SUBDIR) {
		continue;
	    }

/* : Construct full name from prefix and name */

        _tcscpy (full_name, prefix);
        _tcscat (full_name, finddata.name);
		
/* cut off .dll suffix -- this only need be approximate */
        if (sizeof(TCHAR) != sizeof(char)) {
            if (WideCharToMultiByte(CP_UTF8, 0, finddata.name, -1, plugname, sizeof(plugname), NULL, NULL) == 0) { // in case of unicode use utf8
                continue;
            }
        }
        else {
            _tcscpy((TCHAR*)plugname, finddata.name); // w/o unicode local enconding is fine
        }
	    c = strchr(plugname, '.');
	    if (c != NULL) *c = '\0';

	    result = _tsasl_get_plugin (full_name, verifyfile_cb, &library);

	    if (result != SASL_OK) {
		continue;
	    }

	    entries = 0;
	    for (cur_ep = entrypoints; cur_ep->entryname; cur_ep++) {
		result = _sasl_plugin_load(plugname,
					   library,
					   cur_ep->entryname,
					   cur_ep->add_plugin);
		if (result == SASL_OK) {
		    ++entries;
		}
		/* If this fails, it's not the end of the world */
	    }
	    if (entries == 0) {
		_sasl_remove_last_plugin();
	    }

	} while (_tfindnext (fhandle, &finddata) == 0);
	
	_findclose (fhandle);

    } while ((c!='=') && (c!=0));

cleanup:
    if (sizeof(TCHAR) != sizeof(char)) {
        sasl_FREE(path); /* It's always allocated in coversion to wchar */
    }
    return retCode;
}
Example #9
0
bool CArchiverJACK::Compress(LPCTSTR ArcFileName,std::list<CString> &ParamList,CConfigManager &ConfMan,const PARAMETER_TYPE Type,int Options,LPCTSTR,LPCTSTR,LPCTSTR,CString &strLog)
{
	if(!IsOK()){
		return false;
	}

	//ArcFileNameは出力先フォルダ名
	ASSERT(0!=_tcslen(ArcFileName));
	TRACE(_T("ArcFileName=%s\n"),ArcFileName);

	//===========================
	// DLLに渡すオプションの設定
	//===========================
	TRACE(_T("DLLに渡すオプションの設定\n"));

	CString Param;//コマンドライン パラメータ バッファ

	CConfigJACK Config;
	Config.load(ConfMan);
	Param+=_T("-r ");	//分割
	if(Options&COMPRESS_SFX){
		Param+=_T("-m1 ");	//SFX
	}
	else{
		Param+=_T("-m0 ");	//通常
	}
	if(Config.SpecifyVolumeSizeAtCompress){
		CJackVolumeSizeDialog vsd;
		if(IDOK!=vsd.DoModal()){
			return false;
		}
		CString Buf;
		Buf.Format(_T("-v:%d "),vsd.VolumeSize);
		Param+=Buf;//分割サイズ指定
	}else{
		CString Buf;
		Buf.Format(_T("-v:%d "),Config.VolumeSize);
		Param+=Buf;//分割サイズ指定
	}

	//分割対象ファイル名指定
	Param+=_T("\"");
	Param+=*ParamList.begin();
	Param+=_T("\" ");

	//出力フォルダ指定
	Param+=_T("\"");
	Param+=ArcFileName;
	Param+=_T("\"");

	ASSERT(!Param.IsEmpty());
	TRACE(_T("ArchiveHandler Commandline Parameter:%s\n"),Param);

	TRACE(_T("ArchiveHandler呼び出し\n"));
	//char szLog[LOG_BUFFER_SIZE]={0};
	std::vector<char> szLog(LOG_BUFFER_SIZE);
	szLog[0]='\0';
	int Ret=ArchiveHandler(NULL,CT2A(Param),&szLog[0],LOG_BUFFER_SIZE-1);
	strLog=&szLog[0];

	return 0==Ret;
}
Example #10
0
/*
// fill in a char* list[] and its count with arguments up to
// next argument (-<arg>) or end of stack.
// returns 0 on success, nonzero on error
 */
int getArgList(int *argCnt, char **argList[], TCHAR *cmdline)
{
  int cnt;
  char **list;
  TCHAR buf[1024];

  register int i;

  stack_t * stkptr = *g_stacktop;


  /* some sanity checking */
  if (argList == NULL) 
  {
    PrintMessage(_T(__FILE__) _T("::getArgList() called with argList == NULL"));
    return -1;
  }
  if (argCnt == NULL) 
  {
    PrintMessage(_T(__FILE__) _T("::getArgList() called with argCnt == NULL"));
    return -2;
  }


  cnt = *argCnt = 0;
  list = NULL;
  *argList = NULL;

  *buf = (TCHAR)'\0';
  // loop through until end of stack or next option found
  while ( stkptr && (*buf != (TCHAR)'-') )
  {
    stkptr = peekstring(buf, stkptr);
    cnt++;
  }
  if (*buf == (TCHAR)'-') cnt--;

  if (cnt > 0)
  {
    if ((list = (char **)malloc(cnt * sizeof(char *))) == NULL) 
	{
		PrintMessage(_T("WARNING: ") _T(__FILE__) _T("::getArgList() Unable to allocate memory required!"));
		return 1;
	}
    for (i = 0; i < cnt; i++)
    {
      if (popstring(buf)) 
      {
        /* free all the memory we have allocated */
		int j;
		for (j = 0; j < i; j++)
			if (list[j] != NULL) free(list[j]);
		free(list);
        PrintMessage(_T("WARNING: NSIS stack in undefined state!"));
        return 2;
      }
	  _tcscat(cmdline, _T("'"));
      _tcscat(cmdline, buf);
      _tcscat(cmdline, _T("' "));

      list[i] = (char *)malloc((_tcslen(buf)+1)*sizeof(char));
	  if (list[i] == NULL)
      {
        /* free all the memory we have allocated */
		int j;
		for (j = 0; j < i; j++)
          if (list[j] != NULL) free(list[j]);
		free(list);
        /* finish popping the stack so its in a known state */
		for ( ; i < cnt; i++)
          popstring(buf);
		PrintMessage(_T("WARNING: ") _T(__FILE__) _T("::getArgList() Unable to allocate memory required!"));
        return 3;
      }
      strcpy(list[i], _T2A(buf));
    }
  }
  else if (cnt < 0)
  {
    PrintMessage(_T(__FILE__) _T("::getArgList() Internal Error: cnt < 0"));
    return 333;
  }

  *argList = list;
  *argCnt = cnt;
  return 0;
}
Example #11
0
void FindReplaceDlg::initDialog(void)
{
	TCITEM		item;
	TCHAR		txtTab[32];

	item.mask		= TCIF_TEXT;
	if (NLGetText(_hInst, _hParent, _T("Find"), txtTab, sizeof(txtTab) / sizeof(TCHAR)) == FALSE)
		_tcscpy_s(txtTab, _T("Find"));
	item.pszText	= txtTab;
	item.cchTextMax	= (int)_tcslen(txtTab);
	::SendDlgItemMessage(_hSelf, IDC_SWITCH, TCM_INSERTITEM, 0, (LPARAM)&item);
	if (NLGetText(_hInst, _hParent, _T("Replace"), txtTab, sizeof(txtTab) / sizeof(TCHAR)) == FALSE)
		_tcscpy_s(txtTab, _T("Replace"));
	item.pszText	= txtTab;
	item.cchTextMax	= (int)_tcslen(txtTab);
	::SendDlgItemMessage(_hSelf, IDC_SWITCH, TCM_INSERTITEM, 1, (LPARAM)&item);

	/* init comboboxes */
	_pFindCombo.reset( new MultiTypeCombo );
	_pReplaceCombo.reset( new MultiTypeCombo );

	_pFindCombo->init(_hParent, ::GetDlgItem(_hSelf, IDC_COMBO_FIND));
	_pReplaceCombo->init(_hParent, ::GetDlgItem(_hSelf, IDC_COMBO_REPLACE));

	/* set default coding */
	_currDataType = HEX_CODE_HEX;
	_pFindCombo->setCodingType(_currDataType);
	_pReplaceCombo->setCodingType(_currDataType);

	/* set data types */
	::SendDlgItemMessage(_hSelf, IDC_COMBO_DATATYPE, CB_SETMINVISIBLE, HEX_CODE_MAX, 0);
    ::SendDlgItemMessage(_hSelf, IDC_COMBO_DATATYPE, CB_INSERTSTRING, HEX_CODE_HEX, (LPARAM)strCode[HEX_CODE_HEX]);
    ::SendDlgItemMessage(_hSelf, IDC_COMBO_DATATYPE, CB_INSERTSTRING, HEX_CODE_ASCI, (LPARAM)strCode[HEX_CODE_ASCI]);
    ::SendDlgItemMessage(_hSelf, IDC_COMBO_DATATYPE, CB_INSERTSTRING, HEX_CODE_UNI, (LPARAM)strCode[HEX_CODE_UNI]);
	::SendDlgItemMessage(_hSelf, IDC_COMBO_DATATYPE, CB_SETCURSEL, _currDataType, 0);


	/* set radios */
	::SendDlgItemMessage(_hSelf, IDC_RADIO_DIRDOWN, BM_SETCHECK, BST_CHECKED, 0);
	::SendDlgItemMessage(_hSelf, IDC_RADIO_BOTTOM, BM_SETCHECK, BST_CHECKED, 0);

	/* set wrap */
	::SendDlgItemMessage(_hSelf, IDC_CHECK_WRAP, BM_SETCHECK, BST_CHECKED, 0);

	/* is transparent mode available? */
	HMODULE hUser32 = ::GetModuleHandle(_T("User32"));

	if (hUser32)
	{
		/* set transparency */
		::SendDlgItemMessage(_hSelf, IDC_SLIDER_PERCENTAGE, TBM_SETRANGE, FALSE, MAKELONG(20, 225));
		::SendDlgItemMessage(_hSelf, IDC_SLIDER_PERCENTAGE, TBM_SETPOS, TRUE, 200);
		_transFuncAddr = (WNDPROC)GetProcAddress(hUser32, "SetLayeredWindowAttributes");
		setTrans();
	}
	else
	{
		::ShowWindow(::GetDlgItem(_hSelf, IDC_CHECK_TRANSPARENT), SW_HIDE);
		::ShowWindow(::GetDlgItem(_hSelf, IDC_SLIDER_PERCENTAGE), SW_HIDE);
	}
	changeCoding();
}
Example #12
0
/** ini_puts()
 * \param Section     the name of the section to write the string in
 * \param Key         the name of the entry to write, or NULL to erase all keys in the section
 * \param Value       a pointer to the buffer the string, or NULL to erase the key
 * \param Filename    the name and full path of the .ini file to write to
 *
 * \return            1 if successful, otherwise 0
 */
int ini_puts(const TCHAR *Section, const TCHAR *Key, const TCHAR *Value, const TCHAR *Filename)
{
    INI_FILETYPE rfp;
    INI_FILETYPE wfp;
    INI_FILEPOS mark;
    INI_FILEPOS head, tail;
    TCHAR *sp, *ep;
    TCHAR LocalBuffer[INI_BUFFERSIZE];
    int len, match, flag, cachelen;

    assert(Filename != NULL);
    if (!ini_openread(Filename, &rfp)) {
        /* If the .ini file doesn't exist, make a new file */
        if (Key != NULL && Value != NULL) {
            if (!ini_openwrite(Filename, &wfp))
                return 0;
            writesection(LocalBuffer, Section, &wfp);
            writekey(LocalBuffer, Key, Value, &wfp);
            (void)ini_close(&wfp);
        } /* if */
        return 1;
    } /* if */

    /* If parameters Key and Value are valid (so this is not an "erase" request)
     * and the setting already exists, there are two short-cuts to avoid rewriting
     * the INI file.
     */
    if (Key != NULL && Value != NULL) {
        ini_tell(&rfp, &mark);
        match = getkeystring(&rfp, Section, Key, -1, -1, LocalBuffer, sizearray(LocalBuffer), &head);
        if (match) {
            /* if the current setting is identical to the one to write, there is
             * nothing to do.
             */
            if (_tcscmp(LocalBuffer,Value) == 0) {
                (void)ini_close(&rfp);
                return 1;
            } /* if */
            /* if the new setting has the same length as the current setting, and the
             * glue file permits file read/write access, we can modify in place.
             */
#if defined ini_openrewrite
            /* we already have the start of the (raw) line, get the end too */
            ini_tell(&rfp, &tail);
            /* create new buffer (without writing it to file) */
            writekey(LocalBuffer, Key, Value, NULL);
            if (_tcslen(LocalBuffer) == (size_t)(tail - head)) {
                /* length matches, close the file & re-open for read/write, then
                 * write at the correct position
                 */
                (void)ini_close(&rfp);
                if (!ini_openrewrite(Filename, &wfp))
                    return 0;
                (void)ini_seek(&wfp, &head);
                (void)ini_write(LocalBuffer, &wfp);
                (void)ini_close(&wfp);
                return 1;
            } /* if */
#endif
        } /* if */
        /* key not found, or different value & length -> proceed (but rewind the
         * input file first)
         */
        (void)ini_seek(&rfp, &mark);
    } /* if */

    /* Get a temporary file name to copy to. Use the existing name, but with
     * the last character set to a '~'.
     */
    ini_tempname(LocalBuffer, Filename, INI_BUFFERSIZE);
    if (!ini_openwrite(LocalBuffer, &wfp)) {
        (void)ini_close(&rfp);
        return 0;
    } /* if */
    ini_tell(&rfp, &mark);
    cachelen = 0;

    /* Move through the file one line at a time until a section is
     * matched or until EOF. Copy to temp file as it is read.
     */
    len = (Section != NULL) ? _tcslen(Section) : 0;
    if (len > 0) {
        do {
            if (!ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp)) {
                /* Failed to find section, so add one to the end */
                flag = cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark);
                if (Key!=NULL && Value!=NULL) {
                    if (!flag)
                        (void)ini_write(INI_LINETERM, &wfp);  /* force a new line behind the last line of the INI file */
                    writesection(LocalBuffer, Section, &wfp);
                    writekey(LocalBuffer, Key, Value, &wfp);
                } /* if */
                return close_rename(&rfp, &wfp, Filename, LocalBuffer);  /* clean up and rename */
            } /* if */
            /* Copy the line from source to dest, but not if this is the section that
             * we are looking for and this section must be removed
             */
            sp = skipleading(LocalBuffer);
            ep = _tcschr(sp, ']');
            match = (*sp == '[' && ep != NULL && (int)(ep-sp-1) == len && _tcsnicmp(sp + 1,Section,len) == 0);
            if (!match || Key != NULL) {
                if (!cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE)) {
                    cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark);
                    (void)ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp);
                    cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE);
                } /* if */
            } /* if */
        } while (!match);
    } /* if */
    cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark);
    /* when deleting a section, the section head that was just found has not been
     * copied to the output file, but because this line was not "accumulated" in
     * the cache, the position in the input file was reset to the point just
     * before the section; this must now be skipped (again)
     */
    if (Key == NULL) {
        (void)ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp);
        ini_tell(&rfp, &mark);
    } /* if */

    /* Now that the section has been found, find the entry. Stop searching
     * upon leaving the section's area. Copy the file as it is read
     * and create an entry if one is not found.
     */
    len = (Key!=NULL) ? _tcslen(Key) : 0;
    for( ;; ) {
        if (!ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp)) {
            /* EOF without an entry so make one */
            flag = cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark);
            if (Key!=NULL && Value!=NULL) {
                if (!flag)
                    (void)ini_write(INI_LINETERM, &wfp);  /* force a new line behind the last line of the INI file */
                writekey(LocalBuffer, Key, Value, &wfp);
            } /* if */
            return close_rename(&rfp, &wfp, Filename, LocalBuffer);  /* clean up and rename */
        } /* if */
        sp = skipleading(LocalBuffer);
        ep = _tcschr(sp, '='); /* Parse out the equal sign */
        if (ep == NULL)
            ep = _tcschr(sp, ':');
        match = (ep != NULL && len > 0 && (int)(skiptrailing(ep,sp)-sp) == len && _tcsnicmp(sp,Key,len) == 0);
        if ((Key != NULL && match) || *sp == '[')
            break;  /* found the key, or found a new section */
        /* copy other keys in the section */
        if (Key == NULL) {
            ini_tell(&rfp, &mark);  /* we are deleting the entire section, so update the read position */
        } else {
            if (!cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE)) {
                cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark);
                (void)ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp);
                cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE);
            } /* if */
        } /* if */
    } /* for */
    /* the key was found, or we just dropped on the next section (meaning that it
     * wasn't found); in both cases we need to write the key, but in the latter
     * case, we also need to write the line starting the new section after writing
     * the key
     */
    flag = (*sp == '[');
    cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark);
    if (Key != NULL && Value != NULL)
        writekey(LocalBuffer, Key, Value, &wfp);
    /* cache_flush() reset the "read pointer" to the start of the line with the
     * previous key or the new section; read it again (because writekey() destroyed
     * the buffer)
     */
    (void)ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp);
    if (flag) {
        /* the new section heading needs to be copied to the output file */
        cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE);
    } else {
        /* forget the old key line */
        ini_tell(&rfp, &mark);
    } /* if */
    /* Copy the rest of the INI file */
    while (ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp)) {
        if (!cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE)) {
            cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark);
            (void)ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp);
            cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE);
        } /* if */
    } /* while */
    cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark);
    return close_rename(&rfp, &wfp, Filename, LocalBuffer);  /* clean up and rename */
}
Example #13
0
static int getkeystring(INI_FILETYPE *fp, const TCHAR *Section, const TCHAR *Key,
                        int idxSection, int idxKey, TCHAR *Buffer, int BufferSize,
                        INI_FILEPOS *mark)
{
    TCHAR *sp, *ep;
    int len, idx;
    enum quote_option quotes;
    TCHAR LocalBuffer[INI_BUFFERSIZE];

    assert(fp != NULL);
    /* Move through file 1 line at a time until a section is matched or EOF. If
     * parameter Section is NULL, only look at keys above the first section. If
     * idxSection is postive, copy the relevant section name.
     */
    len = (Section != NULL) ? _tcslen(Section) : 0;
    if (len > 0 || idxSection >= 0) {
        idx = -1;
        do {
            if (!ini_read(LocalBuffer, INI_BUFFERSIZE, fp))
                return 0;
            sp = skipleading(LocalBuffer);
            ep = _tcschr(sp, ']');
        } while (*sp != '[' || ep == NULL || (((int)(ep-sp-1) != len || _tcsnicmp(sp+1,Section,len) != 0) && ++idx != idxSection));
        if (idxSection >= 0) {
            if (idx == idxSection) {
                assert(ep != NULL);
                assert(*ep == ']');
                *ep = '\0';
                save_strncpy(Buffer, sp + 1, BufferSize, QUOTE_NONE);
                return 1;
            } /* if */
            return 0; /* no more section found */
        } /* if */
    } /* if */

    /* Now that the section has been found, find the entry.
     * Stop searching upon leaving the section's area.
     */
    assert(Key != NULL || idxKey >= 0);
    len = (Key != NULL) ? (int)_tcslen(Key) : 0;
    idx = -1;
    do {
        if (mark != NULL)
            ini_tell(fp, mark);   /* optionally keep the mark to the start of the line */
        if (!ini_read(LocalBuffer,INI_BUFFERSIZE,fp) || *(sp = skipleading(LocalBuffer)) == '[')
            return 0;
        sp = skipleading(LocalBuffer);
        ep = _tcschr(sp, '=');  /* Parse out the equal sign */
        if (ep == NULL)
            ep = _tcschr(sp, ':');
    } while (*sp == ';' || *sp == '#' || ep == NULL
             || ((len == 0 || (int)(skiptrailing(ep,sp)-sp) != len || _tcsnicmp(sp,Key,len) != 0) && ++idx != idxKey));
    if (idxKey >= 0) {
        if (idx == idxKey) {
            assert(ep != NULL);
            assert(*ep == '=' || *ep == ':');
            *ep = '\0';
            striptrailing(sp);
            save_strncpy(Buffer, sp, BufferSize, QUOTE_NONE);
            return 1;
        } /* if */
        return 0;   /* no more key found (in this section) */
    } /* if */

    /* Copy up to BufferSize chars to buffer */
    assert(ep != NULL);
    assert(*ep == '=' || *ep == ':');
    sp = skipleading(ep + 1);
    sp = cleanstring(sp, &quotes);  /* Remove a trailing comment */
    save_strncpy(Buffer, sp, BufferSize, quotes);
    return 1;
}
Example #14
0
// Function name	: RunLocal
// Description	    : 
// Return type		: void 
// Argument         : bool bDoSMP
void RunLocal(bool bDoSMP)
{
	DWORD size = 100;
	TCHAR pszHost[100], pszCmdLine[MAX_PATH], error_msg[256], pszEnv[256], pszExtra[MAX_PATH];
	STARTUPINFO saInfo;
	PROCESS_INFORMATION psInfo;
	LPTSTR pEnv;
	int rootPort=0;
	HANDLE *hProcess = new HANDLE[g_nHosts];
			
	GetComputerName(pszHost, &size);

	wsprintf(pszCmdLine, TEXT("%s %s"), g_pszExe, g_pszArgs);

	GetTempFileName(_T("."), _T("mpi"), 0, pszExtra);
	// This produces a name in the form: ".\XXXmpi.tmp"
	// \ is illegal in named objects so use &pszExtra[2] instead of pszExtra for the JobID
	if (bDoSMP)
	{
		wsprintf(pszEnv, _T("MPICH_JOBID=%s|MPICH_IPROC=0|MPICH_NPROC=%d|MPICH_ROOTHOST=%s|MPICH_ROOTPORT=%d|MPICH_EXTRA=%s|MPICH_COMNIC=%s|MPICH_SHM_LOW=0|MPICH_SHM_HIGH=%d"),
				&pszExtra[2], g_nHosts, pszHost, -1, pszExtra, pszHost, g_nHosts-1);
	}
	else
	{
		wsprintf(pszEnv, _T("MPICH_JOBID=%s|MPICH_IPROC=0|MPICH_NPROC=%d|MPICH_ROOTHOST=%s|MPICH_ROOTPORT=%d|MPICH_EXTRA=%s|MPICH_COMNIC=%s"),
				&pszExtra[2], g_nHosts, pszHost, -1, pszExtra, pszHost);
	}

	SetEnvironmentVariables(pszEnv);
	if (_tcslen(g_pszEnv) > 0)
		SetEnvironmentVariables(g_pszEnv);
	pEnv = GetEnvironmentStrings();

	GetStartupInfo(&saInfo);

	// launch first process
	if (CreateProcess(
		NULL,
		pszCmdLine,
		NULL, NULL, FALSE,
		IDLE_PRIORITY_CLASS, 
		pEnv,
		NULL,
		&saInfo, &psInfo))
	{
		hProcess[0] = psInfo.hProcess;
		CloseHandle(psInfo.hThread);
	}
	else
	{
		int error = GetLastError();
		Translate_Error(error, error_msg, TEXT("CreateProcess failed: "));
		_tprintf(TEXT("Unable to launch '%s', error %d: %s"), pszCmdLine, error, error_msg);
		return;
	}

	RemoveEnvironmentVariables(pszEnv);
	FreeEnvironmentStrings(pEnv);

	if (g_bNoMPI)
	{
		rootPort = -1;
	}
	else
	{
		// Open the file and read the port number written by the first process
		HANDLE hFile = CreateFile(pszExtra, GENERIC_READ, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
		if (hFile == INVALID_HANDLE_VALUE)
		{
			Translate_Error(GetLastError(), error_msg, TEXT("CreateFile failed "));
			_tprintf(error_msg);
			return;
		}
		
		DWORD num_read = 0;
		TCHAR pBuffer[100];
		pBuffer[0] = '\0';
		TCHAR *pChar = pBuffer;
		clock_t cStart = clock();
		while (true)
		{
			num_read = 0;
			if (!ReadFile(hFile, pChar, 100, &num_read, NULL))
			{
				Translate_Error(GetLastError(), error_msg, TEXT("ReadFile failed "));
				_tprintf(error_msg);
				return;
			}
			if (num_read == 0)
			{
				if (clock() - cStart > 10 * CLOCKS_PER_SEC)
				{
					_tprintf(TEXT("Wait for process 0 to write port to temporary file timed out\n"));
					TerminateProcess(hProcess, 0);
					return;
				}
				Sleep(100);
			}
			else
			{
				for (int i=0; i<(int)num_read; i++)
				{
					if (*pChar == _T('\n'))
						break;
					pChar ++;
				}
				if (*pChar == _T('\n'))
					break;
			}
		}
		CloseHandle(hFile);
		rootPort = _ttoi(pBuffer);
	}
	DeleteFile(pszExtra);

	// launch all the rest of the processes
	for (int i=1; i<g_nHosts; i++)
	{
		if (bDoSMP)
		{
			wsprintf(pszEnv, _T("MPICH_JOBID=%s|MPICH_IPROC=%d|MPICH_NPROC=%d|MPICH_ROOTHOST=%s|MPICH_ROOTPORT=%d|MPICH_COMNIC=%s|MPICH_SHM_LOW=0|MPICH_SHM_HIGH=%d"),
				&pszExtra[2], i, g_nHosts, pszHost, rootPort, pszHost, g_nHosts-1);
		}
		else
		{
			wsprintf(pszEnv, _T("MPICH_JOBID=%s|MPICH_IPROC=%d|MPICH_NPROC=%d|MPICH_ROOTHOST=%s|MPICH_ROOTPORT=%d|MPICH_COMNIC=%s"),
				&pszExtra[2], i, g_nHosts, pszHost, rootPort, pszHost);
		}
		
		SetEnvironmentVariables(pszEnv);
		pEnv = GetEnvironmentStrings();
		
		if (CreateProcess(
			NULL,
			pszCmdLine,
			NULL, NULL, FALSE,
			IDLE_PRIORITY_CLASS, 
			pEnv,
			NULL,
			&saInfo, &psInfo))
		{
			hProcess[i] = psInfo.hProcess;
			CloseHandle(psInfo.hThread);
		}
		else
		{
			int error = GetLastError();
			Translate_Error(error, error_msg, TEXT("CreateProcess failed: "));
			_tprintf(TEXT("Unable to launch '%s', error %d: %s"), pszCmdLine, error, error_msg);
			return;
		}
		
		RemoveEnvironmentVariables(pszEnv);
		FreeEnvironmentStrings(pEnv);
	}

	// Wait for all the processes to terminate
	WaitForLotsOfObjects(g_nHosts, hProcess);

	for (i=0; i<g_nHosts; i++)
		CloseHandle(hProcess[i]);
	delete hProcess;
}
Example #15
0
int SafeStrlen(LPCTSTR lpsz)
{
	return (lpsz == NULL) ? NULL : _tcslen(lpsz);
}
Example #16
0
static void FillListBox()
{
	WIN32_FIND_DATA wfd;
	HANDLE hSearch;
	TCHAR szFilePath[MAX_PATH];
	TCHAR szFilePathSearch[MAX_PATH];
	TCHAR szFileName[MAX_PATH];
	TCHAR *PatchDesc = NULL;
	TCHAR PatchName[256];
	int nHandlePos = 0;
	
	TV_INSERTSTRUCT TvItem;
	
	memset(&TvItem, 0, sizeof(TvItem));
	TvItem.item.mask = TVIF_TEXT | TVIF_PARAM;
	TvItem.hInsertAfter = TVI_LAST;

	_stprintf(szFilePath, _T("%s%s\\"), szAppIpsPath, BurnDrvGetText(DRV_NAME));
	_stprintf(szFilePathSearch, _T("%s*.dat"), szFilePath);
	
	hSearch = FindFirstFile(szFilePathSearch, &wfd);

	if (hSearch != INVALID_HANDLE_VALUE) {
		int Done = 0;
		
		while (!Done ) {
			memset(szFileName, '\0', MAX_PATH);
			_stprintf(szFileName, _T("%s%s"), szFilePath, wfd.cFileName);
			
			FILE *fp = _tfopen(szFileName, _T("r"));
			if (fp) {
				PatchDesc = NULL;
				memset(PatchName, '\0', 256);
				
				PatchDesc = GetPatchDescByLangcode(fp, nIpsSelectedLanguage);
				// If not available - try English first
				if (PatchDesc == NULL) PatchDesc = GetPatchDescByLangcode(fp, 0);
				// Simplified Chinese is the reference language (should always be available!!)
				if (PatchDesc == NULL) PatchDesc = GetPatchDescByLangcode(fp, 1);
				
				for (unsigned int i = 0; i < _tcslen(PatchDesc); i++) {
					if (PatchDesc[i] == '\r' || PatchDesc[i] == '\n') break;
					PatchName[i] = PatchDesc[i];					
				}
				
				// Check for categories
				TCHAR *Tokens;
				int nNumTokens = 0;
				int nNumNodes = 0;
				TCHAR szCategory[256];
				unsigned int nPatchNameLength = _tcslen(PatchName);
								
				Tokens = _tcstok(PatchName, _T("/"));
				while (Tokens != NULL) {
					if (nNumTokens == 0) {
						int bAddItem = 1;
						// Check if item already exists
						nNumNodes = SendMessage(hIpsList, TVM_GETCOUNT, (WPARAM)0, (LPARAM)0);
						for (int i = 0; i < nNumNodes; i++) {
							TCHAR Temp[256];
							TVITEM Tvi;
							memset(&Tvi, 0, sizeof(Tvi));
							Tvi.hItem = hItemHandles[i];
							Tvi.mask = TVIF_TEXT | TVIF_HANDLE;
							Tvi.pszText = Temp;
							Tvi.cchTextMax = 256;
							SendMessage(hIpsList, TVM_GETITEM, (WPARAM)0, (LPARAM)&Tvi);

							if (!_tcsicmp(Tvi.pszText, Tokens)) bAddItem = 0;
						}
						
						if (bAddItem) {
							TvItem.hParent = TVI_ROOT;
							TvItem.item.pszText = Tokens;
							hItemHandles[nHandlePos] = (HTREEITEM)SendMessage(hIpsList, TVM_INSERTITEM, 0, (LPARAM)&TvItem);
							nHandlePos++;
						}
						
						if (_tcslen(Tokens) == nPatchNameLength) {
							hPatchHandlesIndex[nPatchIndex] = hItemHandles[nHandlePos - 1];
							_tcscpy(szPatchFileNames[nPatchIndex], szFileName);
						
							nPatchIndex++;
						}
						
						_tcscpy(szCategory, Tokens);
					} else {
						HTREEITEM hNode = TVI_ROOT;
						// See which category we should be in
						nNumNodes = SendMessage(hIpsList, TVM_GETCOUNT, (WPARAM)0, (LPARAM)0);
						for (int i = 0; i < nNumNodes; i++) {
							TCHAR Temp[256];
							TVITEM Tvi;
							memset(&Tvi, 0, sizeof(Tvi));
							Tvi.hItem = hItemHandles[i];
							Tvi.mask = TVIF_TEXT | TVIF_HANDLE;
							Tvi.pszText = Temp;
							Tvi.cchTextMax = 256;
							SendMessage(hIpsList, TVM_GETITEM, (WPARAM)0, (LPARAM)&Tvi);

							if (!_tcsicmp(Tvi.pszText, szCategory)) hNode = Tvi.hItem;
						}
						
						TvItem.hParent = hNode;
						TvItem.item.pszText = Tokens;
						hItemHandles[nHandlePos] = (HTREEITEM)SendMessage(hIpsList, TVM_INSERTITEM, 0, (LPARAM)&TvItem);
												
						hPatchHandlesIndex[nPatchIndex] = hItemHandles[nHandlePos];
						_tcscpy(szPatchFileNames[nPatchIndex], szFileName);
						
						nHandlePos++;
						nPatchIndex++;
					}
					
					Tokens = _tcstok(NULL, _T("/"));
					nNumTokens++;
				}
				
				fclose(fp);
			}

			Done = !FindNextFile(hSearch, &wfd);
		}

		FindClose(hSearch);
	}
	
	nNumPatches = nPatchIndex;
	
	// Expand all branches
	int nNumNodes = SendMessage(hIpsList, TVM_GETCOUNT, (WPARAM)0, (LPARAM)0);;
	for (int i = 0; i < nNumNodes; i++) {
		SendMessage(hIpsList, TVM_EXPAND, TVE_EXPAND, (LPARAM)hItemHandles[i]);
	}
}
Example #17
0
static BOOL isExt(LPCTSTR filename, LPCTSTR ext)
{
	return _tcsicmp(filename + _tcslen(filename) - 4, ext) == 0;
}
Example #18
0
static int IpsManagerInit()
{
	// Get the games full name
	TCHAR szText[1024] = _T("");
	TCHAR* pszPosition = szText;
	TCHAR* pszName = BurnDrvGetText(DRV_FULLNAME);

	pszPosition += _sntprintf(szText, 1024, pszName);
	
	pszName = BurnDrvGetText(DRV_FULLNAME);
	while ((pszName = BurnDrvGetText(DRV_NEXTNAME | DRV_FULLNAME)) != NULL) {
		if (pszPosition + _tcslen(pszName) - 1024 > szText) {
			break;
		}
		pszPosition += _stprintf(pszPosition, _T(SEPERATOR_2) _T("%s"), pszName);
	}
	
	_tcscpy(szFullName, szText);
	
	_stprintf(szText, _T("%s") _T(SEPERATOR_1) _T("%s"), FBALoadStringEx(hAppInst, IDS_IPSMANAGER_TITLE, true), szFullName);
	
	// Set the window caption
	SetWindowText(hIpsDlg, szText);
	
	// Fill the combo box
	_stprintf(szLanguages[0], _T("English (US)"));
	_stprintf(szLanguages[1], _T("Simplified Chinese"));
	_stprintf(szLanguages[2], _T("Traditional Chinese"));
	_stprintf(szLanguages[3], _T("Japanese"));
	_stprintf(szLanguages[4], _T("Korean"));
	_stprintf(szLanguages[5], _T("French"));
	_stprintf(szLanguages[6], _T("Spanish"));
	_stprintf(szLanguages[7], _T("Italian"));
	_stprintf(szLanguages[8], _T("German"));
	_stprintf(szLanguages[9], _T("Portuguese"));
	_stprintf(szLanguages[10], _T("Polish"));
	_stprintf(szLanguages[11], _T("Hungarian"));
	
	_stprintf(szLanguageCodes[0], _T("en_US"));
	_stprintf(szLanguageCodes[1], _T("zh_CN"));
	_stprintf(szLanguageCodes[2], _T("zh_TW"));
	_stprintf(szLanguageCodes[3], _T("ja_JP"));
	_stprintf(szLanguageCodes[4], _T("ko_KR"));
	_stprintf(szLanguageCodes[5], _T("fr_FR"));
	_stprintf(szLanguageCodes[6], _T("es_ES"));
	_stprintf(szLanguageCodes[7], _T("it_IT"));
	_stprintf(szLanguageCodes[8], _T("de_DE"));
	_stprintf(szLanguageCodes[9], _T("pt_BR"));
	_stprintf(szLanguageCodes[10], _T("pl_PL"));
	_stprintf(szLanguageCodes[11], _T("hu_HU"));

	for (int i = 0; i < NUM_LANGUAGES; i++) {
		SendDlgItemMessage(hIpsDlg, IDC_CHOOSE_LIST, CB_ADDSTRING, 0, (LPARAM)&szLanguages[i]);
	}
	
	SendDlgItemMessage(hIpsDlg, IDC_CHOOSE_LIST, CB_SETCURSEL, (WPARAM)nIpsSelectedLanguage, (LPARAM)0);
	
	hIpsList = GetDlgItem(hIpsDlg, IDC_TREE1);
	
	FillListBox();
	
	CheckActivePatches();
	
	return 0;
}
Example #19
0
		ArrayBlock<RawMouse> getRawMouseArray()
		{
			UINT nDevices;
			PRAWINPUTDEVICELIST pRawInputDeviceList;
			list<RawMouse> rawMiceList;

			if (GetRawInputDeviceList(NULL, &nDevices, sizeof(RAWINPUTDEVICELIST)) != 0)
			{
				showErrorMessageAndExit(L"GetRawInputDeviceList() count");
			}

			pRawInputDeviceList = safeMallocExitOnFailure<RAWINPUTDEVICELIST>(nDevices);

			if (((INT) GetRawInputDeviceList(pRawInputDeviceList, &nDevices, sizeof(RAWINPUTDEVICELIST))) < 0)
			{
				showErrorMessageAndExit(L"GetRawInputDeviceList() get");
			}

			for (UINT currentDeviceIndex = 0; currentDeviceIndex < nDevices; currentDeviceIndex++)
			{
				DWORD currentDeviceType = pRawInputDeviceList[currentDeviceIndex].dwType;
				HANDLE hDevice = pRawInputDeviceList[currentDeviceIndex].hDevice;

				if (currentDeviceType == RIM_TYPEMOUSE)
				{
					UINT cbSize;
					TCHAR* psName;

					if (GetRawInputDeviceInfo(hDevice, RIDI_DEVICENAME, NULL, &cbSize) != 0)
					{
						showErrorMessageAndExit(L"GetRawInputDeviceInfo() count");
					}

					psName = safeMallocExitOnFailure<TCHAR>(cbSize);

					if (((INT) GetRawInputDeviceInfo(hDevice, RIDI_DEVICENAME, psName, &cbSize)) < 0)
					{
						safe_free(&psName);
						showErrorMessageAndExit(L"GetRawInputDeviceInfo() get");
					}

					assert(_tcsnlen(psName, cbSize) == cbSize - 1);

					// We want to ignore RDP mice
					{
						TCHAR rdpMouseName[] = _T("\\\\?\\Root#RDP_MOU#0000#");
						size_t rdpMouseNameStrlen = _tcslen(rdpMouseName);

						if (_tcslen(psName) >= rdpMouseNameStrlen && 
							_tcsncmp(rdpMouseName, psName, rdpMouseNameStrlen) == 0)
						{
							safe_free(&psName);
							continue;
						}
					}

					safe_free(&psName);

					if (GetRawInputDeviceInfo(hDevice, RIDI_DEVICEINFO, NULL, &cbSize) != 0)
					{
						showErrorMessageAndExit(L"GetRawInputDeviceInfo() count");
					}

					PRID_DEVICE_INFO pDeviceInfo = safeMallocBytesExitOnFailure<RID_DEVICE_INFO>(cbSize);

					pDeviceInfo->cbSize = cbSize;

					if (((INT) GetRawInputDeviceInfo(hDevice, RIDI_DEVICEINFO, pDeviceInfo, &cbSize)) < 0)
					{
						showErrorMessageAndExit(L"GetRawInputDeviceInfo() get");
					}

					assert(pDeviceInfo->dwType == RIM_TYPEMOUSE);

					RawMouse currentMouse;
					currentMouse.deviceHandle = pRawInputDeviceList[currentDeviceIndex].hDevice;
					currentMouse.x = 0;
					currentMouse.y = 0;
					currentMouse.z = 0;
					currentMouse.buttonsPressed = ArrayBlock<bool>();
					currentMouse.buttonsPressed.allocate(pDeviceInfo->mouse.dwNumberOfButtons);

					memset(currentMouse.buttonsPressed.data(), 0, 
						sizeof(bool)*currentMouse.buttonsPressed.count());

					rawMiceList.push_back(currentMouse);
				}
			}

			safe_free(&pRawInputDeviceList);

			ArrayBlock<RawMouse> out_rawMiceArray;
			out_rawMiceArray.allocate(rawMiceList.size());

			size_t currentPos = 0;

			for (list<RawMouse>::iterator rawMouseIt = rawMiceList.begin(); 
				rawMouseIt != rawMiceList.end(); rawMouseIt++)
			{
				out_rawMiceArray.data()[currentPos] = *rawMouseIt;
				currentPos++;
			}

			return out_rawMiceArray;
		}
Example #20
0
/***
*int _cenvarg(argv, envp, argblk, envblk, name) - set up cmd line/environ
*
*Purpose:
*       Set up the block forms of  the environment and the command line.
*       If "envp" is null, "_environ" is used instead.
*       File handle info is passed in the environment if _fileinfo is !0.
*
*Entry:
*       _TSCHAR **argv   - argument vector
*       _TSCHAR **envp   - environment vector
*       _TSCHAR **argblk - pointer to pointer set to malloc'ed space for args
*       _TSCHAR **envblk - pointer to pointer set to malloc'ed space for env
*       _TSCHAR *name    - name of program being invoked
*
*Exit:
*       returns 0 if ok, -1 if fails
*       stores through argblk and envblk
*       (calls malloc)
*
*Exceptions:
*
*******************************************************************************/

#ifdef WPRFLAG
int __cdecl _wcenvarg (
#else  /* WPRFLAG */
int __cdecl _cenvarg (
#endif  /* WPRFLAG */
        const _TSCHAR * const *argv,
        const _TSCHAR * const *envp,
        _TSCHAR **argblk,
        _TSCHAR **envblk,
        const _TSCHAR *name
        )
{
        REG1 const _TSCHAR * const *vp;
        REG2 unsigned tmp;
        REG3 _TSCHAR *cptr;
        unsigned arg_len;
        int cfi_len;            /* counts the number of file handles in CFI */

        /*
         * Null environment pointer "envp" means use global variable,
         * "_environ"
         */

        int cwd_start;
        int cwd_end;            /* length of "cwd" strings in environment */

        /*
         * Allocate space for command line string
         *  tmp counts the number of bytes in the command line string
         *      including spaces between arguments
         *  An empty string is special -- 2 bytes
         */

        for (vp = argv, tmp = 2; *vp; tmp += _tcslen(*vp++) + 1) ;

        arg_len = tmp;

        /*
         * Allocate space for the command line plus 2 null bytes
         */

        if ( (*argblk = _malloc_crt(tmp * sizeof(_TSCHAR))) == NULL)
        {
                *envblk = NULL;
                errno = ENOMEM;
                _doserrno = E_nomem;
                return(-1);
        }

        /*
         * Allocate space for environment strings
         *  tmp counts the number of bytes in the environment strings
         *      including nulls between strings
         *  Also add "_C_FILE_INFO=" string
         */
        if (envp)
                for (vp = envp, tmp = 2; *vp; tmp += _tcslen(*vp++) + 1) ;

        /*
         * The _osfile and _osfhnd arrays are passed as binary data in
         * dospawn.c
         */
        cfi_len = 0;    /* no _C_FILE_INFO */

        if (!envp)
                *envblk = NULL;
        else {
                /*
                 * Now that we've decided to pass our own environment block,
                 * compute the size of the "current directory" strings to
                 * propagate to the new environment.
                 */

#ifdef WPRFLAG
            /*
             * Make sure wide environment exists.
             */
            if (!_wenvptr)
            {
                    if ((_wenvptr = (wchar_t *)__crtGetEnvironmentStringsW()) == NULL)
                    return -1;
            }
#else  /* WPRFLAG */
            if (!_aenvptr)
            {
                    if ((_aenvptr = (char *)__crtGetEnvironmentStringsA()) == NULL)
                    return -1;
            }
#endif  /* WPRFLAG */

            /*
                 * search for the first one
                 */
                for (cwd_start = 0;
                     _tenvptr[cwd_start] != _T('\0') &&
                       _tenvptr[cwd_start] != _T('=');
                     cwd_start += _tcslen(&_tenvptr[cwd_start]) + 1)
                {
                }

                /* find the total size of all contiguous ones */
                cwd_end = cwd_start;
                while (_tenvptr[cwd_end+0] == _T('=') &&
                       _tenvptr[cwd_end+1] != _T('\0') &&
                       _tenvptr[cwd_end+2] == _T(':') &&
                       _tenvptr[cwd_end+3] == _T('='))
                {
                        cwd_end += 4 + _tcslen(&_tenvptr[cwd_end+4]) + 1;
                }
                tmp += cwd_end - cwd_start;

                /*
                 * Allocate space for the environment strings plus extra null byte
                 */
                if( !(*envblk = _malloc_crt(tmp * sizeof(_TSCHAR))) )
            {
                        _free_crt(*argblk);
                        *argblk = NULL;
                        errno = ENOMEM;
                        _doserrno = E_nomem;
                        return(-1);
                }

        }

        /*
         * Build the command line by concatenating the argument strings
         * with spaces between, and two null bytes at the end.
         * NOTE: The argv[0] argument is followed by a null.
         */

        cptr = *argblk;
        vp = argv;

        if (!*vp)       /* Empty argument list ? */
                ++cptr; /* just two null bytes */
        else {          /* argv[0] must be followed by a null */
                _tcscpy(cptr, *vp);
                cptr += _tcslen(*vp++) + 1;
        }

        while( *vp ) {
                _tcscpy(cptr, *vp);
                cptr += _tcslen(*vp++);
                *cptr++ = ' ';
        }

        *cptr = cptr[ -1 ] = _T('\0'); /* remove extra blank, add double null */

        /*
         * Build the environment block by concatenating the environment
         * strings with nulls between and two null bytes at the end
         */

        cptr = *envblk;

        if (envp != NULL) {
                /*
                 * Copy the "cwd" strings to the new environment.
                 */
                memcpy(cptr, &_tenvptr[cwd_start], (cwd_end - cwd_start) * sizeof(_TSCHAR));
                cptr += cwd_end - cwd_start;

                /*
                 * Copy the environment strings from "envp".
                 */
                vp = envp;
                while( *vp ) {
                        _tcscpy(cptr, *vp);
                        cptr += 1 + _tcslen(*vp++);
                }
        }

        if (cptr != NULL) {
                if (cptr == *envblk) {
                        /*
                         * Empty environment block ... this requires two
                         * nulls.
                         */
                        *cptr++ = _T('\0');
                }
                /*
                 * Extra null terminates the segment
                 */
                *cptr = _T('\0');
        }

#ifdef WPRFLAG
        _free_crt(_wenvptr);
        _wenvptr = NULL;
#else  /* WPRFLAG */
        _free_crt(_aenvptr);
        _aenvptr = NULL;
#endif  /* WPRFLAG */
        return(0);
}
Example #21
0
static int
GetKeyFilename(connection_t *c, TCHAR *keyfilename, size_t keyfilenamesize, int *keyfile_format, bool silent)
{
  FILE *fp = NULL;
  char line[256];
  int found_key=0;
  int found_pkcs12=0;
  TCHAR configfile_path[MAX_PATH];
  int ret = 0;

  _tcsncpy(configfile_path, c->config_dir, _countof(configfile_path));
  if (!(configfile_path[_tcslen(configfile_path)-1] == '\\'))
    _tcscat(configfile_path, _T("\\"));
  _tcsncat(configfile_path, c->config_file,
          _countof(configfile_path) - _tcslen(configfile_path) - 1);

  if (!(fp=_tfopen(configfile_path, _T("r"))))
    {
      /* can't open config file */
      if (!silent)
        ShowLocalizedMsg(IDS_ERR_OPEN_CONFIG, configfile_path);
      goto out;
    }

  while (fgets(line, sizeof (line), fp))
    {
      if (LineBeginsWith(line, "key", 3))
        {
          if (found_key)
            {
              /* only one key option */
              if (!silent)
                ShowLocalizedMsg(IDS_ERR_ONLY_ONE_KEY_OPTION);
              goto out;
            }
          if (found_pkcs12)
            {
              /* key XOR pkcs12 */
	      if (!silent)
                ShowLocalizedMsg(IDS_ERR_ONLY_KEY_OR_PKCS12);
              goto out;
            }
          found_key=1;
          *keyfile_format = KEYFILE_FORMAT_PEM;
          if (!ParseKeyFilenameLine(c, keyfilename, keyfilenamesize, &line[4]))
            goto out;
        }
      if (LineBeginsWith(line, "pkcs12", 6))
        {
          if (found_pkcs12)
            {
              /* only one pkcs12 option */
	      if (!silent)
                ShowLocalizedMsg(IDS_ERR_ONLY_ONE_PKCS12_OPTION);
              goto out;
            }
          if (found_key)
            {
              /* only key XOR pkcs12 */
	      if (!silent)
                ShowLocalizedMsg(IDS_ERR_ONLY_KEY_OR_PKCS12);
              goto out;
            }
          found_pkcs12=1;
          *keyfile_format = KEYFILE_FORMAT_PKCS12;
          if (!ParseKeyFilenameLine(c, keyfilename, keyfilenamesize, &line[7]))
            goto out;
        }
    }

  if ((!found_key) && (!found_pkcs12))
    {
      /* must have key or pkcs12 option */
      if (!silent)
        ShowLocalizedMsg(IDS_ERR_HAVE_KEY_OR_PKCS12);
      goto out;
    }
  ret = 1;
out:
  if (fp)
    fclose(fp);
  return ret;
}
Example #22
0
static void parse_cmdline (int argc, TCHAR **argv)
{
	int i;

	for (i = 1; i < argc; i++) {
		if (!_tcsncmp (argv[i], "-diskswapper=", 13)) {
			TCHAR *txt = parsetext (argv[i] + 13);
			parse_diskswapper (txt);
			xfree (txt);
		} else if (_tcsncmp (argv[i], "-cfgparam=", 10) == 0) {
			;
		} else if (_tcscmp (argv[i], "-cfgparam") == 0) {
			if (i + 1 < argc)
				i++;
		} else if (_tcsncmp (argv[i], "-config=", 8) == 0) {
			TCHAR *txt = parsetext (argv[i] + 8);
			currprefs.mountitems = 0;
			target_cfgfile_load (&currprefs, txt, -1, 0);
			xfree (txt);
		} else if (_tcsncmp (argv[i], "-statefile=", 11) == 0) {
			TCHAR *txt = parsetext (argv[i] + 11);
			savestate_state = STATE_DORESTORE;
			_tcscpy (savestate_fname, txt);
			xfree (txt);
		} else if (_tcscmp (argv[i], "-f") == 0) {
			/* Check for new-style "-f xxx" argument, where xxx is config-file */
			if (i + 1 == argc) {
				write_log ("Missing argument for '-f' option.\n");
			} else {
				TCHAR *txt = parsetext (argv[++i]);
				currprefs.mountitems = 0;
				target_cfgfile_load (&currprefs, txt, -1, 0);
				xfree (txt);
			}
		} else if (_tcscmp (argv[i], "-s") == 0) {
			if (i + 1 == argc)
				write_log ("Missing argument for '-s' option.\n");
			else
				cfgfile_parse_line (&currprefs, argv[++i], 0);
		} else if (_tcscmp (argv[i], "-h") == 0 || _tcscmp (argv[i], "-help") == 0) {
			usage ();
			exit (0);
		} else if (_tcsncmp (argv[i], "-cdimage=", 9) == 0) {
			TCHAR *txt = parsetext (argv[i] + 9);
			TCHAR *txt2 = xmalloc(TCHAR, _tcslen(txt) + 2);
			_tcscpy(txt2, txt);
			if (_tcsrchr(txt2, ',') != NULL)
				_tcscat(txt2, ",");
			cfgfile_parse_option (&currprefs, "cdimage0", txt2, 0);
			xfree(txt2);
			xfree (txt);
		} else {
			if (argv[i][0] == '-' && argv[i][1] != '\0') {
				const TCHAR *arg = argv[i] + 2;
				int extra_arg = *arg == '\0';
				if (extra_arg)
					arg = i + 1 < argc ? argv[i + 1] : 0;
				if (parse_cmdline_option (&currprefs, argv[i][1], arg) && extra_arg)
					i++;
			}
		}
	}
}
Example #23
0
BOOL CDllFinder::FindDll(TCHAR* tWorkingDirectory,TCHAR* tDllName,OUT TCHAR* tFullPath)
{
    //The \WINNT\SYSTEM32 directory. 
    //The directory of the executable for the process that is loading the DLL. 
    //The current directory of the process that is loading the DLL. 
    //The \WINNT directory. 
    //A directory listed in the PATH environment variable. 
    
    TCHAR psz[MAX_PATH];
    TCHAR pszDirectory[MAX_PATH];
    TCHAR DllName[MAX_PATH];
    TCHAR* pstr;

    // in case full path is already specified
    if (CDllFinder::DoesFileExists(tDllName))
    {
        _tcscpy(tFullPath,tDllName);
        return TRUE;
    }

    // remove directory if any
    _tcsncpy(DllName,tDllName,MAX_PATH);
    DllName[MAX_PATH-1]=0;
    pstr=_tcsrchr(tDllName,'\\');
    if (pstr)
        _tcscpy(DllName,pstr);

    // check if file exists in SYSTEM32 path
    *pszDirectory=0;
    GetSystemDirectory(pszDirectory,MAX_PATH);
    _tcscpy(psz,pszDirectory);
    _tcscat(psz,DllName);
    if (CDllFinder::DoesFileExists(psz))
    {
        _tcscpy(tFullPath,psz);
        return TRUE;
    }

    // check if file exists in WorkingDirectory
    if (tWorkingDirectory)
    {
        // forge full name

        _tcscpy(psz,tWorkingDirectory);
        // if directory doesn't ends with '\' add it
        if (tWorkingDirectory[_tcslen(tWorkingDirectory)-1]!='\\')
            _tcscat(psz,_T("\\"));
        _tcscat(psz,DllName);

        if (CDllFinder::DoesFileExists(psz))
        {
            _tcscpy(tFullPath,psz);
            return TRUE;
        }
    }

    // check if file exists in Windows directory
    *pszDirectory=0;
    GetWindowsDirectory(pszDirectory,MAX_PATH);
    _tcscpy(psz,pszDirectory);
    _tcscat(psz,DllName);
    if (CDllFinder::DoesFileExists(psz))
    {
        _tcscpy(tFullPath,psz);
        return TRUE;
    }

    // check environment path var
    TCHAR* pszEnvPath;
    DWORD size=1024;
    DWORD dwRet;
    pszEnvPath=new TCHAR[size];
    dwRet=GetEnvironmentVariable(_T("Path"),pszEnvPath,size);
    if (dwRet!=0)
    {
        // if buffer is not large enough
        if (dwRet>size)
        {
            // increase buffer size
            size=dwRet;
            delete pszEnvPath;
            pszEnvPath=new TCHAR[size];
            // query env path again
            GetEnvironmentVariable(_T("Path"),pszEnvPath,size);
        }

        // for each path in pszEnvPath
        TCHAR* pszPointer;
        TCHAR* pszPointerDir;
        pszPointerDir=pszEnvPath;

        while(pszPointerDir)
        {
            pszPointer=_tcschr(pszPointerDir,';');
            if (pszPointer)
            {
                *pszPointer=0;
                pszPointer++;
            }
            if (*pszPointerDir==0)
                break;

            _tcscpy(psz,pszPointerDir);
            if (pszPointerDir[_tcslen(pszPointerDir)-1]!='\\')
                _tcscat(psz,_T("\\"));
            _tcscat(psz,DllName);
            // check if file exists
            if (CDllFinder::DoesFileExists(psz))
            {
                _tcscpy(tFullPath,psz);
                delete pszEnvPath;
                return TRUE;
            }
            // point to the next dir
            pszPointerDir=pszPointer;
        }
    }
    delete pszEnvPath;

#if (!defined(TOOLS_NO_MESSAGEBOX))
    TCHAR pszTmp[2*MAX_PATH];
    _stprintf(pszTmp,_T("File %s can't be found.\r\nDo you want to search it manually ?"),DllName);
    if (MessageBox(NULL,pszTmp,_T("Warning"),MB_YESNO|MB_ICONWARNING|MB_TOPMOST)==IDYES)
    {
        *psz=0;

        // fill filter
        _stprintf(pszTmp,_T("%s\0%s\0"),DllName);
        // open dialog
        OPENFILENAME ofn;
        memset(&ofn,0,sizeof (OPENFILENAME));
        ofn.lStructSize=sizeof (OPENFILENAME);
        ofn.hwndOwner=NULL;
        ofn.hInstance=NULL;
        ofn.lpstrFilter=pszTmp;
        ofn.nFilterIndex = 1;
        ofn.Flags=OFN_EXPLORER|OFN_PATHMUSTEXIST|OFN_FILEMUSTEXIST;
        ofn.lpstrFile=psz;
        ofn.nMaxFile=MAX_PATH;
        ofn.lpstrTitle=_T("Select dll file");

        // get file name
        if (GetOpenFileName(&ofn))
        {
            _tcscpy(tFullPath,psz);
            return TRUE;
        }
    }
#endif
    return FALSE;
}
Example #24
0
BOOL NMEAParser::RMC(TCHAR *String, TCHAR **params, size_t nparams, NMEA_INFO *pGPS)
{
  TCHAR *Stop;
  static bool logbaddate=true;
  double speed=0;

  gpsValid = !NAVWarn(params[1][0]);

  GPSCONNECT = TRUE;    
  RMCAvailable=true; // 100409

  #ifdef PNA
  if (DeviceIsGM130) {

	double ps = GM130BarPressure();
	RMZAltitude = (1 - pow(fabs(ps / QNH),  0.190284)) * 44307.69;
	// StartupStore(_T("....... Pressure=%.0f QNH=%.2f Altitude=%.1f\n"),ps,QNH,RMZAltitude);

	RMZAvailable = TRUE;

	UpdateBaroSource(pGPS, BARO__GM130, NULL,   RMZAltitude);
  }
  if (DeviceIsRoyaltek3200) {
	if (Royaltek3200_ReadBarData()) {
		double ps = Royaltek3200_GetPressure();
		RMZAltitude = (1 - pow(fabs(ps / QNH),  0.190284)) * 44307.69;

		#if 0
		pGPS->TemperatureAvailable=true;
		pGPS->OutsideAirTemperature = Royaltek3200_GetTemperature();
		#endif
	}

	RMZAvailable = TRUE;

	UpdateBaroSource(pGPS, BARO__ROYALTEK3200,  NULL,  RMZAltitude);

  }
  #endif // PNA

  if (!activeGPS) {
	// Before ignoring anything else, commit RMZ altitude otherwise it will be ignored!
	if(RMZAvailable) {
		UpdateBaroSource(pGPS, isFlarm? BARO__RMZ_FLARM:BARO__RMZ, NULL, RMZAltitude);
	}
	return TRUE;
  }

  // if no valid fix, we dont get speed either!
  if (gpsValid)
  {
	// speed is in knots, 2 = 3.7kmh
	speed = StrToDouble(params[6], NULL);
  }
  
  pGPS->NAVWarning = !gpsValid;

  // say we are updated every time we get this,
  // so infoboxes get refreshed if GPS connected
  // the RMC sentence marks the start of a new fix, so we force the old data to be saved for calculations
        // note that Condor sends no date..
        if ((_tcslen(params[8]) <6) && !DevIsCondor) {
		#if TESTBENCH
		StartupStore(_T(".... RMC date field empty, skip sentence!\n"));
		#endif
		return TRUE;
	}

	// Even with no valid position, we let RMC set the time and date if valid
	long gy, gm, gd;
	gy = _tcstol(&params[8][4], &Stop, 10) + 2000;   
	params[8][4] = '\0';
	gm = _tcstol(&params[8][2], &Stop, 10); 
	params[8][2] = '\0';
	gd = _tcstol(&params[8][0], &Stop, 10); 

	// SeeYou PC is sending NMEA sentences with RMC date 2072-02-27
	if ( ((gy > 1980) && (gy <2100) ) && (gm != 0) && (gd != 0) ) { 
		pGPS->Year = gy;
		pGPS->Month = gm;
		pGPS->Day = gd;

force_advance:
		RMCtime = StrToDouble(params[0],NULL);
#ifndef OLD_TIME_MODIFY
		double ThisTime = TimeModify(params[0], pGPS, StartDay);
#else
		double ThisTime = TimeModify(RMCtime, pGPS);
#endif
		// RMC time has priority on GGA and GLL etc. so if we have it we use it at once
		if (!TimeHasAdvanced(ThisTime, pGPS)) {
			#if DEBUGSEQ
			StartupStore(_T("..... RMC time not advanced, skipping \n")); // 31C
			#endif
			return FALSE;
		}
			
	}  else {
		if (DevIsCondor) {
			#if DEBUGSEQ
			StartupStore(_T(".. Condor not sending valid date, using 1.1.2012%s"),NEWLINE);
			#endif
			gy=2012; gm=1; gd=1;
			goto force_advance;
		}

		if (gpsValid && logbaddate) { // 091115
			StartupStore(_T("------ NMEAParser:RMC Receiving an invalid or null DATE from GPS%s"),NEWLINE);
			StartupStore(_T("------ NMEAParser: Date received is y=%ld m=%ld d=%ld%s"),gy,gm,gd,NEWLINE); // 100422
			StartupStore(_T("------ This message will NOT be repeated. %s%s"),WhatTimeIsIt(),NEWLINE);
			DoStatusMessage(MsgToken(875));
			logbaddate=false;
		}
		gy=2012; gm=2; gd=30;	// an impossible date!
		goto force_advance;
		 
	}

  if (gpsValid) { 
	double tmplat;
	double tmplon;

	tmplat = MixedFormatToDegrees(StrToDouble(params[2], NULL));
	tmplat = NorthOrSouth(tmplat, params[3][0]);
	  
	tmplon = MixedFormatToDegrees(StrToDouble(params[4], NULL));
	tmplon = EastOrWest(tmplon,params[5][0]);
  
	if (!((tmplat == 0.0) && (tmplon == 0.0))) {
		pGPS->Latitude = tmplat;
		pGPS->Longitude = tmplon;
	}
  
	pGPS->Speed = KNOTSTOMETRESSECONDS * speed;
  
	if (pGPS->Speed>trackbearingminspeed) {
		pGPS->TrackBearing = AngleLimit360(StrToDouble(params[7], NULL));
	}
  } // gpsvalid 091108

#ifdef WIN32
  // As soon as we get a fix for the first time, set the
  // system clock to the GPS time.
  static bool sysTimeInitialised = false;
  
  if (!pGPS->NAVWarning && (gpsValid)) {
	if (SetSystemTimeFromGPS) {
		if (!sysTimeInitialised) {
			if ( ( pGPS->Year > 1980 && pGPS->Year<2100) && ( pGPS->Month > 0) && ( pGPS->Hour > 0)) {
        
				sysTimeInitialised =true; // Attempting only once
				SYSTEMTIME sysTime;
				// ::GetSystemTime(&sysTime);
				int hours = (int)pGPS->Hour;
				int mins = (int)pGPS->Minute;
				int secs = (int)pGPS->Second;
				sysTime.wYear = (unsigned short)pGPS->Year;
				sysTime.wMonth = (unsigned short)pGPS->Month;
				sysTime.wDay = (unsigned short)pGPS->Day;
				sysTime.wHour = (unsigned short)hours;
				sysTime.wMinute = (unsigned short)mins;
				sysTime.wSecond = (unsigned short)secs;
				sysTime.wMilliseconds = 0;
				::SetSystemTime(&sysTime);
			}
		}
	}
  }
#else
#warning "Set system clock to the GPS time not implemented."
#endif

  if(RMZAvailable) {
	UpdateBaroSource(pGPS, BARO__RMZ, NULL,  RMZAltitude);
  }
  if (!GGAAvailable) {
	// update SatInUse, some GPS receiver dont emmit GGA sentance
	if (!gpsValid) { 
		pGPS->SatellitesUsed = 0;
	} else {
		pGPS->SatellitesUsed = -1;
	}
  }
  
  if ( !GGAAvailable || (GGAtime == RMCtime)  )  {
	#if DEBUGSEQ
	StartupStore(_T("... RMC trigger gps, GGAtime==RMCtime\n")); // 31C
	#endif
	TriggerGPSUpdate(); 
  }

  return TRUE;

} // END RMC
Example #25
0
BOOL CTrayNotifyIcon::Create(CWnd* pNotifyWnd, UINT uID, LPCTSTR pszTooltipText, LPCTSTR pszBalloonText, LPCTSTR pszBalloonCaption, UINT nTimeout, BalloonStyle style, HICON hIcon, UINT nNotifyMessage, UINT uMenuID)
{
  //Validate our parameters
  ASSERT(pNotifyWnd && ::IsWindow(pNotifyWnd->GetSafeHwnd()));
  ASSERT(_tcslen(pszTooltipText) < 128);
  ASSERT(_tcslen(pszBalloonText) < 256);
  ASSERT(_tcslen(pszBalloonCaption) < 64);
  ASSERT(hIcon); 
  ASSERT(nNotifyMessage >= WM_USER); //Make sure we avoid conflict with other messages

  //Load up the menu resource which is to be used as the context menu
  if (!m_Menu.LoadMenu(uMenuID == 0 ? uID : uMenuID))
  {
    ASSERT(FALSE);
    return FALSE;
  }
  CMenu* pSubMenu = m_Menu.GetSubMenu(0);
  if (!pSubMenu) 
  {
    ASSERT(FALSE); //Your menu resource has been designed incorrectly
    return FALSE;
  }
  // Make first menu item the default (bold font)
  ::SetMenuDefaultItem(pSubMenu->m_hMenu, 0, TRUE);

  //Install the hook
  m_HookWnd.Init(this, pNotifyWnd);

  //Call the Shell_NotifyIcon function
  m_pNotificationWnd = pNotifyWnd;
  m_NotifyIconData.cbSize = sizeof(NOTIFYICONDATA_2);
  m_NotifyIconData.hWnd = pNotifyWnd->GetSafeHwnd();
  m_NotifyIconData.uID = uID;
  m_NotifyIconData.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP | NIF_INFO;
  m_NotifyIconData.uCallbackMessage = nNotifyMessage;
  m_NotifyIconData.hIcon = hIcon;
  _tcscpy(m_NotifyIconData.szTip, pszTooltipText);
  _tcscpy(m_NotifyIconData.szInfo, pszBalloonText);
  _tcscpy(m_NotifyIconData.szInfoTitle, pszBalloonCaption);
  m_NotifyIconData.uTimeout = nTimeout;
  switch (style)
  {
    case Warning:
    {
      m_NotifyIconData.dwInfoFlags = NIIF_WARNING;
      break;
    }
    case Error:
    {
      m_NotifyIconData.dwInfoFlags = NIIF_ERROR;
      break;
    }
    case Info:
    {
      m_NotifyIconData.dwInfoFlags = NIIF_INFO;
      break;
    }
    default:
    {
      ASSERT(FALSE);
      break;
    }
  }

  m_bCreated = Shell_NotifyIcon(NIM_ADD, (PNOTIFYICONDATA) &m_NotifyIconData);
  return m_bCreated;
}
Example #26
0
BOOL NMEAParser::GGA(TCHAR *String, TCHAR **params, size_t nparams, NMEA_INFO *pGPS)
{

  GGAAvailable = TRUE;
  GPSCONNECT = TRUE;     // 091208

  // this will force gps invalid but will NOT assume gps valid!
  nSatellites = (int)(min(16.0, StrToDouble(params[6], NULL)));
  if (nSatellites==0) {
	gpsValid = false;
  }

    /*
     * Fix quality : 
     *  0 = invalid
     *  1 = GPS fix (SPS)
     *  2 = DGPS fix
     *  3 = PPS fix
     *  4 = Real Time Kinematic
     *  5 = Float RTK
     *  6 = estimated (dead reckoning) (2.3 feature)
     *  7 = Manual input mode
     *  8 = Simulation mode
     */
  
  double ggafix = StrToDouble(params[5],NULL);
  if ( ggafix==0 || ggafix>5 ) {
	#ifdef DEBUG_GPS
	if (ggafix>5) StartupStore(_T("------ GGA DEAD RECKON fix skipped%s"),NEWLINE);
	#endif
#ifndef NDEBUG
    // in debug we need accept manual or simulated fix
    gpsValid = (ggafix == 7 || ggafix == 8); 
#else
	gpsValid=false;
#endif    
  } else {
	gpsValid=true;
  }

  if (!activeGPS) {
	if(RMZAvailable && !RMCAvailable)
	{
		UpdateBaroSource(pGPS, isFlarm? BARO__RMZ_FLARM:BARO__RMZ, NULL, RMZAltitude);
	}
	return TRUE;
  }

  pGPS->SatellitesUsed = nSatellites; // 091208
  pGPS->NAVWarning = !gpsValid; // 091208

  GGAtime=StrToDouble(params[0],NULL);
  // Even with invalid fix, we might still have valid time
  // I assume that 0 is invalid, and I am very sorry for UTC time 00:00 ( missing a second a midnight).
  // is better than risking using 0 as valid, since many gps do not respect any real nmea standard
  //
  // Update 121215: do not update time with GGA if RMC is found, because at 00UTC only RMC will set the date change!
  // Remember that we trigger update of calculations when we get GGA.
  // So what happens if the gps sequence is GGA and then RMC?
  //    2359UTC:
  //           GGA , old date, trigger gps calc
  //           RMC,  old date
  //    0000UTC:
  //           GGA, old date even if new date will come for the same quantum,
  //                GGAtime>0, see (*)
  //                BANG! oldtime from RMC is 2359, new time from GGA is 0, time is in the past!
  //
  // If the gps is sending first RMC, this problem does not appear of course.
  //
  // (*) IMPORTANT> GGAtime at 00UTC will most likely be >0! Because time is in hhmmss.ss  .ss is always >0!!
  // We check GGAtime, RMCtime, GLLtime etc. for 0 because in case of error the gps will send 000000.000 !!
  //
  if ( (!RMCAvailable && (GGAtime>0)) || ((GGAtime>0) && (GGAtime == RMCtime))  ) {  // RMC already came in same time slot

	#if DEBUGSEQ
	StartupStore(_T("... GGA update time = %f RMCtime=%f\n"),GGAtime,RMCtime); // 31C
	#endif
#ifndef OLD_TIME_MODIFY
	double ThisTime = TimeModify(params[0], pGPS, StartDay);
#else
	double ThisTime = TimeModify(GGAtime, pGPS);
#endif
	if (!TimeHasAdvanced(ThisTime, pGPS)) {
		#if DEBUGSEQ
		StartupStore(_T(".... GGA time not advanced, skip\n")); // 31C
		#endif
		return FALSE;
	}
  }
  if (gpsValid) {
	double tmplat;
	double tmplon;
	tmplat = MixedFormatToDegrees(StrToDouble(params[1], NULL));
	tmplat = NorthOrSouth(tmplat, params[2][0]);
	tmplon = MixedFormatToDegrees(StrToDouble(params[3], NULL));
	tmplon = EastOrWest(tmplon,params[4][0]);
	if (!((tmplat == 0.0) && (tmplon == 0.0))) {
		pGPS->Latitude = tmplat;
		pGPS->Longitude = tmplon;
	} 
	else {
		#ifdef DEBUG_GPS
		StartupStore(_T("++++++ GGA gpsValid with invalid posfix!%s"),NEWLINE);
		#endif
		gpsValid=false;
	}
  }

  // GGA is marking now triggering end of data, so OK to use baro
  // Even with invalid fix we might have valid baro data of course

  // any NMEA sentence with time can now trigger gps update: the first to detect new time will make trigger.
  // we assume also that any sentence with no time belongs to current time.
  // note that if no time from gps, no use of vario and baro data, but also no fix available.. so no problems

  if(RMZAvailable)
  {
	UpdateBaroSource(pGPS, isFlarm? BARO__RMZ_FLARM:BARO__RMZ, NULL, RMZAltitude);
  }

  // If  no gps fix, at this point we trigger refresh and quit
  if (!gpsValid) { 
	#if DEBUGSEQ
	StartupStore(_T("........ GGA no gps valid, triggerGPS!\n")); // 31C
	#endif
	TriggerGPSUpdate(); 
	return FALSE;
  }

  // "Altitude" should always be GPS Altitude.
  pGPS->Altitude = ParseAltitude(params[8], params[9]);
  pGPS->Altitude += (GPSAltitudeOffset/1000); // BUGFIX 100429
 
  if (_tcslen(params[10])>0) {
    // No real need to parse this value,
    // but we do assume that no correction is required in this case
//    double GeoidSeparation = ParseAltitude(params[10], params[11]);
  } else {
	if (UseGeoidSeparation) {
            double GeoidSeparation = LookupGeoidSeparation(pGPS->Latitude, pGPS->Longitude);
            pGPS->Altitude -= GeoidSeparation;
	}
  }

  // if RMC would be Triggering update, we loose the relative altitude, which is coming AFTER rmc! 
  // This was causing old altitude recorded in new pos fix.
  // 120428:
  // GGA will trigger gps if there is no RMC,  
  // or if GGAtime is the same as RMCtime, which means that RMC already came and we are last in the sequence
  if ( !RMCAvailable || (GGAtime == RMCtime)  )  {
	#if DEBUGSEQ
	StartupStore(_T("... GGA trigger gps, GGAtime==RMCtime\n")); // 31C
	#endif
	TriggerGPSUpdate(); 
  }
  return TRUE;

} // END GGA
DWORD CShaderEffectLoader::OnLoadFile(DWORD size, void *params)
{
	VERIFY_MESSAGE_SIZE(size, sizeof(TCHAR *));
	TCHAR *pFileName = (TCHAR *)params;

	if( _tcslen( pFileName ) == 0 )
	{
		m_ToolBox->Log( LOGWARNING, _T("Shader File is empty string") );
		return MSG_ERROR;
	}

	StdString szFileName(pFileName);
	szFileName.MakeSafeFileName();
	CHashString effectname( szFileName );

	// only load an effect file once
	static DWORD msgHash_FindObject = CHashString(_T("FindObject")).GetUniqueID();
	FINDOBJECTPARAMS param;
	param.hszName = &effectname;
	m_ToolBox->SendMessage(msgHash_FindObject, sizeof(FINDOBJECTPARAMS), &param );
	if ( param.bFound == true )
	{
		// effect already loaded
		return MSG_HANDLED_STOP;
	}

	IArchive *MemArchive;
	// hash the file name
	CHashString streamType(_T("File"));
	// create a new archive and load the file
	CREATEARCHIVE ca;
	DWORD retVal;
	ca.streamData = pFileName;
	ca.mode = STREAM_MODE_READ;
	ca.streamType = &streamType;
	// call the Archive factory to create an XML archive
	static DWORD msgHash_CreateXMLArchive = CHashString(_T("CreateXMLArchive")).GetUniqueID();
	if (retVal = m_ToolBox->SendMessage(msgHash_CreateXMLArchive, sizeof(CREATEARCHIVE), &ca) != MSG_HANDLED)
	{
		m_ToolBox->Log( LOGWARNING, _T("SHADEREFFECTLOADER: %s\n\tCould not create XML Archive\n"), pFileName );
		return MSG_ERROR;
	}

	MemArchive = dynamic_cast<IXMLArchive *>(ca.archive);

	///create the cal model
	CREATEOBJECTPARAMS cop;
	INITOBJECTPARAMS iop;
	SERIALIZEOBJECTPARAMS sop;
	
	CHashString hszParentName( _T("World") );
	CHashString hszTypeName(_T("CEffect"));	

	cop.parentName = &hszParentName;
	cop.typeName = &hszTypeName;
	cop.name = &effectname;
	static DWORD msgHash_CreateObject = CHashString(_T("CreateObject")).GetUniqueID();
	DWORD retval = m_ToolBox->SendMessage(msgHash_CreateObject, sizeof(CREATEOBJECTPARAMS), &cop, NULL, NULL);

	sop.name = &effectname;
	sop.archive = MemArchive;
	static DWORD msgHash_SerializeObject = CHashString(_T("SerializeObject")).GetUniqueID();
	m_ToolBox->SendMessage(msgHash_SerializeObject, sizeof(SERIALIZEOBJECTPARAMS), &sop, NULL, NULL);
	

	iop.name = &effectname;
	if( retval == MSG_HANDLED )
	{
		static DWORD msgHash_InitObject = CHashString(_T("InitObject")).GetUniqueID();
		retval = m_ToolBox->SendMessage(msgHash_InitObject, sizeof(INITOBJECTPARAMS), &iop, NULL, NULL);
	}

	MemArchive->Close();

	CREATEEFFECTINTERFACE addmsg;
	addmsg.m_Name = &effectname;
	static DWORD msgHash_AddEffect = CHashString(_T("AddEffect")).GetUniqueID();
	m_ToolBox->SendMessage(msgHash_AddEffect, sizeof( CREATEEFFECTINTERFACE ), &addmsg );
	return MSG_HANDLED_STOP;
}
Example #28
0
bool ParseOZIWayPointString(TCHAR *String,WAYPOINT *Temp) {

    Temp->Visible = true; // default all waypoints visible at start
    Temp->FarVisible = true;
    Temp->Format = LKW_OZI;
    Temp->Number = NumberOfWayPoints;
    Temp->FileNum = globalFileNum;
    Temp->Flags = TURNPOINT;

    memset(Temp->Name, 0, sizeof(Temp->Name)); // clear Name

    TCHAR TempString[READLINE_LENGTH];
    memset(TempString, 0, sizeof(TempString)); // clear TempString

    _tcscpy(TempString, String);

    // strtok_r skip empty field, It's not compatible with OziExplorer Waypoint File Version 1.1
    // use strsep_r instead of ( cf. Utils.h )

    TCHAR *pToken = NULL;
    TCHAR *Stop= NULL;

    TCHAR *pWClast = TempString;


    //	Field 1 : Number - this is the location in the array (max 1000), must be unique, usually start at 1 and increment. Can be set to -1 (minus 1) and the number will be auto generated.
    if ((pToken = strsep_r(TempString, TEXT(","), &pWClast)) == NULL)
        return false;

    //	Field 2 : Name - the waypoint name, use the correct length name to suit the GPS type.
    if ((pToken = strsep_r(NULL, TEXT(","), &pWClast)) == NULL)
        return false;

    // guard against overrun
    if (_tcslen(pToken)>NAME_SIZE) {
        pToken[NAME_SIZE-1]= _T('\0');
    }

    // remove trailing spaces
    for (int i=_tcslen(pToken)-1; i>1; i--) if (pToken[i]==' ') pToken[i]=0;
        else break;

    _tcscpy(Temp->Name, pToken);

    //	Field 3 : Latitude - decimal degrees.
    if ((pToken = strsep_r(NULL, TEXT(","), &pWClast)) == NULL)
        return false;

    Temp->Latitude = (double)StrToDouble(pToken, &Stop);

    if((Temp->Latitude > 90) || (Temp->Latitude < -90)) {
        return false;
    }

    //	Field 4 : Longitude - decimal degrees.
    if ((pToken = strsep_r(NULL, TEXT(","), &pWClast)) == NULL)
        return false;

    Temp->Longitude  = (double)StrToDouble(pToken, &Stop);
    if((Temp->Longitude  > 180) || (Temp->Longitude  < -180)) {
        return false;
    }
    //	Field 5 : Date - see Date Format below, if blank a preset date will be used
    if ((pToken = strsep_r(NULL, TEXT(","), &pWClast)) == NULL)
        return false;

    //	Field 6 : Symbol - 0 to number of symbols in GPS
    if ((pToken = strsep_r(NULL, TEXT(","), &pWClast)) == NULL)
        return false;

    //	Field 7 : Status - always set to 1
    if ((pToken = strsep_r(NULL, TEXT(","), &pWClast)) == NULL)
        return false;

    //	Field 8 : Map Display Format
    if ((pToken = strsep_r(NULL, TEXT(","), &pWClast)) == NULL)
        return false;

    //	Field 9 : Foreground Color (RGB value)
    if ((pToken = strsep_r(NULL, TEXT(","), &pWClast)) == NULL)
        return false;

    //	Field 10 : Background Color (RGB value)
    if ((pToken = strsep_r(NULL, TEXT(","), &pWClast)) == NULL)
        return false;

    //	Field 11 : Description (max 40), no commas
    if ((pToken = strsep_r(NULL, TEXT(","), &pWClast)) == NULL)
        return false;

    if (_tcslen(pToken) >0 ) {
        // remove trailing spaces
        for (int i=_tcslen(pToken)-1; i>1; i--) if (pToken[i]==' ') pToken[i]=0;
            else break;

        if (Temp->Comment) {
            free(Temp->Comment);
        }
        Temp->Comment = (TCHAR*)malloc((_tcslen(pToken)+1)*sizeof(TCHAR));
        if (Temp->Comment) _tcscpy(Temp->Comment, pToken);
    }
    else {
        Temp->Comment = NULL; // useless
    }

    //	Field 12 : Pointer Direction
    if ((pToken = strsep_r(NULL, TEXT(","), &pWClast)) == NULL)
        return false;

    //	Field 13 : Garmin Display Format
    if ((pToken = strsep_r(NULL, TEXT(","), &pWClast)) == NULL)
        return false;

    //	Field 14 : Proximity Distance - 0 is off any other number is valid
    if ((pToken = strsep_r(NULL, TEXT(","), &pWClast)) == NULL)
        return false;

    //	Field 15 : Altitude - in feet (-777 if not valid)
    if ((pToken = strsep_r(NULL, TEXT(","), &pWClast)) == NULL)
        return false;

    Temp->Altitude = (double)StrToDouble(pToken, &Stop)/TOFEET;
    if(Temp->Altitude <= 0) {
        WaypointAltitudeFromTerrain(Temp);
    }

    //	Field 16 : Font Size - in points
    //	Field 17 : Font Style - 0 is normal, 1 is bold.
    //	Field 18 : Symbol Size - 17 is normal size
    //	Field 19 : Proximity Symbol Position
    //	Field 20 : Proximity Time
    //	Field 21 : Proximity or Route or Both
    //	Field 22 : File Attachment Name
    //	Field 23 : Proximity File Attachment Name
    //	Field 24 : Proximity Symbol Name

    return true;
}
Example #29
0
	LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
	{
		int wmId, wmEvent;
		std::string fn;

		switch (message) 
		{
		case WM_CREATE:
			PostMessage(hWnd, WM_COMMAND, ID_FILE_LOAD, 0);
			break;

		case WM_MOVE:
			break;

		case WM_COMMAND:
			wmId    = LOWORD(wParam); 
			wmEvent = HIWORD(wParam); 
			// Parse the menu selections:
			switch (wmId)
			{
			//File menu

			case ID_FILE_LOAD:
				BrowseAndBoot();
				break;

			case ID_FILE_REFRESHGAMELIST:
				break;

			//Emulation menu

			case ID_EMULATION_RUN:
				if (g_State.bEmuThreadStarted)
				{
					for (int i=0; i<numCPUs; i++)
						if (disasmWindow[i])
							SendMessage(disasmWindow[i]->GetDlgHandle(), WM_COMMAND, IDC_STOP, 0);
					for (int i=0; i<numCPUs; i++)
						if (disasmWindow[i])
							SendMessage(disasmWindow[i]->GetDlgHandle(), WM_COMMAND, IDC_GO, 0);
				}
				break;

			case ID_EMULATION_STOP:
				for (int i=0; i<numCPUs; i++)
					if (disasmWindow[i])
						SendMessage(disasmWindow[i]->GetDlgHandle(), WM_COMMAND, IDC_STOP, 0);

				Sleep(100);//UGLY wait for event instead

				for (int i=0; i<numCPUs; i++)
					if (disasmWindow[i])
						SendMessage(disasmWindow[i]->GetDlgHandle(), WM_CLOSE, 0, 0);
				for (int i=0; i<numCPUs; i++)
					if (memoryWindow[i])
						SendMessage(memoryWindow[i]->GetDlgHandle(), WM_CLOSE, 0, 0);

				EmuThread_Stop();
				SetPlaying(0);
				Update();
				UpdateMenus();
				break;


			case ID_EMULATION_PAUSE:
				for (int i=0; i<numCPUs; i++)
					if (disasmWindow[i])
						SendMessage(disasmWindow[i]->GetDlgHandle(), WM_COMMAND, IDC_STOP, 0);
				break;

			case ID_EMULATION_SPEEDLIMIT:
				g_Config.bSpeedLimit = !g_Config.bSpeedLimit;
				UpdateMenus();
				break;

			case ID_FILE_LOADSTATE:
				if (W32Util::BrowseForFileName(true, hWnd, "Load state",0,"Save States (*.gcs)\0*.gcs\0All files\0*.*\0\0","gcs",fn))
				{
					SetCursor(LoadCursor(0,IDC_WAIT));
					SetCursor(LoadCursor(0,IDC_ARROW));
				}
				break;

			case ID_FILE_SAVESTATE:
				if (W32Util::BrowseForFileName(false, hWnd, "Save state",0,"Save States (*.gcs)\0*.gcs\0All files\0*.*\0\0","gcs",fn))
				{
					SetCursor(LoadCursor(0,IDC_WAIT));
					SetCursor(LoadCursor(0,IDC_ARROW));
				}
				break;

			case ID_OPTIONS_SCREEN1X:
				SetZoom(1);
				UpdateMenus();
				break;
			case ID_OPTIONS_SCREEN2X:
				SetZoom(2);
				UpdateMenus();
				break;
			case ID_OPTIONS_SCREEN3X:
				SetZoom(3);
				UpdateMenus();
				break;
			case ID_OPTIONS_SCREEN4X:
				SetZoom(4);
				UpdateMenus();
				break;

			case ID_OPTIONS_BUFFEREDRENDERING:
				g_Config.bBufferedRendering = !g_Config.bBufferedRendering;
				UpdateMenus();
				break;

			case ID_FILE_EXIT:
				DestroyWindow(hWnd);
				break;

			//////////////////////////////////////////////////////////////////////////
			//CPU menu
			//////////////////////////////////////////////////////////////////////////
			case ID_CPU_DYNAREC:
				g_Config.bJIT = true;
				UpdateMenus();
				break;			
			case ID_CPU_INTERPRETER:
				g_Config.bJIT = false;
				UpdateMenus();
				break;

			//case ID_CPU_RESET: 
			//	MessageBox(hwndMain,"Use the controls in the disasm window for now..","Sorry",0);
			//	Update();
			//	break;

			case ID_DEBUG_RUNPOWERPCTEST:
				//doppctest();
				break;
			//////////////////////////////////////////////////////////////////////////
			//Debug menu
			//////////////////////////////////////////////////////////////////////////
				/*
			case ID_DEBUG_LOCATESYMBOLS:
				{
					std::vector<std::string> files=  W32Util::BrowseForFileNameMultiSelect(true,hWnd,"MOJS",0,"BLAH\0*.*",0);
					std::vector<std::string>::iterator iter;
					if (files.size())
					{
						for (iter=files.begin(); iter!=files.end(); iter++)
						{
							LOG(MASTER_LOG,"Loading symbols from %s", iter->c_str());
							LoadSymbolsFromO((*iter).c_str(),0x02000000,1*1024*1024);
						}
						symbolMap.SortSymbols();
//						HLE_PatchFunctions();
					}
					
					for (int i=0; i<numCPUs; i++)
						if (disasmWindow[i])
							disasmWindow[i]->NotifyMapLoaded();
					for (int i=0; i<numCPUs; i++)
						if (memoryWindow[i])
							memoryWindow[i]->Update();
				}
				break;
*/

			case ID_DEBUG_LOADMAPFILE:
				if (W32Util::BrowseForFileName(true, hWnd, "Load .MAP",0,"Maps\0*.map\0All files\0*.*\0\0","map",fn))
				{
					symbolMap.LoadSymbolMap(fn.c_str());
//					HLE_PatchFunctions();
					for (int i=0; i<numCPUs; i++)
						if (disasmWindow[i])
							disasmWindow[i]->NotifyMapLoaded();
					for (int i=0; i<numCPUs; i++)
						if (memoryWindow[i])
							memoryWindow[i]->NotifyMapLoaded();
				}
				break;
			case ID_DEBUG_SAVEMAPFILE:
				if (W32Util::BrowseForFileName(false, hWnd, "Save .MAP",0,"Maps\0*.map\0All files\0*.*\0\0","map",fn))
					symbolMap.SaveSymbolMap(fn.c_str());
				break;
				/*
			case ID_DEBUG_COMPILESIGNATUREFILE:
				if (W32Util::BrowseForFileName(false, hWnd, "Save signature file",0,"Sigs\0*.sig\0All files\0*.*\0\0","sig",fn))
					symbolMap.CompileFuncSignaturesFile(fn.c_str());
				break;
			case ID_DEBUG_USESIGNATUREFILE:
				if (W32Util::BrowseForFileName(true, hWnd, "Use signature file",0,"Sigs\0*.sig\0All files\0*.*\0\0","sig",fn))
				{
					symbolMap.UseFuncSignaturesFile(fn.c_str(),0x80400000);
//					HLE_PatchFunctions();
					for (int i=0; i<numCPUs; i++)
						if (disasmWindow[i])
							disasmWindow[i]->NotifyMapLoaded();
				}
				break;*/

			case ID_DEBUG_RESETSYMBOLTABLE:
				symbolMap.ResetSymbolMap();
				for (int i=0; i<numCPUs; i++)
					if (disasmWindow[i])
						disasmWindow[i]->NotifyMapLoaded();
				for (int i=0; i<numCPUs; i++)
					if (memoryWindow[i])
						memoryWindow[i]->NotifyMapLoaded();
				break;
			case ID_DEBUG_DISASSEMBLY:
				if (disasmWindow[0])
					disasmWindow[0]->Show(true);
				break;
			case ID_DEBUG_MEMORYVIEW:
				if (memoryWindow[0])
					memoryWindow[0]->Show(true);
				break;
			case ID_DEBUG_LOG:
        LogManager::GetInstance()->GetConsoleListener()->Show(LogManager::GetInstance()->GetConsoleListener()->Hidden());
				break;

			//////////////////////////////////////////////////////////////////////////
			//Options menu
			//////////////////////////////////////////////////////////////////////////
			case ID_OPTIONS_IGNOREILLEGALREADS:
				g_Config.bIgnoreBadMemAccess = !g_Config.bIgnoreBadMemAccess;
				UpdateMenus();
				break;
				//case ID_OPTIONS_FULLSCREEN:
				//	break;

			case ID_OPTIONS_DISPLAYRAWFRAMEBUFFER:
				g_Config.bDisplayFramebuffer = !g_Config.bDisplayFramebuffer;
				UpdateMenus();
				break;

			
			//////////////////////////////////////////////////////////////////////////
			//Help menu
			//////////////////////////////////////////////////////////////////////////
	
      case ID_HELP_OPENWEBSITE:
				ShellExecute(NULL, "open", "http://www.ppsspp.org/", NULL, NULL, SW_SHOWNORMAL);
        break;

      case ID_HELP_ABOUT:
				DialogManager::EnableAll(FALSE);
				DialogBox(hInst, (LPCTSTR)IDD_ABOUTBOX, hWnd, (DLGPROC)About);
				DialogManager::EnableAll(TRUE);
				break;

			default:
				{
					MessageBox(hwndMain,"Unimplemented","Sorry",0);
				}
				break;
			}
			break;
		case WM_KEYDOWN:
			{
				static int mojs=0;
				mojs ^= 1;
				//SetSkinMode(mojs);
			}
			break;
		case WM_DROPFILES:
			{
				HDROP hdrop = (HDROP)wParam;
				int count = DragQueryFile(hdrop,0xFFFFFFFF,0,0);
				if (count != 1)
				{
					MessageBox(hwndMain,"You can only load one file at a time","Error",MB_ICONINFORMATION);
				}
				else
				{
					TCHAR filename[512];
					DragQueryFile(hdrop,0,filename,512);
					TCHAR *type = filename+_tcslen(filename)-3;
/*
					TBootFileType t;
					if (strcmp(type,"bin")==0)
						t=BOOT_BIN;
					else if (strcmp(type,"elf")==0)
						t=BOOT_ELF;
					else if (strcmp(type,"dol")==0)
						t=BOOT_DOL;
					else
					{
						MessageBox(hwndMain,"Not a runnable Gamecube file","Error",MB_ICONERROR);
						break;
					}
					CCore::Start(0,filename,t);
					*/

					if (g_State.bEmuThreadStarted)
					{
						SendMessage(hWnd, WM_COMMAND, ID_EMULATION_STOP, 0);
					}
					
					MainWindow::SetPlaying(filename);
					MainWindow::Update();
					MainWindow::UpdateMenus();

					EmuThread_Start(filename);
				}
			}
			break;

			//case WM_ERASEBKGND:
			//	return 0;
		case WM_CLOSE:
			Sleep(100);//UGLY wait for event instead
			EmuThread_Stop();

			/*
			if (g_Config.bConfirmOnQuit && CCore::IsRunning())
			{
				if (IDNO==MessageBox(hwndMain,"A game is in progress. Are you sure you want to exit?","Are you sure?",MB_YESNO|MB_ICONQUESTION))
					return 1;//or 1?
				else
					return DefWindowProc(hWnd,message,wParam,lParam);
				break;
			}
			else
			*/
				return DefWindowProc(hWnd,message,wParam,lParam);
//		case WM_LBUTTONDOWN:
//			TrackPopupMenu(menu,0,0,0,0,hWnd,0);
//			break;
		case WM_DESTROY:
			PostQuitMessage(0);
			break;
		case WM_SIZE:
			break;
		case WM_NCHITTEST:
			if (skinMode)
				return HTCAPTION;
			else
				return DefWindowProc(hWnd,message,wParam,lParam);

		case WM_USER+1:
			disasmWindow[0] = new CDisasm(MainWindow::GetHInstance(), MainWindow::GetHWND(), currentDebugMIPS);
			DialogManager::AddDlg(disasmWindow[0]);
			disasmWindow[0]->Show(TRUE);
			memoryWindow[0] = new CMemoryDlg(MainWindow::GetHInstance(), MainWindow::GetHWND(), currentDebugMIPS);
			DialogManager::AddDlg(memoryWindow[0]);
			if (disasmWindow[0])
				disasmWindow[0]->NotifyMapLoaded();
			if (memoryWindow[0])
				memoryWindow[0]->NotifyMapLoaded();
			break;

		default:
			return DefWindowProc(hWnd, message, wParam, lParam);
		}
		return 0;
	}
Example #30
0
/* This function is launched in a separate thread and waits for 
 * a message from a completion port associated with a job.
 */
DWORD WINAPI JobNotify(PVOID) 
{
   TCHAR sz[2000];
   BOOL fDone = FALSE;

   while (!fDone) 
   {
      DWORD dwBytesXferred;
      ULONG_PTR CompKey;
      LPOVERLAPPED po;
      
	  /* Attempts to dequeue an I/O completion packet 
	   * from the specified I/O completion port. 
	   * If there is no completion packet queued, the function 
	   * waits for a pending I/O operation associated with the completion port to complete.
	   *
       * To dequeue multiple I/O completion packets at once, 
	   * use the GetQueuedCompletionStatusEx function
	   *  
	   * CompletionPort [in] 
       *   A handle to the completion port. To create a completion port, 
	   *   use the CreateIoCompletionPort function.
	   *
	   * lpNumberOfBytes [out] 
       *   A pointer to a variable that receives the number of bytes 
	   *   transferred during an I/O operation that has completed
       *   
	   * lpCompletionKey [out] 
       *   A pointer to a variable that receives the completion key value 
	   *   associated with the file handle whose I/O operation has completed. 
	   *   A completion key is a per-file key that is specified in a call to CreateIoCompletionPort.
       *
	   * lpOverlapped [out]  
       *   A pointer to a variable that receives the address of the 
	   *   OVERLAPPED structure that was specified when the completed I/O operation was started. 
	   * 
	   * dwMilliseconds [in] 
       *   The number of milliseconds that the caller is willing to wait 
	   *   for a completion packet to appear at the completion port. 
	   *   If a completion packet does not appear within the specified time, 
	   *   the function times out, returns FALSE, and sets *lpOverlapped to NULL.
	   *
       *   If dwMilliseconds is INFINITE, the function will never time out. 
	   *   If dwMilliseconds is zero and there is no I/O operation to dequeue, 
	   *   the function will time out immediately.
       */
      GetQueuedCompletionStatus(
		  g_hIOCP, 
          &dwBytesXferred, 
		  &CompKey, 
		  &po, 
		  INFINITE);

      /* The app is shutting down, exit this thread */
      fDone = (CompKey == COMPKEY_TERMINATE);

      HWND hwndLB = FindWindow(NULL, TEXT("Job Lab"));
      hwndLB = GetDlgItem(hwndLB, IDC_STATUS);

      if (CompKey == COMPKEY_JOBOBJECT) 
	  {
         _tcscpy_s(sz, _countof(sz), TEXT("--> Notification: "));
         PTSTR psz = sz + _tcslen(sz);
         switch (dwBytesXferred) 
		 {
			 /* We have reached an event when job time was reached */
             case JOB_OBJECT_MSG_END_OF_JOB_TIME:
                  StringCchPrintf(
					    psz, 
						_countof(sz) - _tcslen(sz), 
                        TEXT("Job time limit reached"));
             break;
			 /* The time allowed for process in the job is exceeded.
			  * So we get process name from the overlapped structure.
			  */
             case JOB_OBJECT_MSG_END_OF_PROCESS_TIME: 
			 {
                  TCHAR szProcessName[MAX_PATH];
                  
				  /* po is a process identifier. */
                  GetProcessName(
					  PtrToUlong(po), 
					  szProcessName, 
					  MAX_PATH);

                  StringCchPrintf(
					  psz, 
					  _countof(sz) - _tcslen(sz), 
                      TEXT("Job process %s (Id=%d) time limit reached"), 
                      szProcessName, 
					  po);
             }
             break;

             case JOB_OBJECT_MSG_ACTIVE_PROCESS_LIMIT:
                  StringCchPrintf(
					  psz, 
					  _countof(sz) - _tcslen(sz), 
                      TEXT("Too many active processes in job"));
             break;

             case JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO:
                  StringCchPrintf(
					  psz, 
					  _countof(sz) - _tcslen(sz), 
                      TEXT("Job contains no active processes"));
             break;

             case JOB_OBJECT_MSG_NEW_PROCESS: 
			 {
                  TCHAR szProcessName[MAX_PATH];
                  GetProcessName(
					  PtrToUlong(po), 
					  szProcessName, 
					  MAX_PATH);

                  StringCchPrintf(
					  psz, 
					  _countof(sz) - _tcslen(sz), 
                      TEXT("New process %s (Id=%d) in Job"), 
					  szProcessName, 
					  po);
             }
             break;

             case JOB_OBJECT_MSG_EXIT_PROCESS: 
			 {
                  TCHAR szProcessName[MAX_PATH];
                  GetProcessName(
					 PtrToUlong(po), 
					 szProcessName, 
					 MAX_PATH);

                  StringCchPrintf(
					  psz, 
					  _countof(sz) - _tcslen(sz), 
                      TEXT("Process %s (Id=%d) terminated"), 
					  szProcessName, 
					  po);
             }
             break;

             case JOB_OBJECT_MSG_ABNORMAL_EXIT_PROCESS: 
			 {
                 TCHAR szProcessName[MAX_PATH];
                 GetProcessName(
					 PtrToUlong(po), 
					 szProcessName, 
					 MAX_PATH);

                 StringCchPrintf(
					 psz, 
					 _countof(sz) - _tcslen(sz), 
                     TEXT("Process %s (Id=%d) terminated abnormally"), 
                     szProcessName, 
					 po);
             }
             break;

             case JOB_OBJECT_MSG_PROCESS_MEMORY_LIMIT: 
		     {
                 TCHAR szProcessName[MAX_PATH];
                 GetProcessName(
					 PtrToUlong(po), 
					 szProcessName, 
					 MAX_PATH);

                 StringCchPrintf(
					 psz, 
					 _countof(sz) - _tcslen(sz), 
                     TEXT("Process (%s Id=%d) exceeded memory limit"), 
                     szProcessName, 
					 po);
             }
             break;

             case JOB_OBJECT_MSG_JOB_MEMORY_LIMIT: 
			 {
                 TCHAR szProcessName[MAX_PATH];
                 GetProcessName(
					 PtrToUlong(po), 
					 szProcessName, 
					 MAX_PATH);

                 StringCchPrintf(
					 psz, 
					 _countof(sz) - _tcslen(sz),
                     TEXT("Process %s (Id=%d) exceeded job memory limit"), 
                     szProcessName, 
					 po);
             }
             break;

             default:
                 StringCchPrintf(
					 psz, 
					 _countof(sz) - _tcslen(sz),
                     TEXT("Unknown notification: %d"), 
					 dwBytesXferred);
             break;
         }
         ListBox_SetCurSel(hwndLB, ListBox_AddString(hwndLB, sz));
         /* Force a status update when a notification arrives */
         CompKey = 1; 
      }

      if (CompKey == COMPKEY_STATUS) 
	  {
         static int s_nStatusCount = 0;

         StringCchPrintf(
			 sz, 
			 _countof(sz), 
             TEXT("--> Status Update (%u)"), 
			 s_nStatusCount++);

         ListBox_SetCurSel(hwndLB, ListBox_AddString(hwndLB, sz));

         /* Show the basic accounting information */
         JOBOBJECT_BASIC_AND_IO_ACCOUNTING_INFORMATION jobai;

         g_job.QueryBasicAccountingInfo(&jobai);

         StringCchPrintf(
			 sz, 
			 _countof(sz), 
             TEXT("Total Time: User=%I64u, Kernel=%I64u        ")
             TEXT("Period Time: User=%I64u, Kernel=%I64u"), 
             jobai.BasicInfo.TotalUserTime.QuadPart, 
             jobai.BasicInfo.TotalKernelTime.QuadPart,
             jobai.BasicInfo.ThisPeriodTotalUserTime.QuadPart, 
             jobai.BasicInfo.ThisPeriodTotalKernelTime.QuadPart);

         ListBox_SetCurSel(hwndLB, ListBox_AddString(hwndLB, sz));

         StringCchPrintf(
			 sz, 
			 _countof(sz), 
             TEXT("Page Faults=%u, Total Processes=%u, ")
             TEXT("Active Processes=%u, Terminated Processes=%u"), 
             jobai.BasicInfo.TotalPageFaultCount, 
             jobai.BasicInfo.TotalProcesses, 
             jobai.BasicInfo.ActiveProcesses, 
             jobai.BasicInfo.TotalTerminatedProcesses);

         ListBox_SetCurSel(hwndLB, ListBox_AddString(hwndLB, sz));

         /* Show the I/O accounting information */
         StringCchPrintf(
			 sz, 
			 _countof(sz), 
             TEXT("Reads=%I64u (%I64u bytes), ")
             TEXT("Write=%I64u (%I64u bytes), Other=%I64u (%I64u bytes)"), 
             jobai.IoInfo.ReadOperationCount,  
			 jobai.IoInfo.ReadTransferCount, 
             jobai.IoInfo.WriteOperationCount, 
			 jobai.IoInfo.WriteTransferCount, 
             jobai.IoInfo.OtherOperationCount, 
			 jobai.IoInfo.OtherTransferCount);

         ListBox_SetCurSel(hwndLB, ListBox_AddString(hwndLB, sz));

         /* Show the peak per-process and job memory usage */
         JOBOBJECT_EXTENDED_LIMIT_INFORMATION joeli;
         g_job.QueryExtendedLimitInfo(&joeli);

         StringCchPrintf(
			 sz, 
			 _countof(sz), 
             TEXT("Peak memory used: Process=%I64u, Job=%I64u"), 
             (__int64)joeli.PeakProcessMemoryUsed, 
             (__int64)joeli.PeakJobMemoryUsed);
         ListBox_SetCurSel(hwndLB, ListBox_AddString(hwndLB, sz));

         /* Show the set of Process IDs */
         DWORD dwNumProcesses = 50;
         DWORD dwProcessIdList[50];

         g_job.QueryBasicProcessIdList(
			 dwNumProcesses, 
             dwProcessIdList, 
			 &dwNumProcesses);

         StringCchPrintf(
			 sz, 
			 _countof(sz), 
			 TEXT("PIDs: %s"), 
             (dwNumProcesses == 0) ? TEXT("(none)") : TEXT(""));

         ListBox_SetCurSel(hwndLB, ListBox_AddString(hwndLB, sz));

         TCHAR szProcessName[MAX_PATH];

         for (DWORD x = 0; x < dwNumProcesses; x++) 
		 {
            GetProcessName(
				dwProcessIdList[x], 
                szProcessName, 
				_countof(szProcessName));

            StringCchPrintf(
				sz, 
				_countof(sz), 
				TEXT("   %d - %s"), 
                dwProcessIdList[x], 
				szProcessName);

            ListBox_SetCurSel(hwndLB, ListBox_AddString(hwndLB, sz));
         }
      }
   }

   return(0);
}