예제 #1
0
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
	int argc;
	char **argv = CommandLineToArgvA(GetCommandLineA(), &argc);

	int res = main(argc, argv);

	// Free memory
	LocalFree((HLOCAL)argv);

	return  res;
}
예제 #2
0
int CALLBACK WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShowCmd)
{
	ReserveBottomMemory();

	tick_thd.Start();

	int argc=0;
	wchar* cmd_line=GetCommandLineA();
	wchar** argv=CommandLineToArgvA(cmd_line,&argc);
	if(strstr(cmd_line,"NoConsole")==0)
	{
		if (AllocConsole())
		{
			freopen("CON","w",stdout);
			freopen("CON","w",stderr);
			freopen("CON","r",stdin);
		}
		SetConsoleCtrlHandler( (PHANDLER_ROUTINE) CtrlHandler, TRUE );
	}

	SetupPath();

	//SetUnhandledExceptionFilter(&ExeptionHandler);
	__try
	{
		int dc_init(int argc,wchar* argv[]);
		void dc_run();
		void dc_term();
		dc_init(argc,argv);

		#ifdef _WIN64
				setup_seh();
		#endif

		dc_run();
		dc_term();
	}
	__except( ExeptionHandler(GetExceptionInformation()) )
	{
		printf("Unhandled exception - Emulation thread halted...\n");
	}
	SetUnhandledExceptionFilter(0);

	return 0;
}
예제 #3
0
	bool CommandMap::ExecuteCommandWithStatus(std::string command)
	{
		int numArgs = 0;
		auto args = CommandLineToArgvA((PCHAR)command.c_str(), &numArgs);

		if (numArgs <= 0)
			return false;

		auto cmd = FindCommand(args[0]);
		if (!cmd)
			return false;

		std::vector<std::string> argsVect;
		if (numArgs > 1)
		for (int i = 1; i < numArgs; i++)
			argsVect.push_back(args[i]);

		if (cmd->Type == eCommandTypeCommand)
		{
			cmd->UpdateEvent(argsVect, std::string()); // if it's a command call it and return
			return true;
		}

		std::string previousValue;
		auto updateRet = SetVariable(cmd, (numArgs > 1 ? argsVect[0] : ""), previousValue);

		if (updateRet != eVariableSetReturnValueSuccess)
			return false;

		if (numArgs <= 1)
			return true;

		if (!cmd->UpdateEvent)
			return true; // no update event, so we'll just return with what we set the value to

		auto ret = cmd->UpdateEvent(argsVect, std::string());

		if (ret) // error, revert the variable
			return true;

		// error, revert the variable
		this->SetVariable(cmd, previousValue, std::string());
		return false;
	}
예제 #4
0
파일: Main.cpp 프로젝트: Mateuus/srcundead
// This function called by engine before main app window created, before any IO initialized. 
void game::PreInit()
{
	//@FOR STEAM- SetCurrentDirectory("Z:\\tsg\\WarOnline\\bin\\");

	u_srand(GetTickCount());

	g_HardwareInfo.Grab();

	win::hWinIcon  = NULL;
	win::szWinName = GetBuildVersionString();

#ifdef FINAL_BUILD
	win::hWinIcon = ::LoadIcon(win::hInstance, MAKEINTRESOURCE(IDI_WARZ));
	if(strstr(__r3dCmdLine, "-svchost") == NULL && strstr(__r3dCmdLine, "-gna") == NULL)//
	{
		MessageBox(NULL, "Please run UndeadBrasil launcher.", g_szApplicationName, MB_OK);
		ExitProcess(0);
	}
#endif	

#ifdef _DEBUG
	r3dOutToLog("cmd: %s\n", __r3dCmdLine);
#endif	
	
	// parse command line
	int argc = 0;
	char** argv = CommandLineToArgvA(__r3dCmdLine, &argc);
	for(int i=0; i<argc; i++) 
	{
		//if(strcmp(argv[i], "-login") == 0 && (i + 1) < argc)
		//{
		//	r3dscpy(Login_PassedUser, argv[++i]);
		//	continue;
		//}
		//if(strcmp(argv[i], "-pwd") == 0 && (i + 1) < argc)
		//{
		//	r3dscpy(Login_PassedPwd, argv[++i]);
		//	continue;
		//}
		if(strcmp(argv[i], "-WOLogin") == 0 && (i + 1) < argc)
		{
			r3dscpy(Login_PassedAuth, argv[++i]);
			continue;
		}
		
		//if(strcmp(argv[i], "-steam") == 0)
		//{
		//	gSteam.IS_ENABLED = true;
		//	continue;
		//}

		//if(strcmp(argv[i], "-survey") == 0 && (i + 1) < argc)
		//{
		//	gSurveyOutLink = argv[++i];
		//	continue;
		//}

#ifndef FINAL_BUILD
#if !DISABLE_PROFILER
		if (strcmp(argv[i], "-profile") == 0)
		{
			if (i + 1 >= argc)
				r3dError("Incorrect syntax for '-profile' option. Use '-profile level_name'");
			strcpy_s(LevelEditName, _countof(LevelEditName), argv[i + 1]);
			//	Set scheduled profile time to -1 to adjust it automatically after level will be loaded
			gScheduledProfileTime = -1.0f;
		}

		if (strcmp(argv[i], "-gprofile") == 0)
		{
			if (i + 1 >= argc)
				r3dError("Incorrect syntax for '-gprofile' option. Use '-gprofile level_name'");

			strcpy_s(LevelEditName, _countof(LevelEditName), argv[i + 1]);

			gProfileD3DFromCommandLine = true;
			gScheduledProfileTime = -1.0f;
		}
#endif

		if (strcmp(argv[i], "-camera") == 0)
		{
			if (i + 1 >= argc)
				r3dError("Incorrect syntax for '-camera' option. Use '-camera camera_spot_name'");

			strcpy_s(initialCameraSpotName, _countof(initialCameraSpotName), argv[i + 1]);
		}
#endif
	}
}
예제 #5
0
bool SH2Patcher::Init()
{
	this->dwVideoWidth = (int)GetPrivateProfileInt("Video", "Width", 1280, ".\\sh2proxy.ini");
	this->dwVideoHeight = (int)GetPrivateProfileInt("Video", "Height", 720, ".\\sh2proxy.ini");
	this->bVideoWindowed = (GetPrivateProfileInt("Video", "Windowed", 0, ".\\sh2proxy.ini") == 1);

	this->bWindowBorderless = (GetPrivateProfileInt("Window", "Borderless", 0, ".\\sh2proxy.ini") == 1);
	this->bForceWindowBorderless = (GetPrivateProfileInt("Window", "ForceBorderless", 0, ".\\sh2proxy.ini") == 1);
	this->dwWindowX = GetPrivateProfileInt("Window", "PositionX", 0, ".\\sh2proxy.ini");
	this->dwWindowY = GetPrivateProfileInt("Window", "PositionY", 0, ".\\sh2proxy.ini");

	LPSTR *szArgList;
	int argCount;

	szArgList = CommandLineToArgvA(GetCommandLine(), &argCount);
	if (szArgList != NULL && argCount > 1)
	{
		for (int i = 1; i < argCount; i++)
		{
			char* pos = strstr(szArgList[i], "=");
			int intval = 0;
			if (pos != NULL)
			{
				pos += 1;
				intval = atoi(pos);
			}

			if (strstr(szArgList[i], "-width=") != NULL || strstr(szArgList[i], "-w=") != NULL)
				this->dwVideoWidth = intval;

			if (strstr(szArgList[i], "-height=") != NULL || strstr(szArgList[i], "-h=") != NULL)
				this->dwVideoHeight = intval;

			if (strcmp(szArgList[i], "-windowed") == 0 || strcmp(szArgList[i], "-window") == 0 || strcmp(szArgList[i], "-w") == 0)
				this->bVideoWindowed = true;

			if (strcmp(szArgList[i], "-fullscreen") == 0 || strcmp(szArgList[i], "-fs") == 0 || strcmp(szArgList[i], "-f") == 0)
				this->bVideoWindowed = false;

			if (strcmp(szArgList[i], "-borderless") == 0 || strcmp(szArgList[i], "-bl") == 0)
				this->bWindowBorderless = true;

			if (strcmp(szArgList[i], "-borders") == 0 || strcmp(szArgList[i], "-b") == 0)
				this->bWindowBorderless = false;

			if (strstr(szArgList[i], "-x=") != NULL)
				this->dwWindowX = intval;

			if (strstr(szArgList[i], "-y=") != NULL)
				this->dwWindowY = intval;
		}
	}

	this->bPatchSingleCore = (GetPrivateProfileInt("Patches", "SingleCoreAffinity", 1, ".\\sh2proxy.ini") == 1);
	this->bPatchDisableSafeMode = (GetPrivateProfileInt("Patches", "DisableSafeMode", 1, ".\\sh2proxy.ini") == 1);
	this->bPatchFastTransitions = (GetPrivateProfileInt("Patches", "FastTransitions", 1, ".\\sh2proxy.ini") == 1);

	this->wTransitionWidth = (int)GetPrivateProfileInt("Patches", "FastTransitionWidth", 0, ".\\sh2proxy.ini");
	this->wTransitionHeight = (int)GetPrivateProfileInt("Patches", "FastTransitionHeight", 0, ".\\sh2proxy.ini");

	this->bExtraCreateLocalFix = (GetPrivateProfileInt("Extra", "CreateLocalFix", 1, ".\\sh2proxy.ini") == 1);

	this->handle = GetCurrentProcess();
	this->baseAddr = (DWORD_PTR)GetModuleHandle("sh2pc.exe");

	if (this->IsSH2())
	{
		this->PatchCode();

		if (this->bExtraCreateLocalFix)
		{
			if (FileExists("local.fix"))
				return true;

			std::ofstream myfile;
			myfile.open("local.fix");
			myfile << "HACK DX_CONFIG_DRIVER_AA_NOT_BROKEN 1";
			myfile.close();
		}
	}

	return true;
}
예제 #6
0
파일: main.cpp 프로젝트: Mateuus/newundead
void game::MainLoop(void)
{
  r3dOutToLog("Starting updater, v:%s, cmd:%s\n", UPDATER_VERSION, __r3dCmdLine);

  CUpdater updater;
  
  // parse command line
  int argc = 0;
  char** argv = CommandLineToArgvA(__r3dCmdLine, &argc);
  for(int i=0; i<argc; i++) 
  {
    /*if(strcmp(argv[i], "-steam") == 0 && (i + 0) < argc)
    {
      r3dOutToLog("Trying to init steam\n");
      gSteam.InitSteam();
      continue;
    }*/
  }

  if(g_isConsoleUpdater)
  {
    cmdLine_MainLoop(updater);
    return;
  }
  
  updater.Start();

  win32_input_Flush();
  
  if(g_taskbar) g_taskbar->SetProgressState(win::hWnd, TBPF_NORMAL);
  
  r3dStartFrame();
  while(1)
  {
    r3dEndFrame();
    r3dStartFrame();

    g_mb = 0;
    g_hCursor = gCursorArrow;
    tempDoMsgLoop();
    ::Sleep(1);
    
    r3dRenderer->StartRender();
    r3dRenderer->StartFrame();
    r3dRenderer->SetRenderingMode(R3D_BLEND_ALPHA | R3D_BLEND_NZ);
    r3dSetFiltering(R3D_POINT);
    
    r3dDrawBox2D(0, 0, r3dRenderer->ScreenW, r3dRenderer->ScreenH, r3dColor(64, 64, 64));
    
    #if 0
    updater.status_ = CUpdater::STATUS_TimeExpired;
    updater.showProgress_ = false;
    updater.prgTotal_.cur = 100;
    updater.prgTotal_.total = 100;
    r3dscpy(updater.updMsg1_, "Xxxxxxx");
    #endif

    switch(updater.status_) 
    {
      default: r3d_assert(0);
      
      case CUpdater::STATUS_Checking:
	g_bkgStarting->draw(0, 0, r3dRenderer->ScreenW, r3dRenderer->ScreenH, r3dColor(255, 255, 255));
	break;

      case CUpdater::STATUS_NeedLogin:
	g_bkgLogin->draw(0, 0, r3dRenderer->ScreenW, r3dRenderer->ScreenH, r3dColor(255, 255, 255));
	
	drawLoginButtons(updater);
	break;

      case CUpdater::STATUS_SerialCheck:
	g_bkgSerialCheck->draw(0, 0, r3dRenderer->ScreenW, r3dRenderer->ScreenH, r3dColor(255, 255, 255));

	drawSerialCheckButtons(updater);
	break;
    
      case CUpdater::STATUS_NeedRegister:
	g_bkgRegister->draw(0, 0, r3dRenderer->ScreenW, r3dRenderer->ScreenH, r3dColor(255, 255, 255));

	drawRegisterButtons(updater);
	break;
	
      case CUpdater::STATUS_TimeExpired:
	g_bkgExpired->draw(0, 0, r3dRenderer->ScreenW, r3dRenderer->ScreenH, r3dColor(255, 255, 255));

	drawTimeExpiredButtons(updater);
	break;

      case CUpdater::STATUS_Updating:
	g_bkgUpdate->draw(0, 0, r3dRenderer->ScreenW, r3dRenderer->ScreenH, r3dColor(255, 255, 255));

	drawUpdateButtons(updater);
        drawServerStatus(updater);
	drawNews(updater);
	break;
    }
    drawProgressBar(updater);
    drawCloseButton();

    r3dRenderer->EndFrame();
    r3dRenderer->EndRender(true);

    // if exit requested by control-f4
    if(g_bExit) {
      updater.RequestStop();
      break;
    }
    
    // activate updater window if other instance requested it
    if(WaitForSingleObject(g_updaterEvt, 0) == WAIT_OBJECT_0) {
      SwitchToThisWindow(win::hWnd, TRUE);
    }

    // try to remove mouse lock because of 
    // win::HandleActivate code that will lock mouse inside window
    ClipCursor(NULL);

    // if signalled to play game
    if(g_bStartGame)
      break;

    if(updater.result_ != CUpdater::RES_UPDATING && updater.result_ != CUpdater::RES_PLAY)
      break;
      
    // wndclass.hCursor must be NULL for this to work
    //SetCursor(g_hCursor);
  }
  
  updater.Stop();

  if(g_taskbar) g_taskbar->SetProgressState(win::hWnd, TBPF_NOPROGRESS);
  
  switch(updater.result_)
  {
    default: r3d_assert(0); 
    case CUpdater::RES_STOPPED:
      break;

    case CUpdater::RES_PLAY:
      startGame(updater);
      break;
      
    case CUpdater::RES_ERROR:
      showErrorMessageBox(updater);
      break;
  }
  
  gHwInfoPoster.Stop();
  TerminateProcess(GetCurrentProcess(), 0);
  
  return;
}
예제 #7
0
파일: runcpu.c 프로젝트: xavery/runcpu
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpszCmd,
                   int nCmd)
{
  STARTUPINFO sProcStartupInfo;
  PROCESS_INFORMATION sProcInformation;
  DWORD dwNewProcessAffinity;
  int argc, i, rv = 1;
  char **argv, *szProcCmdLine, *szLastErrorMsg;
  LPCTSTR lpProcWorkingDir = NULL;

  argv = CommandLineToArgvA(GetCommandLine(),&argc,&szProcCmdLine);

  if(argc < 2)
  {
    ErrorMsgBox("Usage : [-a affinity] [-d working_dir] -- <cmdline>",
                "Improper parameters");
    goto beach;
  }

  for(i=1; i<argc; ++i)
  {
    if(strcmp(argv[i],"-a") == 0)
    {
      ++i;
      if(i >= argc)
      {
        ErrorMsgBox("No data after -a.","Improper parameters");
        goto beach;
      }
      else if(sscanf_s(argv[i],"%8x",&dwNewProcessAffinity) != 1)
      {
        ErrorMsgBox("Improper affinity specification",
                    "Improper parameters");
        goto beach;
      }
    }
    else if(strcmp(argv[i],"-d") == 0)
    {
      ++i;
      if(i >= argc)
      {
        ErrorMsgBox("No data after -d.","Improper parameters");
        goto beach;
      }
      else lpProcWorkingDir = argv[i];
    }
  }

  /* prepare the STARTUPINFO structure. in our case, it is desired to hide
   * the window of the launched process. */
  ZeroMemory(&sProcStartupInfo, sizeof(sProcStartupInfo));
  sProcStartupInfo.cb = sizeof(sProcStartupInfo);
  sProcStartupInfo.dwFlags = STARTF_USESHOWWINDOW;
  sProcStartupInfo.wShowWindow = SW_HIDE;

  ZeroMemory(&sProcInformation, sizeof(sProcInformation));

  /* create the process by specifying its commandline. the process is created
   * as a suspended one. it is later resumed with ResumeThread() after setting
   * its affinity. therefore, the process will not start its execution until
   * the desired affinity is set. */
  if(CreateProcess(NULL, szProcCmdLine, NULL, NULL, FALSE,
                   CREATE_SUSPENDED, NULL, lpProcWorkingDir, &sProcStartupInfo,
                   &sProcInformation) == 0)
  {
    szLastErrorMsg = win_strerror("CreateProcess()");
    ErrorMsgBox(szLastErrorMsg, "WinAPI call failed");
    HeapFree(GetProcessHeap(),0,szLastErrorMsg);
    return 1;
  }

  /* set the affinity mask for the process. */
  if(SetProcessAffinityMask(sProcInformation.hProcess, dwNewProcessAffinity)
      == 0)
  {
    szLastErrorMsg = win_strerror("SetProcessAffinityMask()");
    ErrorMsgBox(szLastErrorMsg, "WinAPI call failed");
    HeapFree(GetProcessHeap(),0,szLastErrorMsg);

    if(TerminateProcess(sProcInformation.hProcess, 255) == 0)
    {
      szLastErrorMsg = win_strerror("TerminateProcess()");
      ErrorMsgBox(szLastErrorMsg, "WinAPI call failed");
      HeapFree(GetProcessHeap(),0,szLastErrorMsg);
    }
    goto beach2;
  }

  /* and resume (actually, start) its execution. */
  if(ResumeThread(sProcInformation.hThread) == -1)
  {
    szLastErrorMsg = win_strerror("ResumeThread()");
    ErrorMsgBox(szLastErrorMsg, "WinAPI call failed");
    HeapFree(GetProcessHeap(),0,szLastErrorMsg);

    if(TerminateProcess(sProcInformation.hProcess, 255) == 0)
    {
      szLastErrorMsg = win_strerror("TerminateProcess()");
      ErrorMsgBox(szLastErrorMsg, "WinAPI call failed");
      HeapFree(GetProcessHeap(),0,szLastErrorMsg);
    }
    goto beach2;
  }

  /* process launched successfully. */
  rv = 0;

beach2:
  /* close handles to the created process and its main thread, and exit. */
  CloseHandle(sProcInformation.hProcess);
  CloseHandle(sProcInformation.hThread);

beach:
  HeapFree(GetProcessHeap(),0,argv);
  return rv;
}
예제 #8
0
파일: process.c 프로젝트: FreeRDP/FreeRDP
BOOL _CreateProcessExA(HANDLE hToken, DWORD dwLogonFlags,
                       LPCSTR lpApplicationName, LPSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes,
                       LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags,
                       LPVOID lpEnvironment,
                       LPCSTR lpCurrentDirectory, LPSTARTUPINFOA lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation)
{
	pid_t pid;
	int numArgs;
	LPSTR* pArgs = NULL;
	char** envp = NULL;
	char* filename = NULL;
	HANDLE thread;
	HANDLE process;
	WINPR_ACCESS_TOKEN* token;
	LPTCH lpszEnvironmentBlock;
	BOOL ret = FALSE;
	sigset_t oldSigMask;
	sigset_t newSigMask;
	BOOL restoreSigMask = FALSE;
	numArgs = 0;
	lpszEnvironmentBlock = NULL;
	pArgs = CommandLineToArgvA(lpCommandLine, &numArgs);

	if (!pArgs)
		return FALSE;

	token = (WINPR_ACCESS_TOKEN*) hToken;

	if (lpEnvironment)
	{
		envp = EnvironmentBlockToEnvpA(lpEnvironment);
	}
	else
	{
		lpszEnvironmentBlock = GetEnvironmentStrings();

		if (!lpszEnvironmentBlock)
			goto finish;

		envp = EnvironmentBlockToEnvpA(lpszEnvironmentBlock);
	}

	if (!envp)
		goto finish;

	filename = FindApplicationPath(pArgs[0]);

	if (NULL == filename)
		goto finish;

	/* block all signals so that the child can safely reset the caller's handlers */
	sigfillset(&newSigMask);
	restoreSigMask = !pthread_sigmask(SIG_SETMASK, &newSigMask, &oldSigMask);
	/* fork and exec */
	pid = fork();

	if (pid < 0)
	{
		/* fork failure */
		goto finish;
	}

	if (pid == 0)
	{
		/* child process */
#ifndef __sun
		int maxfd;
#endif
		int fd;
		int sig;
		sigset_t set;
		struct sigaction act;
		/* set default signal handlers */
		memset(&act, 0, sizeof(act));
		act.sa_handler = SIG_DFL;
		act.sa_flags = 0;
		sigemptyset(&act.sa_mask);

		for (sig = 1; sig < NSIG; sig++)
			sigaction(sig, &act, NULL);

		/* unblock all signals */
		sigfillset(&set);
		pthread_sigmask(SIG_UNBLOCK, &set, NULL);

		if (lpStartupInfo)
		{
			int handle_fd;
			handle_fd = winpr_Handle_getFd(lpStartupInfo->hStdOutput);

			if (handle_fd != -1)
				dup2(handle_fd, STDOUT_FILENO);

			handle_fd = winpr_Handle_getFd(lpStartupInfo->hStdError);

			if (handle_fd != -1)
				dup2(handle_fd, STDERR_FILENO);

			handle_fd = winpr_Handle_getFd(lpStartupInfo->hStdInput);

			if (handle_fd != -1)
				dup2(handle_fd, STDIN_FILENO);
		}

#ifdef __sun
		closefrom(3);
#else
#ifdef F_MAXFD // on some BSD derivates
		maxfd = fcntl(0, F_MAXFD);
#else
		maxfd = sysconf(_SC_OPEN_MAX);
#endif

		for (fd = 3; fd < maxfd; fd++)
			close(fd);

#endif // __sun

		if (token)
		{
			if (token->GroupId)
			{
				int rc = setgid((gid_t) token->GroupId);

				if (rc < 0)
				{
				}
				else
				{
					initgroups(token->Username, (gid_t) token->GroupId);
				}
			}

			if (token->UserId)
				setuid((uid_t) token->UserId);
		}

		/* TODO: add better cwd handling and error checking */
		if (lpCurrentDirectory && strlen(lpCurrentDirectory) > 0)
			chdir(lpCurrentDirectory);

		if (execve(filename, pArgs, envp) < 0)
		{
			/* execve failed - end the process */
			_exit(1);
		}
	}
	else
	{
		/* parent process */
	}

	process = CreateProcessHandle(pid);

	if (!process)
	{
		goto finish;
	}

	thread = CreateNoneHandle();

	if (!thread)
	{
		ProcessHandleCloseHandle(process);
		goto finish;
	}

	lpProcessInformation->hProcess = process;
	lpProcessInformation->hThread = thread;
	lpProcessInformation->dwProcessId = (DWORD) pid;
	lpProcessInformation->dwThreadId = (DWORD) pid;
	ret = TRUE;
finish:

	/* restore caller's original signal mask */
	if (restoreSigMask)
		pthread_sigmask(SIG_SETMASK, &oldSigMask, NULL);

	free(filename);

	if (pArgs)
	{
		HeapFree(GetProcessHeap(), 0, pArgs);
	}

	if (lpszEnvironmentBlock)
		FreeEnvironmentStrings(lpszEnvironmentBlock);

	if (envp)
	{
		int i = 0;

		while (envp[i])
		{
			free(envp[i]);
			i++;
		}

		free(envp);
	}

	return ret;
}
예제 #9
0
파일: main.cpp 프로젝트: paulftw/vpinball
extern "C" int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPTSTR /*lpCmdLine*/, int /*nShowCmd*/)
{
#ifdef CRASH_HANDLER
    rde::CrashHandler::Init();
#endif

	// disable auto-rotate on tablets
#if (WINVER <= 0x0601)
    SetDisplayAutoRotationPreferences = (pSDARP) GetProcAddress(GetModuleHandle(TEXT("user32.dll")),
                                                                "SetDisplayAutoRotationPreferences");
    if(SetDisplayAutoRotationPreferences)
        SetDisplayAutoRotationPreferences(ORIENTATION_PREFERENCE_LANDSCAPE);
#else
    SetDisplayAutoRotationPreferences(ORIENTATION_PREFERENCE_LANDSCAPE);
#endif

	g_hinst = hInstance;
   
#if _WIN32_WINNT >= 0x0400 & defined(_ATL_FREE_THREADED)
    HRESULT hRes = CoInitializeEx(NULL, COINIT_MULTITHREADED);
#else
    HRESULT hRes = CoInitialize(NULL);
#endif
    _ASSERTE(SUCCEEDED(hRes));
    _Module.Init(ObjectMap, hInstance, &LIBID_VPinballLib);

	bool fFile = false;
	bool fPlay = false;
    bool bRun = true;
	TCHAR szTableFileName[_MAX_PATH] = {0};
    int nRet = 0;

    int nArgs;
	LPSTR *szArglist = CommandLineToArgvA(GetCommandLine(), &nArgs);

	for(int i=0; i < nArgs; ++i)
    {
        if (lstrcmpi(szArglist[i], _T("-UnregServer"))==0 || lstrcmpi(szArglist[i], _T("/UnregServer"))==0)
        {
            _Module.UpdateRegistryFromResource(IDR_VPINBALL, FALSE);
            nRet = _Module.UnregisterServer(TRUE);
            bRun = false;
			break;
        }
        if (lstrcmpi(szArglist[i], _T("-RegServer"))==0 || lstrcmpi(szArglist[i], _T("/RegServer"))==0)
        {
            _Module.UpdateRegistryFromResource(IDR_VPINBALL, TRUE);
            nRet = _Module.RegisterServer(TRUE);
            bRun = false;
			break;
        }

		const bool editfile = (lstrcmpi(szArglist[i], _T("-Edit"))==0 || lstrcmpi(szArglist[i], _T("/Edit"))==0);
		const bool playfile = (lstrcmpi(szArglist[i], _T("-Play"))==0 || lstrcmpi(szArglist[i], _T("/Play"))==0);
        if ((editfile || playfile) && (i+1 < nArgs))
        {
			fFile = true;
			fPlay = playfile;

			// Remove leading - or /
			char* filename;
			if((szArglist[i+1][0] == '-') || (szArglist[i+1][0] == '/'))
				filename = szArglist[i+1]+1;
			else
				filename = szArglist[i+1];

			// Remove " "
			if(filename[0] == '"') {
				strcpy_s(szTableFileName,filename+1);
				szTableFileName[lstrlen(szTableFileName)] = '\0';
			}
			else
				strcpy_s(szTableFileName,filename);

			// Add current path
			char szLoadDir[MAX_PATH];
			if(szTableFileName[1] != ':') {
				GetCurrentDirectory(MAX_PATH,szLoadDir);
				strcat_s(szLoadDir,"\\");
				strcat_s(szLoadDir,szTableFileName);
				strcpy_s(szTableFileName,szLoadDir);
			} else
				// Or set from table path
				if(playfile) {
					PathFromFilename(szTableFileName, szLoadDir);
					SetCurrentDirectory(szLoadDir);
				}

			if(playfile)
				VPinball::SetOpenMinimized();

			break;
        }
    }

	free(szArglist);

    // load and register VP type library for COM integration
    char szFileName[_MAX_PATH];
    if (GetModuleFileName(hInstance, szFileName, _MAX_PATH))
    {
        ITypeLib *ptl = NULL;
        MAKE_WIDEPTR_FROMANSI(wszFileName, szFileName);
        if (SUCCEEDED(LoadTypeLib(wszFileName, &ptl)))
        {
            // first try to register system-wide (if running as admin)
            HRESULT hr = RegisterTypeLib(ptl, wszFileName, NULL);
            if (!SUCCEEDED(hr))
            {
                // if failed, register only for current user
                hr = RegisterTypeLibForUser(ptl, wszFileName, NULL);
                if (!SUCCEEDED(hr))
                    MessageBox(0, "Could not register type library. Try running Visual Pinball as administrator.", "Error", MB_ICONWARNING);
            }
            ptl->Release();
        }
        else
            MessageBox(0, "Could not load type library.", "Error", MB_ICONSTOP);
    }

    if (bRun)
    {
#if _WIN32_WINNT >= 0x0400 & defined(_ATL_FREE_THREADED)
        hRes = _Module.RegisterClassObjects(CLSCTX_LOCAL_SERVER,
            REGCLS_MULTIPLEUSE | REGCLS_SUSPENDED);
        _ASSERTE(SUCCEEDED(hRes));
        hRes = CoResumeClassObjects();
#else
        hRes = _Module.RegisterClassObjects(CLSCTX_LOCAL_SERVER,
            REGCLS_MULTIPLEUSE);
#endif
        _ASSERTE(SUCCEEDED(hRes));

		INITCOMMONCONTROLSEX iccex;
		iccex.dwSize = sizeof(INITCOMMONCONTROLSEX);
		iccex.dwICC = ICC_COOL_CLASSES;
		InitCommonControlsEx(&iccex);

        {
            EditableRegistry::RegisterEditable<Bumper>();
            EditableRegistry::RegisterEditable<Decal>();
            EditableRegistry::RegisterEditable<DispReel>();
            EditableRegistry::RegisterEditable<Flasher>();
            EditableRegistry::RegisterEditable<Flipper>();
            EditableRegistry::RegisterEditable<Gate>();
            EditableRegistry::RegisterEditable<Kicker>();
            EditableRegistry::RegisterEditable<Light>();
            EditableRegistry::RegisterEditable<LightSeq>();
            EditableRegistry::RegisterEditable<Plunger>();
            EditableRegistry::RegisterEditable<Primitive>();
            EditableRegistry::RegisterEditable<Ramp>();
            EditableRegistry::RegisterEditable<Rubber>();
            EditableRegistry::RegisterEditable<Spinner>();
            EditableRegistry::RegisterEditable<Surface>();
            EditableRegistry::RegisterEditable<Textbox>();
            EditableRegistry::RegisterEditable<Timer>();
            EditableRegistry::RegisterEditable<Trigger>();
        }

		g_pvp = new VPinball();
		g_pvp->AddRef();
		g_pvp->Init();
		g_haccel = LoadAccelerators(g_hinst,MAKEINTRESOURCE(IDR_VPACCEL));

		if (fFile)
			{
			g_pvp->LoadFileName(szTableFileName);

			if (fPlay)
				g_pvp->DoPlay();
			}

		// VBA APC handles message loop (bastards)
		g_pvp->MainMsgLoop();

		g_pvp->Release();

		DestroyAcceleratorTable(g_haccel);

        _Module.RevokeClassObjects();
        Sleep(dwPause); //wait for any threads to finish
    }

    _Module.Term();
    CoUninitialize();
#ifdef _CRTDBG_MAP_ALLOC
#ifdef DEBUG_XXX  //disable this in perference to DevPartner
	_CrtSetDumpClient(MemLeakAlert);
#endif
	_CrtDumpMemoryLeaks();
#endif
	//SET_CRT_DEBUG_FIELD( _CRTDBG_LEAK_CHECK_DF );

    return nRet;
}
예제 #10
0
BOOL _CreateProcessExA(HANDLE hToken, DWORD dwLogonFlags,
		LPCSTR lpApplicationName, LPSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes,
		LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment,
		LPCSTR lpCurrentDirectory, LPSTARTUPINFOA lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation)
{
	pid_t pid;
	int flags;
	int numArgs;
	LPSTR* pArgs = NULL;
	char** envp = NULL;
	char* filename = NULL;
	HANDLE thread;
	HANDLE process;
	WINPR_ACCESS_TOKEN* token;
	LPTCH lpszEnvironmentBlock;
	BOOL ret = FALSE;

	pid = 0;
	numArgs = 0;
	lpszEnvironmentBlock = NULL;

	pArgs = CommandLineToArgvA(lpCommandLine, &numArgs);

	flags = 0;

	token = (WINPR_ACCESS_TOKEN*) hToken;

	if (lpEnvironment)
	{
		envp = EnvironmentBlockToEnvpA(lpEnvironment);
	}
	else
	{
		lpszEnvironmentBlock = GetEnvironmentStrings();
		envp = EnvironmentBlockToEnvpA(lpszEnvironmentBlock);
	}

	filename = FindApplicationPath(pArgs[0]);
	if (NULL == filename)
		goto finish;

	/* fork and exec */

	pid = fork();

	if (pid < 0)
	{
		/* fork failure */
		goto finish;
	}

	if (pid == 0)
	{
		/* child process */
#ifdef __sun
	closefrom(3);
#else
	int maxfd;
#ifdef F_MAXFD // on some BSD derivates
	maxfd = fcntl(0, F_MAXFD);
#else
	maxfd = sysconf(_SC_OPEN_MAX);
#endif
	int fd;
	for(fd=3; fd<maxfd; fd++)
		close(fd);
#endif // __sun

		if (token)
		{
			if (token->GroupId)
			{
				int rc = setgid((gid_t) token->GroupId);
				if (rc < 0)
				{
				}
				else
				{
					initgroups(token->Username, (gid_t) token->GroupId);
				}
			}

			if (token->UserId)
				setuid((uid_t) token->UserId);

			/* TODO: add better cwd handling and error checking */
			if (lpCurrentDirectory && strlen(lpCurrentDirectory) > 0)
				chdir(lpCurrentDirectory);
		}

		if (execve(filename, pArgs, envp) < 0)
		{
			/* execve failed - end the process */
			_exit(1);
		}
	}
	else
	{
		/* parent process */
	}

	process = CreateProcessHandle(pid);

	if (!process)
	{
		goto finish;
	}

	thread = CreateNoneHandle();

	if (!thread)
	{
		goto finish;
	}

	lpProcessInformation->hProcess = process;
	lpProcessInformation->hThread = thread;
	lpProcessInformation->dwProcessId = (DWORD) pid;
	lpProcessInformation->dwThreadId = (DWORD) pid;

	ret = TRUE;

finish:
	if (filename)
	{
		free(filename);
	}

	if (pArgs)
	{
		HeapFree(GetProcessHeap(), 0, pArgs);
	}

	if (lpszEnvironmentBlock)
		FreeEnvironmentStrings(lpszEnvironmentBlock);

	if (envp)
	{
		int i = 0;

		while (envp[i])
		{
			free(envp[i]);
			i++;
		}

		free(envp);
	}

	return ret;
}
예제 #11
0
int WINAPI WinMain(HINSTANCE hInstance,
	HINSTANCE hPrevInstance,
	LPSTR lpCmdLine,
	int nCmdShow)
{
	RECT rc;
	int nWidth;
	int nHeight;

	HWND hWndTS = FindTSWindow();
	if(hWndTS != NULL) {
		GetWindowRect(hWndTS, &rc);
		nWidth = rc.right - rc.left;
		nHeight = rc.bottom - rc.top;
	} else {
		ExitProcess(0);
	}

	bool bUseJoystick = true;
	int nArgCount;
	LPSTR *pArgList;

	pArgList = CommandLineToArgvA(GetCommandLine(), &nArgCount);
	for (int i = 0; i < nArgCount; ++i)
	{
		if (pArgList[i][0] != '-')
			continue;

		if (strcmp(pArgList[i]+1, "j") == 0)
			bUseJoystick = !bUseJoystick;

		if (strcmp(pArgList[i]+1, "v") == 0)
			ToggleDisplaySection(0);

		if (strcmp(pArgList[i]+1, "f") == 0)
			ToggleFontOutline();

		if (strcmp(pArgList[i]+1, "s") == 0)
			ToggleSpeedLimitOnly();

		if (pArgList[i][1] == 'm')
		{
			if (isdigit(pArgList[i][2]))
			{
				int nSection = atoi(pArgList[i]+2);
				if (nSection >= 1 && nSection <= 12)
					ToggleDisplaySection(nSection);
			}
		}

		if (pArgList[i][1] == 's')
		{
			if (isdigit(pArgList[i][2]))
			{
				int nSection = atoi(pArgList[i]+2);
				if (nSection >= 1 && nSection <= 12)
					ToggleDisplaySection(nSection + 12);
			}
		}
	}

	margin.cxRightWidth = nWidth;
	margin.cyBottomHeight = nHeight;

	WNDCLASSEX wc;
	ZeroMemory(&wc, sizeof(WNDCLASSEX));

	wc.cbSize = sizeof(WNDCLASSEX);
	wc.style = CS_HREDRAW | CS_VREDRAW;
	wc.lpfnWndProc = WindowProc;
	wc.hInstance = hInstance;
	wc.hCursor = LoadCursor(NULL, IDC_ARROW);
	wc.hbrBackground = (HBRUSH)RGB(0,0,0);
	wc.lpszClassName = "WindowClass";

	RegisterClassEx(&wc);

	hWnd = CreateWindowEx(0,
		"WindowClass",
		"TrainSim Helper",
		WS_EX_TOPMOST | WS_POPUP,
		rc.left, rc.top,
		nWidth, nHeight,
		NULL,
		NULL,
		hInstance,
		NULL);

	SetWindowLong(hWnd, GWL_EXSTYLE,(int)GetWindowLong(hWnd, GWL_EXSTYLE) | WS_EX_LAYERED |WS_EX_TRANSPARENT);
	SetLayeredWindowAttributes(hWnd, RGB(0,0,0), 255, ULW_COLORKEY | LWA_ALPHA);

	ShowWindow(hWnd, nCmdShow);

	InitD3D(hWnd, nWidth, nHeight);
	MSG msg;
	::SetWindowPos(hWndTS, HWND_NOTOPMOST,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE);

	// V for the whole overlay
	RegisterHotKey(hWnd, 0, MOD_SHIFT | MOD_ALT, 0x56 /* V key */);

	// F1-F12 for the main overlay
	for (int i = 1; i <= 12; ++i)
		RegisterHotKey(hWnd, i, MOD_SHIFT | MOD_ALT, VK_F1 + i - 1);

	// F1-F12 for the steam overlay
	for (int i = 13; i <= 24; ++i)
		RegisterHotKey(hWnd, i, MOD_SHIFT | MOD_CONTROL, VK_F1 + i - 13);

	// 0-9 digits for the countdown
	for (int i = 100; i <= 109; ++i)
		RegisterHotKey(hWnd, i, MOD_SHIFT | MOD_ALT, 0x30 + i - 100);

	// R for the countdown reset
	RegisterHotKey(hWnd, 110, MOD_SHIFT | MOD_ALT, 0x52 /* R key */);

	// D for driving direction
	RegisterHotKey(hWnd, 201, MOD_SHIFT | MOD_ALT, 0x44 /* D key */);

	// F for font outline
	RegisterHotKey(hWnd, 202, MOD_SHIFT | MOD_ALT, 0x46 /* F key */);

	// S for speed limit only
	RegisterHotKey(hWnd, 203, MOD_SHIFT | MOD_ALT, 0x53 /* S key */);

	if (bUseJoystick)
		if (FAILED(InitDirectInput()))
			ExitProcess(0);

	bool fDone = false;

	while(!fDone)
	{
		hWndTS = FindTSWindow();
		if (!hWndTS)
		{
			msg.wParam = 0;
			break;
		}

		RECT rcNew;
		GetWindowRect(hWndTS, &rcNew);
		if (rcNew.left != rc.left || rcNew.top != rc.top)
		{
			rc = rcNew;
			MoveWindow(hWnd, rc.left, rc.top, nWidth, nHeight, FALSE);
		}

		::SetWindowPos(hWnd, HWND_TOPMOST,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE);
		Sleep(10);

		RenderOverlay();
		if (bUseJoystick)
			UpdateJoystick();

		while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);

			switch(msg.message)
			{
			case WM_QUIT:
				fDone = true;
				break;
			}
		}
	}

	if (bUseJoystick)
		FreeDirectInput();

	return msg.wParam;
}
예제 #12
0
int WINAPI WinMain(HINSTANCE hInstance,  HINSTANCE hPrevInstance,  LPSTR lpCmdLine, int nCmdShow)
{
  int argc;
  char ** argv = CommandLineToArgvA(GetCommandLineA(),&argc);

#else
int main (int argc, char *argv[])
{
#endif
  HINSTANCE hinstLib;

  char buffer[MAX_PATH],*file;

  if (!GetFullPathName(argv[0],MAX_PATH,buffer,&file)) {
    MessageBox(NULL,
      TEXT("Couldn't find the correct working directory"),
      TEXT("Failed to start editor"),
      MB_OK|MB_ICONERROR);
    return 0;
  }
  if (file!=NULL)
    *file = 0; // finish the string, I don't need the appname
  //int i;
  //for (i=0;i<argc; i++)
  //		printf("%d %s\n",i,argv[i]);

  SetCurrentDirectory(buffer);


  SetDllDirectory(".\\bin\\");
  hinstLib = LoadLibrary("lua5.1.dll");
  if (hinstLib != NULL)
  {
    luaL_newstate = (voidfunc*) GetProcAddress(hinstLib, "luaL_newstate");
    luaL_loadbuffer = (varfunc*) GetProcAddress(hinstLib, "luaL_loadbuffer");
    luaL_openlibs = (varfunc*) GetProcAddress(hinstLib, "luaL_openlibs");
    lua_pcall = (varfunc*)GetProcAddress(hinstLib, "lua_pcall");
    lua_tolstring = (varfunc*)GetProcAddress(hinstLib, "lua_tolstring");
    lua_setfield = (varfunc*)GetProcAddress(hinstLib, "lua_setfield");
    lua_pushcclosure = (varfunc*)GetProcAddress(hinstLib, "lua_pushcclosure");
    lua_createtable = (varfuncvoid*)GetProcAddress(hinstLib, "lua_createtable");
    lua_pushstring = (varfuncvoid*)GetProcAddress(hinstLib, "lua_pushstring");
    lua_rawseti = (varfuncvoid*)GetProcAddress(hinstLib, "lua_rawseti");
    // If the function address is valid, call the function.

    if (luaL_newstate && luaL_loadbuffer && luaL_openlibs && lua_pcall &&
      lua_pushcclosure && lua_setfield && lua_tolstring &&
      lua_createtable && lua_pushstring && lua_rawseti)
    {
      // OK, I don't do any error checking here, which COULD
      // lead to bugs that are hard to find, but considered the simplicity
      // of the whole process, it SHOULD be pretty unlikely to fail here
      // but don't come back on me if it does...
      void *L = luaL_newstate();
      int i;

      if (L!=NULL) {
        lua_createtable(L,argc,0);
        for (i=0;i<argc;i++) {
          lua_pushstring(L,argv[i]);
          lua_rawseti(L,-2,i+1);
        }
        lua_setfield(L,LUA_GLOBALSINDEX,"_ARG");
        luaL_openlibs(L);
        lua_pushcclosure(L,luafunc_mbox,0);
        lua_setfield(L,LUA_GLOBALSINDEX,"_ERRMSG");
        if (luaL_loadbuffer(L,luacode,strlen(luacode),"Initializer") == 0)
          lua_pcall(L,0,0,0);
        else
          MessageBox(NULL,
          TEXT("An unexpected error occured while loading the lua chunk."),
          TEXT("Failed to start editor"),
          MB_OK|MB_ICONERROR);
      } else
        MessageBox(NULL,
        TEXT("Couldn't initialize a luastate"),
        TEXT("Failed to start editor"),
        MB_OK|MB_ICONERROR);
    } else {
      MessageBox(NULL,
        TEXT("Could not load all functions that are supposed to be located in the lua5.1.dll\n"
        "This is not supposed to be happening..."),
        TEXT("Failed to start editor"),
        MB_OK|MB_ICONERROR);
    }

    // Free the DLL module.
    FreeLibrary(hinstLib);
  } else {
    MessageBox(NULL,
      TEXT("The lua5.1.dll could not be found or loaded, please check the working directory of the application.\n"),
      TEXT("Failed to initialize editor"),
      MB_OK|MB_ICONERROR);
  }

  return 0;
}
예제 #13
0
void FCmdLine::Set(const char* cmdLine)
{
	m_argv = CommandLineToArgvA((PCHAR)cmdLine, &m_argc); 
}
예제 #14
0
파일: main.cpp 프로젝트: djrobx/vpinballx
   virtual BOOL InitInstance() 
   { 
#ifdef CRASH_HANDLER
      rde::CrashHandler::Init();
#endif

      // disable auto-rotate on tablets
#if (WINVER <= 0x0601)
      SetDisplayAutoRotationPreferences = (pSDARP)GetProcAddress(GetModuleHandle(TEXT("user32.dll")),
         "SetDisplayAutoRotationPreferences");
      if (SetDisplayAutoRotationPreferences)
         SetDisplayAutoRotationPreferences(ORIENTATION_PREFERENCE_LANDSCAPE);
#else
      SetDisplayAutoRotationPreferences(ORIENTATION_PREFERENCE_LANDSCAPE);
#endif

      g_hinst = theInstance;
#if _WIN32_WINNT >= 0x0400 & defined(_ATL_FREE_THREADED)
      hRes = CoInitializeEx(NULL, COINIT_MULTITHREADED);
#else
      hRes = CoInitialize(NULL);
#endif
      _ASSERTE(SUCCEEDED(hRes));
      _Module.Init(ObjectMap, theInstance, &LIBID_VPinballLib);

      fFile = false;
      fPlay = false;
      fPov = false;
      bRun = true;
      int nRet = 0;
      memset(szTableFileName, 0, _MAX_PATH);
      // Start VP with file dialog open and then also playing that one?
      int stos;
      HRESULT hr = GetRegInt("Editor", "SelectTableOnStart", &stos);
      if (hr != S_OK)
         stos = 1; // The default = on
      if (stos)
      {
         fFile = true;
         fPlay = true;
         fPov = false;
      }

      int nArgs;
      LPSTR *szArglist = CommandLineToArgvA(GetCommandLine(), &nArgs);

      for (int i = 0; i < nArgs; ++i)
      {
         if (lstrcmpi(szArglist[i], _T("-h")) == 0 || lstrcmpi(szArglist[i], _T("/h")) == 0
            || lstrcmpi(szArglist[i], _T("-Help")) == 0 || lstrcmpi(szArglist[i], _T("/Help")) == 0
            || lstrcmpi(szArglist[i], _T("-?")) == 0 || lstrcmpi(szArglist[i], _T("/?")) == 0)
         {
            ShowError("-UnregServer  Unregister VP functions\n-RegServer  Register VP functions\n\n-DisableTrueFullscreen  Force-disable True Fullscreen setting\n\n-Edit [filename]  load file into VP\n-Play [filename]  load and play file\n-Pov [filename]  load, export pov and close");
            bRun = false;
            break;
         }

         if (lstrcmpi(szArglist[i], _T("-UnregServer")) == 0 || lstrcmpi(szArglist[i], _T("/UnregServer")) == 0)
         {
            _Module.UpdateRegistryFromResource(IDR_VPINBALL, FALSE);
            nRet = _Module.UnregisterServer(TRUE);
            bRun = false;
            break;
         }
         if (lstrcmpi(szArglist[i], _T("-RegServer")) == 0 || lstrcmpi(szArglist[i], _T("/RegServer")) == 0)
         {
            _Module.UpdateRegistryFromResource(IDR_VPINBALL, TRUE);
            nRet = _Module.RegisterServer(TRUE);
            bRun = false;
            break;
         }

         disableTrueFullscreen |= (lstrcmpi(szArglist[i], _T("-DisableTrueFullscreen")) == 0 || lstrcmpi(szArglist[i], _T("/DisableTrueFullscreen")) == 0);

         const bool editfile = (lstrcmpi(szArglist[i], _T("-Edit")) == 0 || lstrcmpi(szArglist[i], _T("/Edit")) == 0);
         const bool playfile = (lstrcmpi(szArglist[i], _T("-Play")) == 0 || lstrcmpi(szArglist[i], _T("/Play")) == 0);
		 const bool povfile = (lstrcmpi(szArglist[i], _T("-Pov")) == 0 || lstrcmpi(szArglist[i], _T("/Pov")) == 0);
		 if ((editfile || playfile || povfile) && (i + 1 < nArgs))
         {
            fFile = true;
            fPlay = playfile;
			fPov = povfile;

            // Remove leading - or /
            char* filename;
            if ((szArglist[i + 1][0] == '-') || (szArglist[i + 1][0] == '/'))
               filename = szArglist[i + 1] + 1;
            else
               filename = szArglist[i + 1];

            // Remove " "
            if (filename[0] == '"') {
               strcpy_s(szTableFileName, filename + 1);
               szTableFileName[lstrlen(szTableFileName) - 1] = '\0';
            }
            else
               strcpy_s(szTableFileName, filename);

            // Add current path
            char szLoadDir[MAX_PATH];
            if (szTableFileName[1] != ':') {
               GetCurrentDirectory(MAX_PATH, szLoadDir);
               strcat_s(szLoadDir, "\\");
               strcat_s(szLoadDir, szTableFileName);
               strcpy_s(szTableFileName, szLoadDir);
            }
            else
               // Or set from table path
               if (playfile) {
                  PathFromFilename(szTableFileName, szLoadDir);
                  SetCurrentDirectory(szLoadDir);
               }

            if (playfile || povfile)
               VPinball::SetOpenMinimized();

            break;
         }
      }

      free(szArglist);

      // load and register VP type library for COM integration
      char szFileName[_MAX_PATH];
      if (GetModuleFileName(theInstance, szFileName, _MAX_PATH))
      {
         ITypeLib *ptl = NULL;
         MAKE_WIDEPTR_FROMANSI(wszFileName, szFileName);
         if (SUCCEEDED(LoadTypeLib(wszFileName, &ptl)))
         {
            // first try to register system-wide (if running as admin)
            hr = RegisterTypeLib(ptl, wszFileName, NULL);
            if (!SUCCEEDED(hr))
            {
               // if failed, register only for current user
               hr = RegisterTypeLibForUser(ptl, wszFileName, NULL);
               if (!SUCCEEDED(hr))
                  MessageBox(0, "Could not register type library. Try running Visual Pinball as administrator.", "Error", MB_ICONWARNING);
            }
            ptl->Release();
         }
         else
            MessageBox(0, "Could not load type library.", "Error", MB_ICONSTOP);
      }

      //SET_CRT_DEBUG_FIELD( _CRTDBG_LEAK_CHECK_DF );
      return TRUE;
   }
예제 #15
0
파일: process.c 프로젝트: TrickyCat/FreeRDP
BOOL _CreateProcessExA(HANDLE hToken, DWORD dwLogonFlags,
		LPCSTR lpApplicationName, LPSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes,
		LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment,
		LPCSTR lpCurrentDirectory, LPSTARTUPINFOA lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation)
{
	pid_t pid;
	int flags;
	int numArgs;
	LPSTR* pArgs;
	char** envp;
	char* filename = NULL;
	WINPR_THREAD* thread;
	WINPR_PROCESS* process;
	WINPR_ACCESS_TOKEN* token;
	LPTCH lpszEnvironmentBlock;

	pid = 0;
	envp = NULL;
	numArgs = 0;
	lpszEnvironmentBlock = NULL;

	pArgs = CommandLineToArgvA(lpCommandLine, &numArgs);

	flags = 0;

	token = (WINPR_ACCESS_TOKEN*) hToken;

	if (lpEnvironment)
	{
		envp = EnvironmentBlockToEnvpA(lpEnvironment);
	}
	else
	{
		lpszEnvironmentBlock = GetEnvironmentStrings();
		envp = EnvironmentBlockToEnvpA(lpszEnvironmentBlock);
	}

	filename = FindApplicationPath(pArgs[0]);

	/* fork and exec */

	pid = fork();

	if (pid < 0)
	{
		/* fork failure */
		return FALSE;
	}

	if (pid == 0)
	{
		/* child process */
#ifdef __sun
	closefrom(3);
#else
	int maxfd;
#ifdef F_MAXFD // on some BSD derivates
	maxfd = fcntl(0, F_MAXFD);
#else
	maxfd = sysconf(_SC_OPEN_MAX);
#endif
	int fd;
	for(fd=3; fd<maxfd; fd++)
		close(fd);
#endif // __sun

		if (token)
		{
			if (token->GroupId)
			{
				setgid((gid_t) token->GroupId);
				initgroups(token->Username, (gid_t) token->GroupId);
			}

			if (token->UserId)
				setuid((uid_t) token->UserId);
		}

		if (execve(filename, pArgs, envp) < 0)
		{
			return FALSE;
		}
	}
	else
	{
		/* parent process */
	}

	process = (WINPR_PROCESS*) malloc(sizeof(WINPR_PROCESS));

	if (!process)
		return FALSE;

	ZeroMemory(process, sizeof(WINPR_PROCESS));

	WINPR_HANDLE_SET_TYPE(process, HANDLE_TYPE_PROCESS);

	process->pid = pid;
	process->status = 0;
	process->dwExitCode = 0;

	thread = (WINPR_THREAD*) malloc(sizeof(WINPR_THREAD));

	ZeroMemory(thread, sizeof(WINPR_THREAD));

	if (!thread)
		return FALSE;

	WINPR_HANDLE_SET_TYPE(thread, HANDLE_TYPE_THREAD);

	thread->mainProcess = TRUE;

	lpProcessInformation->hProcess = (HANDLE) process;
	lpProcessInformation->hThread = (HANDLE) thread;
	lpProcessInformation->dwProcessId = (DWORD) pid;
	lpProcessInformation->dwThreadId = (DWORD) pid;

	free(filename);

	if (pArgs)
	{
		HeapFree(GetProcessHeap(), 0, pArgs);
	}

	if (lpszEnvironmentBlock)
		FreeEnvironmentStrings(lpszEnvironmentBlock);

	if (envp)
	{
		int i = 0;

		while (envp[i])
		{
			free(envp[i]);
			i++;
		}

		free(envp);
	}

	return TRUE;
}
예제 #16
0
	bool CommandMap::ExecuteCommandWithStatus(std::string command, bool isUserInput, std::string *output)
	{
		*output = "";

		int numArgs = 0;
		auto args = CommandLineToArgvA((PCHAR)command.c_str(), &numArgs);

		if (numArgs <= 0)
		{
			*output = "Invalid input";
			return false;
		}

		auto cmd = FindCommand(args[0]);
		if (!cmd || (isUserInput && cmd->Flags & eCommandFlagsInternal))
		{
			*output = "Command/Variable not found";
			return false;
		}

		if ((cmd->Flags & eCommandFlagsRunOnMainMenu) && !ElDorito::Instance().GameHasMenuShown)
		{
			queuedCommands.push_back(command);
			*output = "Command queued until mainmenu shows";
			return true;
		}

		// Host-only commands
		if (cmd->Flags & eCommandFlagsCheat || cmd->Flags & eCommandFlagsHostOnly)
		{
			auto session = Blam::Network::GetActiveSession();
			if (session && session->IsEstablished() && !session->IsHost())
			{
				*output = "Only a player hosting a game can use this command";
				return false;
			}
		}

		std::vector<std::string> argsVect;
		if (numArgs > 1)
			for (int i = 1; i < numArgs; i++)
				argsVect.push_back(args[i]);

		if (cmd->Type == eCommandTypeCommand && cmd->Flags == eCommandFlagsArgsNoParse)
		{
			argsVect.clear();
			if (numArgs >= 2)
				argsVect.push_back(command.substr(std::strlen(args[0]) + 1)); //push unparsed arguments after the command
			return cmd->UpdateEvent(argsVect, *output);
		}

		if (cmd->Type == eCommandTypeCommand)
			return cmd->UpdateEvent(argsVect, *output); // if it's a command call it and return

		if (numArgs <= 1)
		{
			*output = cmd->ValueString;
			return true;
		}

		std::string previousValue;
		auto updateRet = SetVariable(cmd, argsVect[0], previousValue);
		switch (updateRet)
		{
		case eVariableSetReturnValueError:
			*output = "Command/variable not found";
			return false;
		case eVariableSetReturnValueInvalidArgument:
			*output = "Invalid value";
			return false;
		case eVariableSetReturnValueOutOfRange:
			if (cmd->Type == eCommandTypeVariableInt)
				*output = "Value " + argsVect[0] + " out of range [" + std::to_string(cmd->ValueIntMin) + ".." + std::to_string(cmd->ValueIntMax) + "]";
			else if (cmd->Type == eCommandTypeVariableInt64)
				*output = "Value " + argsVect[0] + " out of range [" + std::to_string(cmd->ValueInt64Min) + ".." + std::to_string(cmd->ValueInt64Max) + "]";
			else if (cmd->Type == eCommandTypeVariableFloat)
				*output = "Value " + argsVect[0] + " out of range [" + std::to_string(cmd->ValueFloatMin) + ".." + std::to_string(cmd->ValueFloatMax) + "]";
			else
				*output = "Value " + argsVect[0] + " out of range [this shouldn't be happening!]";
			return false;
		}

		if (!cmd->UpdateEvent)
		{
			*output = previousValue + " -> " + cmd->ValueString; // no update event, so we'll just return with what we set the value to
			return true;
		}

		auto ret = cmd->UpdateEvent(argsVect, *output);

		if (!ret) // error, revert the variable
			this->SetVariable(cmd, previousValue, std::string());

		if (output->length() <= 0)
			*output = previousValue + " -> " + cmd->ValueString;

		return ret;
	}
예제 #17
0
bool CMPVlcSourceStream::Load(const TCHAR* fn)
{
    char def_options[512];
    char def_sout[512];


    LogDebug("Load()");
    Clear();

    strncpy(m_fn, fn, sizeof(m_fn));

    sprintf(m_pipename, "\\\\.\\pipe\\vlc2ds_%d_%d", GetCurrentThreadId(), GetTickCount());

    LogDebug("Creating named pipe %s", m_pipename);
    m_hPipe = CreateNamedPipe(
                  m_pipename,             // pipe name
                  PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,       // read/write access
                  PIPE_TYPE_MESSAGE |       // message type pipe
                  PIPE_READMODE_BYTE |   // message-read mode
                  PIPE_WAIT,                // blocking mode
                  PIPE_UNLIMITED_INSTANCES, // max. instances
                  IPTV_BUFFER_SIZE,                  // output buffer size
                  IPTV_BUFFER_SIZE,                  // input buffer size
                  0,                        // client time-out
                  NULL);                    // default security attribute
    if (!m_hPipe)
    {
        LogError("CreateNamedPipe failed");
        return false;
    }
    /* Load the VLC engine */
    m_vlc = libvlc_new (0, NULL);
    if (!m_vlc)
    {
        LogError("libvlc_new failed");
        return false;
    }


    // parse input MRL and options
    GetPrivateProfileString("main", "options", "", def_options, sizeof(def_options), m_inifile);
    GetPrivateProfileString("main", "sout", "file{mux=ts,dst=\"\\%s\"}", def_sout, sizeof(def_sout), m_inifile);

    if (strlen(def_options) > 0)
    {
        strcat_s(m_fn, " ");
        strcat_s(m_fn, def_options);
    }

    LogInfo("Adding media: %s", m_fn);

    int argc;
    m_argv = CommandLineToArgvA(m_fn, &argc);
    m_options = (char**)CoTaskMemAlloc(argc * sizeof(char*));

    int nopt = 0;
    int noremux = -1;
    char *opt_out = 0;
    for (int n = 0; n < argc; n++)
    {
        if (m_argv[n][0] == '-' && m_argv[n][1] == '-')
            m_options[nopt] = m_argv[n] + 2;
        else if (m_argv[n][0] == ':')
            m_options[nopt] = m_argv[n] + 1;
        else
        {
            strncpy(m_input, m_argv[n], sizeof(m_input));
            continue;
        }

        if (strncmp(m_options[nopt], "sout", 4) == 0)			// disable direct ts dump if there are any sout options
            noremux = 0;

        if (strncmp(m_options[nopt], "sout=", 5) == 0)
            opt_out = m_options[nopt] + 5;
        else if (strncmp(m_options[nopt], "exec=", 5) == 0)
            m_exec = m_options[nopt] + 5;
        else if (strncmp(m_options[nopt], "exec-opt=", 9) == 0)
            m_exec_opt = m_options[nopt] + 9;
        else if (strncmp(m_options[nopt], "exec-wait=", 10) == 0)
            m_exec_wait = atoi(m_options[nopt] + 10);
        else if (strncmp(m_options[nopt], "no-remux", 8) == 0 && noremux == -1)
            noremux = 1;
        else
            nopt++;
    }


    char t_output[512];
    if (noremux == 1)
    {
        sprintf_s(m_dump_opt, "ts-dump-file=%s", m_pipename);
        m_options[nopt++] = m_dump_opt;
        strcpy_s(m_output, "#dummy");
    }
    else
    {
        sprintf_s(t_output, def_sout, m_pipename);
        if (opt_out)
            sprintf_s(m_output, "%s:%s", opt_out, t_output);
        else
            sprintf_s(m_output, "#%s", t_output);
    }

    LogDebug("input=%s", m_input);
    LogDebug("output=%s", m_output);
    for (int i = 0; i < nopt; i++)
        LogDebug("options[%d]=%s", i, m_options[i]);

    if (libvlc_vlm_add_broadcast(m_vlc, "vlc_ds_stream", m_input, m_output, nopt, m_options, true, 0) != 0)
    {
        LogError("libvlc_vlm_add_broadcast failed");
        return false;
    }
    return true;
}
예제 #18
0
파일: Main.cpp 프로젝트: Mateuus/devsrc
// This function called by engine before main app window created, before any IO initialized.
void game::PreInit()
{
	//MessageBox(NULL,"ถ้าคุณเจอคำว่า 'โปรแกรมกำลังอัพเดท โปรดเข้าเกมใหม่อีกครั้ง' ให้ลบโปรแกรมพวก Hamachi ออก","Allright Client",MB_OK);
#ifdef FINAL_BUILD // Client
	//runantihack();
	//Sleep(5000);
#else
	//Sleep(5000);
#endif
	//antihack();
	//@FOR STEAM- SetCurrentDirectory("Z:\\tsg\\WarOnline\\bin\\");

	u_srand(GetTickCount());

	g_HardwareInfo.Grab();

	win::hWinIcon  = NULL;
	win::szWinName = GetBuildVersionString();
	//#ifdef FINAL_BUILD
#ifdef Q_PROTECT
	//antihack();
#endif

#ifdef FINAL_BUILD
	win::hWinIcon = ::LoadIcon(win::hInstance, MAKEINTRESOURCE(IDI_WARZ));
	if(strstr(__r3dCmdLine, "-UDBRASILMTs") == NULL && strstr(__r3dCmdLine, "-gna") == NULL)
	{
		MessageBox(NULL, "Please run Undead Launcher launcher.", g_szApplicationName, MB_OK);
		ExitProcess(0);
	}
#endif	

#ifdef _DEBUG
	r3dOutToLog("cmd: %s\n", __r3dCmdLine);
#endif	
	// parse command line
	int argc = 0;
	char** argv = CommandLineToArgvA(__r3dCmdLine, &argc);
	for(int i=0; i<argc; i++) 
	{
		if(strcmp(argv[i], "-loginudbrasil157mts") == 0 && (i + 1) < argc)
		{
			r3dscpy(Login_PassedUser, argv[++i]);
			continue;
		}
		if(strcmp(argv[i], "-pwdudbrasilpwdmts") == 0 && (i + 1) < argc)
		{
			r3dscpy(Login_PassedPwd, argv[++i]);
			continue;
		}
		if(strcmp(argv[i], "-UDBRAuth") == 0 && (i + 1) < argc)
		{
			r3dscpy(Login_PassedAuth, argv[++i]);
			continue;
		}

		if(strcmp(argv[i], "-steam") == 0)
		{
			gSteam.IS_ENABLED = true;
			continue;
		}

		if(strcmp(argv[i], "-survey") == 0 && (i + 1) < argc)
		{
			gSurveyOutLink = argv[++i];
			continue;
		}
		//antihack();
#ifndef FINAL_BUILD
#if !DISABLE_PROFILER
		if (strcmp(argv[i], "-profile") == 0)
		{
			if (i + 1 >= argc)
				r3dError("Incorrect syntax for '-profile' option. Use '-profile level_name'");
			strcpy_s(LevelEditName, _countof(LevelEditName), argv[i + 1]);
			//	Set scheduled profile time to -1 to adjust it automatically after level will be loaded
			gScheduledProfileTime = -1.0f;
		}

		if (strcmp(argv[i], "-gprofile") == 0)
		{
			if (i + 1 >= argc)
				r3dError("Incorrect syntax for '-gprofile' option. Use '-gprofile level_name'");

			strcpy_s(LevelEditName, _countof(LevelEditName), argv[i + 1]);

			gProfileD3DFromCommandLine = true;
			gScheduledProfileTime = -1.0f;
		}
#endif

		if (strcmp(argv[i], "-camera") == 0)
		{
			if (i + 1 >= argc)
				r3dError("Incorrect syntax for '-camera' option. Use '-camera camera_spot_name'");

			strcpy_s(initialCameraSpotName, _countof(initialCameraSpotName), argv[i + 1]);
		}
#endif

	}
}
예제 #19
0
	std::string CommandMap::ExecuteCommand(std::string command)
	{
		int numArgs = 0;
		auto args = CommandLineToArgvA((PCHAR)command.c_str(), &numArgs);

		if (numArgs <= 0)
			return "Invalid input";

		auto cmd = FindCommand(args[0]);
		if (!cmd)
			return "Command/Variable not found";

		if ((cmd->Flags & eCommandFlagsRunOnMainMenu) && !ElDorito::Instance().GameHasMenuShown)
		{
			queuedCommands.push_back(command);
			return "Command queued until mainmenu shows";
		}

		if ((cmd->Flags & eCommandFlagsHostOnly) && !ElDorito::Instance().IsHostPlayer())
			return "Only a player hosting a game can use this command";

		std::vector<std::string> argsVect;
		if (numArgs > 1)
		for (int i = 1; i < numArgs; i++)
			argsVect.push_back(args[i]);

		if (cmd->Type == eCommandTypeCommand)
		{
			std::string retInfo;
			cmd->UpdateEvent(argsVect, retInfo); // if it's a command call it and return
			return retInfo;
		}

		std::string previousValue;
		auto updateRet = SetVariable(cmd, (numArgs > 1 ? argsVect[0] : ""), previousValue);

		switch (updateRet)
		{
		case eVariableSetReturnValueError:
			return "Command/Variable not found";
		case eVariableSetReturnValueInvalidArgument:
			return "Invalid value";
		case eVariableSetReturnValueOutOfRange:
			if (cmd->Type == eCommandTypeVariableInt)
				return "Value " + argsVect[0] + " out of range [" + std::to_string(cmd->ValueIntMin) + ".." + std::to_string(cmd->ValueIntMax) + "]";
			if (cmd->Type == eCommandTypeVariableInt64)
				return "Value " + argsVect[0] + " out of range [" + std::to_string(cmd->ValueInt64Min) + ".." + std::to_string(cmd->ValueInt64Max) + "]";
			if (cmd->Type == eCommandTypeVariableFloat)
				return "Value " + argsVect[0] + " out of range [" + std::to_string(cmd->ValueFloatMin) + ".." + std::to_string(cmd->ValueFloatMax) + "]";

			return "Value " + argsVect[0] + " out of range [this shouldn't be happening!]";
		}

		// special case for blanking strings
		if (cmd->Type == eCommandTypeVariableString && numArgs > 1 && argsVect[0].empty())
			cmd->ValueString = "";

		if (numArgs <= 1)
			return previousValue;

		if (!cmd->UpdateEvent)
			return previousValue + " -> " + cmd->ValueString; // no update event, so we'll just return with what we set the value to

		std::string retVal;
		auto ret = cmd->UpdateEvent(argsVect, retVal);

		if (!ret) // error, revert the variable
			this->SetVariable(cmd, previousValue, std::string());

		if (retVal.length() <= 0)
			return previousValue + " -> " + cmd->ValueString;

		return retVal;
	}