Ejemplo n.º 1
0
void OpenConsole() 
{
	COORD csize;
	CONSOLE_SCREEN_BUFFER_INFO csbiInfo; 
	SMALL_RECT srect;
	char buf[256];

	//dont do anything if we're already attached
	if (hConsole) return;

	//attach to an existing console (if we can; this is circuitous because AttachConsole wasnt added until XP)
	//remember to abstract this late bound function notion if we end up having to do this anywhere else
	bool attached = false;
	HMODULE lib = LoadLibrary("kernel32.dll");
	if(lib)
	{
		typedef BOOL (WINAPI *_TAttachConsole)(DWORD dwProcessId);
		_TAttachConsole _AttachConsole  = (_TAttachConsole)GetProcAddress(lib,"AttachConsole");
		if(_AttachConsole)
		{
			if(_AttachConsole(-1))
				attached = true;
		}
		FreeLibrary(lib);
	}

	//if we failed to attach, then alloc a new console
	if(!attached)
	{
		AllocConsole();
	}

	hConsole = GetStdHandle(STD_OUTPUT_HANDLE);

	//redirect stdio
	long lStdHandle = (long)hConsole;
	int hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
	if(hConHandle == -1)
		return; //this fails from a visual studio command prompt
	
	FILE *fp = _fdopen( hConHandle, "w" );
	*stdout = *fp;
	//and stderr
	*stderr = *fp;

	memset(buf,0,256);
	sprintf(buf,"%s OUTPUT", DESMUME_NAME_AND_VERSION);
	SetConsoleTitle(TEXT(buf));
	csize.X = 60;
	csize.Y = 800;
	SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), csize);
	GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbiInfo);
	srect = csbiInfo.srWindow;
	srect.Right = srect.Left + 99;
	srect.Bottom = srect.Top + 64;
	SetConsoleWindowInfo(GetStdHandle(STD_OUTPUT_HANDLE), TRUE, &srect);
	SetConsoleCP(GetACP());
	SetConsoleOutputCP(GetACP());
	if(attached) printlog("\n");
	printlog("%s\n",DESMUME_NAME_AND_VERSION);
	printlog("- compiled: %s %s\n\n",__DATE__,__TIME__);


}
Ejemplo n.º 2
0
ADAPTER_LIST CSocketApp::GetMacInfo(void)
{
	USES_CONVERSION;
	ADAPTER_LIST AdapterList;
	
	PIP_ADAPTER_INFO pIpAdapterInfo;
    PIP_ADAPTER_INFO pAdapter = NULL;
    DWORD dwRetVal = 0;

    ULONG ulOutBufLen = sizeof (IP_ADAPTER_INFO);
    pIpAdapterInfo = (IP_ADAPTER_INFO *) malloc(sizeof (IP_ADAPTER_INFO));
    if (pIpAdapterInfo == NULL) {
		AllocConsole();
        _cprintf("Error allocating memory needed to call GetAdaptersinfo\n");
        FreeConsole();
		return AdapterList;
    }
    if (GetAdaptersInfo(pIpAdapterInfo, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW) {
        free(pIpAdapterInfo);
        pIpAdapterInfo = (IP_ADAPTER_INFO *) malloc(ulOutBufLen);
        if (pIpAdapterInfo == NULL) {
			AllocConsole();
            _cprintf("Error allocating memory needed to call GetAdaptersinfo\n");
			FreeConsole();
            return AdapterList;
        }
    }

    if ((dwRetVal = GetAdaptersInfo(pIpAdapterInfo, &ulOutBufLen)) == NO_ERROR) {
        pAdapter = pIpAdapterInfo;
        while (pAdapter) {
			ADAPTER_INFO AdapterInfo;

			AdapterInfo.sName = A2W(pAdapter->AdapterName);
			AdapterInfo.sDesc = A2W(pAdapter->Description);
			AdapterInfo.uType = pAdapter->Type;

			CString sMacAddr;
			CString sTemp;
			for (DWORD i = 0; i < pAdapter->AddressLength; i++)
			{
				sTemp.Format(_T("%02x"), pAdapter->Address[i]);
				sMacAddr += sTemp;
			}
			AdapterInfo.sMac = sMacAddr;

			IP_ADDR_STRING *pIpAddrString =&(pAdapter->IpAddressList);
			do 
			{
				AdapterInfo.sIPs.push_back(A2W(pIpAddrString->IpAddress.String));
				pIpAddrString = pIpAddrString->Next;
			} while (pIpAddrString);
			pAdapter = pAdapter->Next;

			AdapterList.push_back(AdapterInfo);
        }
    } else {
		AllocConsole();
        _cprintf("GetAdaptersInfo failed with error: %d\n", dwRetVal);
		FreeConsole();
    }
    if (pIpAdapterInfo)
        free(pIpAdapterInfo);
	return AdapterList;
}
Ejemplo n.º 3
0
__declspec(dllexport) XMPIN* XMPIN_GetInterface(UINT32 version, void* ifproc) {
	AllocConsole();
	if (version != 1) return NULL;
	return &vgmstream_intf;
}
Ejemplo n.º 4
0
int main (int argc, char **argv)
{
	int ret = 1;


	/* Create application instance */
	QApplication qapp(argc, argv);

#ifdef Q_OS_WIN
	AllocConsole();
	freopen("CONOUT$", "wb", stdout);
#endif

	/* Print the version number */
	displayVersion();

	// scan command line arguments for a specified config file
	QString configFile;
	for (int i = 0; i < argc; i++)
	{
		if (argv[i][0] == '-' && argv[i][1] == 'o')
			configFile = argv[i + 1];
	}
	
	/* Create the session manager object with an optional user-specified
	 * configuration filename */
	SessionManager* sessionMgr = new SessionManager(configFile);

	// For now this will suffice
	pSEQPrefs = sessionMgr->preferences();

	// TODO: do something with this junk
	showeq_params = new ShowEQParams;

	QString section = "Interface";
	/* Allow map depth filtering */
	showeq_params->retarded_coords  = pSEQPrefs->getPrefBool("RetardedCoords", section, 0);
	showeq_params->systime_spawntime = pSEQPrefs->getPrefBool("SystimeSpawntime", section, false);
	showeq_params->pvp = pSEQPrefs->getPrefBool("PvPTeamColoring", section, false);
	showeq_params->deitypvp = pSEQPrefs->getPrefBool("DeityPvPTeamColoring", section, false);
	showeq_params->keep_selected_visible = pSEQPrefs->getPrefBool("KeepSelected", section, true);
	showeq_params->useUpdateRadius = pSEQPrefs->getPrefBool("UseUpdateRadius", section, false);

	section = "Misc";
	showeq_params->fast_machine = pSEQPrefs->getPrefBool("FastMachine", section, true);
	showeq_params->createUnknownSpawns = pSEQPrefs->getPrefBool("CreateUnknownSpawns", section, true);

	showeq_params->walkpathrecord = pSEQPrefs->getPrefBool("WalkPathRecording", section, false);
	showeq_params->walkpathlength = pSEQPrefs->getPrefInt("WalkPathLength", section, 25);
	/* Tells SEQ whether or not to display casting messages (Turn this off if you're on a big raid) */

	section = "SpawnList";
	showeq_params->showRealName = pSEQPrefs->getPrefBool("ShowRealName", section, false);

	/* Different files for different kinds of raw data */

	section = "SaveState";
	showeq_params->saveZoneState = pSEQPrefs->getPrefBool("ZoneState", section, 1);
	showeq_params->savePlayerState = pSEQPrefs->getPrefBool("PlayerState", section, 1);
	showeq_params->saveSpawns = pSEQPrefs->getPrefBool("Spawns", section, false);
	showeq_params->saveSpawnsFrequency = pSEQPrefs->getPrefInt("SpawnsFrequency", section, (120 * 1000));
	showeq_params->restorePlayerState = false;
	showeq_params->restoreZoneState = false;
	showeq_params->restoreSpawns = false;
	showeq_params->saveRestoreBaseFilename = sessionMgr->dataLocationMgr()->findWriteFile("tmp", pSEQPrefs->getPrefString("BaseFilename", section, "last")).absFilePath();
	showeq_params->filterZoneDataLog = 0;
	
#ifndef Q_OS_WIN
	parseArguments(argc, argv);		
#endif
#ifdef Q_WS_X11
	QColor::setAllowX11ColorNames(true);
#endif

	/* Create the main interface. */
	EQInterface* mainInterface = new EQInterface(sessionMgr);
	qapp.setMainWidget(mainInterface);
	
	/* Start the main program loop */
	ret = qapp.exec();
	
	// Clean up
	delete mainInterface;
	delete sessionMgr;
	
	return ret;
}
Ejemplo n.º 5
0
int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nShowCmd)
{
    CONTEXT("WinMain()");

    BOOL any_desktop_running = IsAnyDesktopRunning();

    BOOL startup_desktop;

    // strip extended options from the front of the command line
    String ext_options;

    while(*lpCmdLine == '-') {
        while(*lpCmdLine && !_istspace((unsigned)*lpCmdLine))
            ext_options += *lpCmdLine++;

        while(_istspace((unsigned)*lpCmdLine))
            ++lpCmdLine;
    }

     // command line option "-install" to replace previous shell application with ROS Explorer
    if (_tcsstr(ext_options,TEXT("-install"))) {
        // install ROS Explorer into the registry
        TCHAR path[MAX_PATH];

        int l = GetModuleFileName(0, path, COUNTOF(path));
        if (l) {
            HKEY hkey;

            if (!RegOpenKey(HKEY_LOCAL_MACHINE, TEXT("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon"), &hkey)) {

                ///@todo save previous shell application in config file

                RegSetValueEx(hkey, TEXT("Shell"), 0, REG_SZ, (LPBYTE)path, l*sizeof(TCHAR));
                RegCloseKey(hkey);
            }

            if (!RegOpenKey(HKEY_CURRENT_USER, TEXT("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon"), &hkey)) {

                ///@todo save previous shell application in config file

                RegSetValueEx(hkey, TEXT("Shell"), 0, REG_SZ, (LPBYTE)TEXT(""), l*sizeof(TCHAR));
                RegCloseKey(hkey);
            }
        }

        HWND shellWindow = GetShellWindow();

        if (shellWindow) {
            DWORD pid;

            // terminate shell process for NT like systems
            GetWindowThreadProcessId(shellWindow, &pid);
            HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);

             // On Win 9x it's sufficient to destroy the shell window.
            DestroyWindow(shellWindow);

            if (TerminateProcess(hProcess, 0))
                WaitForSingleObject(hProcess, INFINITE);

            CloseHandle(hProcess);
        }

        startup_desktop = TRUE;
    } else {
         // create desktop window and task bar only, if there is no other shell and we are
         // the first explorer instance
         // MS Explorer looks additionally into the registry entry HKCU\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\shell,
         // to decide wether it is currently configured as shell application.
        startup_desktop = !any_desktop_running;
    }


    bool autostart = !any_desktop_running;

    // disable autostart if the SHIFT key is pressed
    if (GetAsyncKeyState(VK_SHIFT) < 0)
        autostart = false;

#ifdef _DEBUG    //MF: disabled for debugging
    autostart = false;
#endif

    // If there is given the command line option "-desktop", create desktop window anyways
    if (_tcsstr(ext_options,TEXT("-desktop")))
        startup_desktop = TRUE;
#ifndef ROSSHELL
    else if (_tcsstr(ext_options,TEXT("-nodesktop")))
        startup_desktop = FALSE;

    // Don't display cabinet window in desktop mode
    if (startup_desktop && !_tcsstr(ext_options,TEXT("-explorer")))
        nShowCmd = SW_HIDE;
#endif

    if (_tcsstr(ext_options,TEXT("-noautostart")))
        autostart = false;
    else if (_tcsstr(ext_options,TEXT("-autostart")))
        autostart = true;

#ifndef __WINE__
    if (_tcsstr(ext_options,TEXT("-console"))) {
        AllocConsole();

        _dup2(_open_osfhandle((long)GetStdHandle(STD_INPUT_HANDLE), _O_RDONLY), 0);
        _dup2(_open_osfhandle((long)GetStdHandle(STD_OUTPUT_HANDLE), 0), 1);
        _dup2(_open_osfhandle((long)GetStdHandle(STD_ERROR_HANDLE), 0), 2);

        g_Globals._log = _fdopen(1, "w");
        setvbuf(g_Globals._log, 0, _IONBF, 0);

        LOG(TEXT("starting explorer debug log\n"));
    }
#endif


    if (startup_desktop) {
         // hide the XP login screen (Credit to Nicolas Escuder)
         // another undocumented event: "Global\\msgina: ReturnToWelcome"
        if (!SetShellReadyEvent(TEXT("msgina: ShellReadyEvent")))
            SetShellReadyEvent(TEXT("Global\\msgina: ShellReadyEvent"));
    }
#ifdef ROSSHELL
    else
        return 0;    // no shell to launch, so exit immediatelly
#endif


    if (!any_desktop_running) {
        // launch the shell DDE server
        if (g_SHDOCVW_ShellDDEInit)
            (*g_SHDOCVW_ShellDDEInit)(TRUE);
    }


    bool use_gdb_stub = false;    // !IsDebuggerPresent();

    if (_tcsstr(ext_options,TEXT("-debug")))
        use_gdb_stub = true;

    if (_tcsstr(ext_options,TEXT("-break"))) {
        LOG(TEXT("debugger breakpoint"));
        __debugbreak();
    }

#ifdef _M_IX86
    // activate GDB remote debugging stub if no other debugger is running
    if (use_gdb_stub) {
        LOG(TEXT("waiting for debugger connection...\n"));

        initialize_gdb_stub();
    }
#endif

    g_Globals.init(hInstance);

    // initialize COM and OLE before creating the desktop window
    OleInit usingCOM;

    // init common controls library
    CommonControlInit usingCmnCtrl;

    g_Globals.read_persistent();

    if (startup_desktop) {
        WaitCursor wait;

        g_Globals._desktops.init();

        g_Globals._hwndDesktop = DesktopWindow::Create();
#ifdef _USE_HDESK
        g_Globals._desktops.get_current_Desktop()->_hwndDesktop = g_Globals._hwndDesktop;
#endif
    }

    if (_tcsstr(ext_options,TEXT("-?"))) {
        MessageBoxA(g_Globals._hwndDesktop,
            "/e        open cabinet window in explorer mode\r\n"
            "/root        open cabinet window in rooted mode\r\n"
            "/mdi        open cabinet window in MDI mode\r\n"
            "/sdi        open cabinet window in SDI mode\r\n"
            "\r\n"
            "-?        display command line options\r\n"
            "\r\n"
            "-desktop        start in desktop mode regardless of an already running shell\r\n"
            "-nodesktop    disable desktop mode\r\n"
            "-explorer        display cabinet window regardless of enabled desktop mode\r\n"
            "\r\n"
            "-install        replace previous shell application with ROS Explorer\r\n"
            "\r\n"
            "-noautostart    disable autostarts\r\n"
            "-autostart    enable autostarts regardless of debug build\r\n"
            "\r\n"
            "-console        open debug console\r\n"
            "\r\n"
            "-debug        activate GDB remote debugging stub\r\n"
            "-break        activate debugger breakpoint\r\n",
            "ROS Explorer - command line options", MB_OK);
    }

    Thread* pSSOThread = NULL;

    if (startup_desktop) {
        // launch SSO thread to allow message processing independent from the explorer main thread
        pSSOThread = new SSOThread;
        pSSOThread->Start();
    }

    /**TODO launching autostart programs can be moved into a background thread. */
    if (autostart) {
        const char* argv[] = {"", "s"};    // call startup routine in SESSION_START mode
        startup(2, argv);
    }

#ifndef ROSSHELL
    if (g_Globals._hwndDesktop)
        g_Globals._desktop_mode = true;
#endif


    int ret = explorer_main(hInstance, lpCmdLine, nShowCmd);


    // write configuration file
    g_Globals.write_persistent();

    if (pSSOThread) {
        pSSOThread->Stop();
        delete pSSOThread;
    }

    if (!any_desktop_running) {
        // shutdown the shell DDE server
        if (g_SHDOCVW_ShellDDEInit)
            (*g_SHDOCVW_ShellDDEInit)(FALSE);
    }

    return ret;
}
Ejemplo n.º 6
0
int WINAPI
WinMain(
	__in HINSTANCE hInstance,
	__in HINSTANCE hPrevInstance,
	__in LPSTR lpCmdLine,
	__in int nCmdShow)
{

	Mem::init(512 * 1024);

	DebugClient::Init();
	DebugClient::RegisterExceptionFilter();

	HMODULE hUser32 = LoadLibrary(L"user32.dll");
	typedef BOOL(*SetProcessDPIAwareFunc)();
	SetProcessDPIAwareFunc setDPIAware = NULL;
	if (hUser32) setDPIAware = (SetProcessDPIAwareFunc)GetProcAddress(hUser32, "SetProcessDPIAware");
	if (setDPIAware) setDPIAware();
	if (hUser32) FreeLibrary(hUser32);
	if (AllocConsole()) {
		freopen("CONOUT$", "w", stdout);
		SetConsoleTitle(L"Debug Console");
		SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_RED);
	}

	// set std::cout to use custom streambuf
	outbuf ob;
	std::streambuf *sb = std::cout.rdbuf(&ob);

	std::cout << "Started" << std::endl;

	/*int msgboxID = MessageBox(
		NULL,
		(LPCWSTR)L"Koku",
		(LPCWSTR)L"Dialog",
		MB_ICONWARNING | MB_CANCELTRYCONTINUE | MB_DEFBUTTON2
	);*/

	WSADATA wsaData;

    #define DEFAULT_PORT "5900"

	struct addrinfo *result = NULL, *ptr = NULL, hints;

	int iResult;

	// Initialize Winsock
	iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
	if (iResult != 0) {
		std::cout << "WSAStartup failed: failed: " << iResult;
		return 1;
	}

	ZeroMemory(&hints, sizeof(hints));
	hints.ai_family = AF_INET;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_protocol = IPPROTO_TCP;
	hints.ai_flags = AI_PASSIVE;

	// Resolve the local address and port to be used by the server
	iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
	if (iResult != 0) {
		std::cout << "getaddrinfo failed: " << iResult;
		//Sleep(3000);
		//std::cout.rdbuf(sb);
		WSACleanup();
		return 1;
	}

	SOCKET ListenSocket = INVALID_SOCKET;
	// Create a SOCKET for the server to listen for client connections
	ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);

	if (ListenSocket == INVALID_SOCKET) {
		std::cout << "Error at socket(): " << WSAGetLastError();
		freeaddrinfo(result);
		WSACleanup();
		return 1;
	}

	// Setup the TCP listening socket
	iResult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen);
	if (iResult == SOCKET_ERROR) {
		std::cout << "bind failed with error: " << WSAGetLastError();
		freeaddrinfo(result);
		closesocket(ListenSocket);
		WSACleanup();
		return 1;
	}

	freeaddrinfo(result);

	VncServer::init();
	std::cout << "Initialized" << std::endl;
	if (ListenSocket != INVALID_SOCKET)
	{
		std::cout << "Socket success" << std::endl;
		WSocket::tcpDisableDelay(ListenSocket, true);
		WSocket::tcpSetKeepAlive(ListenSocket, true, 5 * 60 * 1000, 5 * 1000);
		VncServer::start(ListenSocket);
	}
	std::cout << "Shutting down" << std::endl;
	WSocket::tcpClose(ListenSocket);
	VncServer::uninit();

	std::cout << "Goodbye!" << std::endl;
	Sleep(3000);
	std::cout.rdbuf(sb);
	return 0;
}
Ejemplo n.º 7
0
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	static HWND		shwnd;
	static HDC		hdc;
	static HGLRC	hglrc, hglrc_legacy;
	static Engine	altEngine;
	static POINT	center;

	switch (message)
	{
	case WM_CREATE:
		AllocConsole();
		RedirectIOToConsole();
		SetTimer ( hwnd, TICK_TIMER, 16, NULL );
		hdc = GetDC(hwnd);
		setupPixelFormat(hdc);
#ifndef DIRECTX
		hglrc_legacy = wglCreateContext(hdc);
		wglMakeCurrent(hdc, hglrc_legacy);

		//opengl 2.0
		hglrc = hglrc_legacy;

#endif
		shwnd = hwnd;
		altEngine.init(&shwnd, &hdc);
		return 0;

	case WMU_RENDER:
		altEngine.render();
		return 0;

	case WM_TIMER:
		switch(wParam)
		{
		case TICK_TIMER:
			altEngine.step();
			break;
		}
		return 0;

	case WM_MOUSEMOVE:
		{

		}
		return 0;
	case WM_SIZE:
		{
			int	width, height;

			width	= LOWORD(lParam);
			height	= HIWORD(lParam);
			center.x = width / 2;
			center.y = height / 2;
			altEngine.resize(width, height);
		}
		return 0;

	case WM_SYSCOMMAND:
		switch(wParam)
		{
		case SC_SCREENSAVE:
		case SC_MONITORPOWER:
			return 0;
		}
		break;

	case WM_DESTROY:
#ifndef DIRECTX
		if (hglrc)
		{
			wglMakeCurrent(NULL, NULL);
			wglDeleteContext(hglrc);
			ReleaseDC(hwnd, hdc);
		}
#endif
		altEngine.destroy();
		PostQuitMessage(0);
		return 0;
	}
	return DefWindowProc (hwnd, message, wParam, lParam);
}
Ejemplo n.º 8
0
/////////////////////////////////////////////////
// System-Console
TSysConsole::TSysConsole(){
  Ok=(AllocConsole()!=0);
  IAssert(Ok);
  hStdOut=GetStdHandle(STD_OUTPUT_HANDLE);
  IAssert(hStdOut!=INVALID_HANDLE_VALUE);
}
Ejemplo n.º 9
0
/**   after we define and instantiate our programs components   **/
int WINAPI WinMain(HINSTANCE hThisInstance, HINSTANCE hPrevInstance,
                    LPSTR lpszArgument, int nCmdShow)
{
    UNREFERENCED(lpszArgument);
    UNREFERENCED(hPrevInstance);
    /**   here messages to the application are saved   **/
    MSG messages;

   /**********************************************
    *                                            *
    *   create the main window - width, height   *
    *                                            *
    **********************************************/
    HWND hwnd = createMainWin(hThisInstance, 400, 600);

    /**   if main window handle is invalid alert and quit  **/
    if(!hwnd){
        // using wide string for the Unicode crowd
        MessageBox(NULL, _T(" can not create main window "),
                         _T(" WinBreakoutC++ "), MB_OK);

        /**   this in itself will end the program   **/
        PostQuitMessage(0);
    }

    /**   make the window visible on the screen   **/
    ShowWindow(hwnd, nCmdShow);

/**   some debugging code   **/
/**   with the following statements a Debug build target
      allows us to use printf and cout/printf to display data     **/
#ifdef _DEBUG
    if(!AllocConsole()){
        MessageBox(NULL, _T(" can not create console window "),
                         _T(" WinBreakoutC++ "), MB_OK);
    }
    freopen("CONOUT$","wb",stdout);  // reopen stout handle as console window output
#endif

    /**   get our windows rectangle so we can size things   **/
    GetClientRect(hwnd, &mwinRect);

    createBall(20, mwinRect.right / 2, mwinRect.bottom / 2);

    // TODO:  this needs to be from top with a re-sizable window
    createPaddle(mwinRect.bottom - 60, 40, 10);

    createWall(50);

    /**   run the message loop                        **/
    /**   It will run until GetMessage() returns 0.   **/
    /**   argument two is null we are listening to    **/
    /**   the thread not the window.  we get all      **/
    /**   messages.  this loop is the heart of our    **/
    /**   program pumping messages not blood          **/

    /**   messages is MSG structure that windows passes       **/
    /**   messages to our program defined in top of WinMain   **/
    while(GetMessage(&messages, NULL, 0, 0))
    {
        /**   Translate virtual-key messages into character messages   **/
        TranslateMessage(&messages);

        /**   Send message to WindowProcedure   **/
        DispatchMessage(&messages);
    }

    /**   The program return-value is 0                   **/
    /**   - The value that PostQuitMessage() gave was 0   **/
    /**   that's all folks                                **/
    return messages.wParam;
}
Ejemplo n.º 10
0
void CreateConsole()
{
    AllocConsole();
    *stdout = *_fdopen(_open_osfhandle((long)GetStdHandle(STD_OUTPUT_HANDLE), _O_TEXT), "w");
    setvbuf(stdout, NULL, _IONBF, 0);
}
Ejemplo n.º 11
0
int main()
{
	INPUT_RECORD	irBuffer;
	memset(&irBuffer,0,sizeof(INPUT_RECORD));
	DWORD	dwResult;
	
	AllocConsole();
	
	hIn = GetStdHandle(STD_INPUT_HANDLE);
	g_hOut = GetStdHandle(STD_OUTPUT_HANDLE);

	SetMonitorSize( SCREEN_TEXT_SIZE_X, SCREEN_TEXT_SIZE_Y );

	InitMyLog();
	
	char szNationName[100] = {0,} ;//021007 lsw
	if( GetPrivateProfileString( "NATION_SET", "NATION_NAME", "" , szNationName, 50,PROXY_SERVER_INI_ ) )
	{
		bool bIsFree = (bool)GetPrivateProfileInt( "NATION_SET", "BETA_SERVER", 0, PROXY_SERVER_INI_ );
		if(!LocalMgr.InitVersion(szNationName,bIsFree)){return false;}
	}
	else
	{
		return false;
	}

	if( !StartProxyServer() )
	{
		goto FinishProxyServer;
	}

	g_pINet->ResumeTimer( 4 );
	g_pINet->ResumeTimer( 5 );
	g_pINet->ResumeTimer( 6 );

	while ( g_pServerTable->IsServerRunning() )
	{
		ReadConsoleInput(hIn,&irBuffer,1,&dwResult);
	
		if (irBuffer.EventType == KEY_EVENT)
		{
			if (irBuffer.Event.KeyEvent.bKeyDown)
			{
				switch ( irBuffer.Event.KeyEvent.wVirtualKeyCode )
				{
				case VK_ESCAPE:
					{
						if( MessageBox( NULL, "Are you sure to DESTROY this Proxy server?", "IMPORTANT", MB_YESNO ) == IDYES )
							g_pServerTable->DestroyServer( FINISH_TYPE_NORMAL );
					}break;
				case VK_F1:
					{
						SetEvent(g_pProxy->hKeyEvent[0]);
					}break;
				case VK_F2:
					{
						SetEvent(g_pProxy->hKeyEvent[2]);
					}break;
				case VK_F3:
					{
						// Decrese Max User
						SetEvent(g_pProxy->hKeyEvent[7]);
					}break;
				case VK_F4:
					{
						// Increse Max User
						SetEvent(g_pProxy->hKeyEvent[6]);
					}break;
					
				case VK_F5:
					{
						if ( g_pServerTable->ToggleUserAcceptAllowed() == true )
						{
							MyLog( LOG_NORMAL, "USER ACCEPT ALLOWED by Key Event" );
						}
						else 
						{
							MyLog( LOG_NORMAL, "USER ACCEPT STOPED by Key Event" );
						}
					}break;
				case VK_F6:
					{
						// Increse Limit
						SetEvent(g_pProxy->hKeyEvent[4]);	
					}break;
				case VK_F7:
					{
						// Decrese Limit
						SetEvent(g_pProxy->hKeyEvent[5]);
					}break;
				case VK_F8:
					{
						// Increse Limit
						//SetEvent(g_pProxy->hKeyEvent[4]);	
						//if( MessageBox( NULL, "WARNING!!! Are you sure Close One AgentServer?", "IMPORTANT", MB_YESNO ) == IDYES )
						if( MessageBox( NULL, "WARNING!!! Are you sure Close All AgentServer?", "IMPORTANT", MB_YESNO ) == IDYES )//020822 lsw
							DestroyAgent();
					}break;
				case VK_F9:
					{ 
						if( MessageBox( NULL, "WARNING!!! Are you sure to DESTROY All DBDemon?", "IMPORTANT", MB_YESNO ) == IDYES )
							DestroyAllDBDemon();
					}break;
				case VK_F10:
					{
						if( MessageBox( NULL, "WARNING!!! Are you sure to DESTROY ALL Map SERVERS?", "IMPORTANT", MB_YESNO ) == IDYES )
							DestroyAllMapserver();
							//SetEvent(g_pProxy->hKeyEvent[1]);
					}break;
				case VK_F11:
					{
						MyLog( LOG_JUST_DISPLAY, " " );
						MyLog( LOG_JUST_DISPLAY, "Attempt all disconnected Listener....." );
						MyLog( LOG_JUST_DISPLAY, " " );
						g_pRMTable->ConnectAllDisconnectedListener();
					}break;
				case VK_F12:
					{
						g_pServerTable->ShowListenerStatus();
					}break;
				default:break;
				}
			}
		}
	}

FinishProxyServer:
	
	MyLog( LOG_NORMAL, "Deleting ProxyServer Resources..." );
	EndProxyServer();
	MyLog( LOG_NORMAL, "*** PROXY SERVER Finished Successfully." );
	FreeMyLog();
	FreeConsole();
	return 0;
}
Ejemplo n.º 12
0
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
	//
	// Console window is required for the program to automatically close when the user quits Steam
	//
	if(AllocConsole())
	{
		FILE* stream = nullptr;
		freopen_s(&stream, "CONOUT$", "w", stdout);
		freopen_s(&stream, "CONOUT$", "w", stderr);
		freopen_s(&stream, "CONIN$", "r", stdin);

		printf("SteamMusicKeys\n\n");
	}

	printf("Searching for Steam...	");
	bool SteamAPI_SteamIsRunning = SteamAPI_IsSteamRunning();

	for(int i = 0; i < STEAMAPI_STEAMISRUNNING_RETRY_COUNT; i++)
	{
		if(SteamAPI_SteamIsRunning = SteamAPI_IsSteamRunning())
		{
			printf("Found!\n");
			break;
		}
		Sleep(STEAMAPI_STEAMISRUNNING_RETRY_DELAY);
	}

	if(!SteamAPI_SteamIsRunning)
	{
		printf("Not Found!\n");
		MessageBox(0,L"ERROR: Could not initialize SteamAPI (Steam is not running)", 0, 0);
		FreeConsole();
		return 1;
	}

	printf("Initializing SteamAPI...\n");
	if(!SteamAPI_Init())
	{
		MessageBox(0, L"ERROR: Could not initialize SteamAPI", 0, 0);
		FreeConsole();
		return 2;
	}

	printf("Initializing Steam Music...\n");
	if(!(IMus = SteamMusic()))
	{
		MessageBox(0, L"ERROR: Could not initialize Steam Music", 0, 0);
		SteamAPI_Shutdown();
		FreeConsole();
		return 3;
	}

	printf("Creating dummy window...\n");
	HWND hWnd = SMK_CreateDummyWindow(hInstance, L"SteamMusicKeys");
	if(!hWnd)
	{
		MessageBox(0, L"ERROR: Could not create dummy window", 0, 0);
		SteamAPI_Shutdown();
		FreeConsole();
		return 4;
	}

	printf("Registering hotkeys...\n");
	SMK_RegisterHotkeys(hWnd);
	printf("Hiding console...\n");
	ShowWindow (GetConsoleWindow(), SW_HIDE);
	SMK_MessageLoop();

	printf("Showing console...\n");
	ShowWindow (GetConsoleWindow(), SW_SHOW);
	printf("Freeing Hotkeys...\n");
	SMK_UnregisterHotkeys(hWnd);
	printf("Freeing SteamAPI\n");
	SteamAPI_Shutdown();
	printf("Freeing Console\n");
	FreeConsole();
	return 0;
}
Ejemplo n.º 13
0
void WINAPI DbgInitLogTo (
    HKEY hKey)
{
    LONG  lReturn;
    DWORD dwKeyType;
    DWORD dwKeySize;
    TCHAR szFile[MAX_PATH] = {0};
    static const TCHAR cszKey[] = TEXT("LogToFile");

    dwKeySize = MAX_PATH;
    lReturn = RegQueryValueEx(
        hKey,                       // Handle to an open key
        cszKey,                     // Subkey name derivation
        NULL,                       // Reserved field
        &dwKeyType,                 // Returns the field type
        (LPBYTE) szFile,            // Returns the field's value
        &dwKeySize);                // Number of bytes transferred

    // create an empty key if it does not already exist
    //
    if (lReturn != ERROR_SUCCESS || dwKeyType != REG_SZ)
       {
       dwKeySize = sizeof(TCHAR);
       lReturn = RegSetValueEx(
            hKey,                   // Handle of an open key
            cszKey,                 // Address of subkey name
            (DWORD) 0,              // Reserved field
            REG_SZ,                 // Type of the key field
            (PBYTE)szFile,          // Value for the field
            dwKeySize);            // Size of the field buffer
       }

    // if an output-to was specified.  try to open it.
    //
    if (m_hOutput != INVALID_HANDLE_VALUE) {
       EXECUTE_ASSERT(CloseHandle (m_hOutput));
       m_hOutput = INVALID_HANDLE_VALUE;
    }
    if (szFile[0] != 0)
       {
       if (!lstrcmpi(szFile, TEXT("Console"))) {
          m_hOutput = GetStdHandle (STD_OUTPUT_HANDLE);
          if (m_hOutput == INVALID_HANDLE_VALUE) {
             AllocConsole ();
             m_hOutput = GetStdHandle (STD_OUTPUT_HANDLE);
          }
          SetConsoleTitle (TEXT("ActiveX Debug Output"));
       } else if (szFile[0] &&
                lstrcmpi(szFile, TEXT("Debug")) &&
                lstrcmpi(szFile, TEXT("Debugger")) &&
                lstrcmpi(szFile, TEXT("Deb")))
          {
            m_hOutput = CreateFile(szFile, GENERIC_WRITE,
                                 FILE_SHARE_READ,
                                 NULL, OPEN_ALWAYS,
                                 FILE_ATTRIBUTE_NORMAL,
                                 NULL);

            if (INVALID_HANDLE_VALUE == m_hOutput &&
                GetLastError() == ERROR_SHARING_VIOLATION)
            {
               TCHAR uniqueName[MAX_PATH] = {0};
               if (SUCCEEDED(DbgUniqueProcessName(szFile, uniqueName)))
               {
                    m_hOutput = CreateFile(uniqueName, GENERIC_WRITE,
                                         FILE_SHARE_READ,
                                         NULL, OPEN_ALWAYS,
                                         FILE_ATTRIBUTE_NORMAL,
                                         NULL);
               }
            }
               
            if (INVALID_HANDLE_VALUE != m_hOutput)
            {
              static const TCHAR cszBar[] = TEXT("\r\n\r\n=====DbgInitialize()=====\r\n\r\n");
              LARGE_INTEGER zero = {0, 0};
              SetFilePointerEx(m_hOutput, zero, NULL, FILE_END);
              DbgOutString (cszBar);
            }
          }
       }
}
Ejemplo n.º 14
0
int main()
{
	RegisterExecutablePlatform(ExePlatformLogin);
	set_exception_handler();
#ifdef _WINDOWS //Starts window minimized on Windows.
	HWND handleWindow;
	AllocConsole();
	handleWindow = FindWindowA("ConsoleWindowClass", nullptr);
	ShowWindow(handleWindow, 2);
#endif

	//Create our error log, is of format login_<number>.log
	time_t current_time = time(nullptr);
	std::stringstream log_name(std::stringstream::in | std::stringstream::out);
#ifdef WIN32
	log_name << ".\\logs\\login_" << (unsigned int)current_time << ".log";
#else
	log_name << "./logs/login_" << (unsigned int)current_time << ".log";
#endif
	server_log = new ErrorLog(log_name.str().c_str());
	server_log->Log(log_debug, "Logging System Init.");

	//Create our subsystem and parse the ini file.
	server.config = new Config();
	server_log->Log(log_debug, "Config System Init.");

	std::string configFile = "login.ini"; 
	ifstream f(configFile.c_str());
	if (f.good())
	{
	}
	else
	{
		f.close();
		server_log->Log(log_debug, "login.ini errors. Incomplete or missing.");
		#ifdef WIN32 //Almost never ran in a terminal on linux, so no need to hold window open to see error.
		server_log->Log(log_debug, "Press any key to close");
		std::getchar();
		#endif
	}

	server.config->Parse("login.ini");

	//Parse auto account creation option.
	if (server.config->GetVariable("options", "auto_account_create").compare("TRUE") == 0)
	{
		server.options.AutoCreate(true);
	}

	//Parse auto account activation option.
	if (server.config->GetVariable("options", "auto_account_activate").compare("TRUE") == 0)
	{
		server.options.AutoActivate(true);
	}

	//Parse failed access log option.
	if (server.config->GetVariable("options", "failed_login_log").compare("TRUE") == 0)
	{
		server.options.LoginFails(true);
	}

	//Parse IP login access log option. For cross checking account/IP "anti cheat/box record"
	if (server.config->GetVariable("options", "good_loginIP_log").compare("TRUE") == 0)
	{
		server.options.LoginGood(true);
	}

	//Parse unregistered allowed option.
	if(server.config->GetVariable("options", "unregistered_allowed").compare("FALSE") == 0)
	{
		server.options.AllowUnregistered(false);
	}

	//Parse trace option.
	if(server.config->GetVariable("options", "trace").compare("TRUE") == 0)
	{
		server.options.Trace(true);
	}

	//Parse trace option.
	if(server.config->GetVariable("options", "world_trace").compare("TRUE") == 0)
	{
		server.options.WorldTrace(true);
	}

	//Parse packet inc dump option.
	if(server.config->GetVariable("options", "dump_packets_in").compare("TRUE") == 0)
	{
		server.options.DumpInPackets(true);
	}

	//Parse packet out dump option.
	if(server.config->GetVariable("options", "dump_packets_out").compare("TRUE") == 0)
	{
		server.options.DumpOutPackets(true);
	}

	//Parse encryption mode option.
	std::string mode = server.config->GetVariable("security", "mode");
	if(mode.size() > 0)
	{
		server.options.EncryptionMode(atoi(mode.c_str()));
	}

	//Parse local network option.
	std::string ln = server.config->GetVariable("options", "local_network");
	if(ln.size() > 0)
	{
		server.options.LocalNetwork(ln);
	}

	//Parse local network option.
	std::string mip = server.config->GetVariable("options", "network_ip");
	if(mip.size() > 0)
	{
		server.options.NetworkIP(mip);
	}

	//Parse local network option.
	std::string pws = server.config->GetVariable("options", "salt");
	if(pws.size() > 0)
	{
		server.options.SetSalt(pws);
	}

	//Parse reject duplicate servers option.
	if(server.config->GetVariable("options", "reject_duplicate_servers").compare("TRUE") == 0)
	{
		server.options.RejectDuplicateServers(true);
	}

	//Parse account table option.
	ln = server.config->GetVariable("schema", "account_table");
	if(ln.size() > 0)
	{
		server.options.AccountTable(ln);
	}

	//Parse access log table option.
	ln = server.config->GetVariable("schema", "access_log_table");
	if (ln.size() > 0)
	{
		server.options.AccountAccessLogTable(ln);
	}

	//Parse world account table option.
	ln = server.config->GetVariable("schema", "world_registration_table");
	if(ln.size() > 0)
	{
		server.options.WorldRegistrationTable(ln);
	}

	//Parse admin world account table option.
	ln = server.config->GetVariable("schema", "world_admin_registration_table");
	if(ln.size() > 0)
	{
		server.options.WorldAdminRegistrationTable(ln);
	}

	//Parse world type table option.
	ln = server.config->GetVariable("schema", "world_server_type_table");
	if(ln.size() > 0)
	{
		server.options.WorldServerTypeTable(ln);
	}

	//Create our DB from options.
	if(server.config->GetVariable("database", "subsystem").compare("MySQL") == 0)
	{
#ifdef EQEMU_MYSQL_ENABLED
		server_log->Log(log_debug, "MySQL Database Init.");
		server.db = (Database*)new DatabaseMySQL(
			server.config->GetVariable("database", "user"),
			server.config->GetVariable("database", "password"),
			server.config->GetVariable("database", "host"),
			server.config->GetVariable("database", "port"),
			server.config->GetVariable("database", "db"));
#endif
	}
	else if(server.config->GetVariable("database", "subsystem").compare("PostgreSQL") == 0)
	{
#ifdef EQEMU_POSTGRESQL_ENABLED
		server_log->Log(log_debug, "PostgreSQL Database Init.");
		server.db = (Database*)new DatabasePostgreSQL(
			server.config->GetVariable("database", "user"),
			server.config->GetVariable("database", "password"),
			server.config->GetVariable("database", "host"),
			server.config->GetVariable("database", "port"),
			server.config->GetVariable("database", "db"));
#endif
	}

	//Make sure our database got created okay, otherwise cleanup and exit.
	if(!server.db)
	{
		server_log->Log(log_error, "Database Initialization Failure.");
		server_log->Log(log_debug, "Config System Shutdown.");
		delete server.config;
		server_log->Log(log_debug, "Log System Shutdown.");
		delete server_log;
		return 1;
	}

	//create our server manager.
	server_log->Log(log_debug, "Server Manager Initialize.");
	server.SM = new ServerManager();
	if(!server.SM)
	{
		//We can't run without a server manager, cleanup and exit.
		server_log->Log(log_error, "Server Manager Failed to Start.");
		server_log->Log(log_debug, "Database System Shutdown.");
		delete server.db;
		server_log->Log(log_debug, "Config System Shutdown.");
		delete server.config;
		server_log->Log(log_debug, "Log System Shutdown.");
		delete server_log;
		return 1;
	}

	//create our client manager.
	server_log->Log(log_debug, "Client Manager Initialize.");
	server.CM = new ClientManager();
	if(!server.CM)
	{
		//We can't run without a client manager, cleanup and exit.
		server_log->Log(log_error, "Client Manager Failed to Start.");
		server_log->Log(log_debug, "Server Manager Shutdown.");
		delete server.SM;
		server_log->Log(log_debug, "Database System Shutdown.");
		delete server.db;
		server_log->Log(log_debug, "Config System Shutdown.");
		delete server.config;
		server_log->Log(log_debug, "Log System Shutdown.");
		delete server_log;
		return 1;
	}

#ifdef WIN32
#ifdef UNICODE
	SetConsoleTitle(L"EQEmu Login Server");
#else
	SetConsoleTitle("EQEmu Login Server");
#endif
#endif

	server_log->Log(log_debug, "Server Started.");
	while(run_server)
	{
		Timer::SetCurrentTime();
		server.CM->Process();
		server.SM->Process();
		Sleep(100);
	}
	server_log->Log(log_debug, "Server Shutdown.");
	server_log->Log(log_debug, "Client Manager Shutdown.");
	delete server.CM;
	server_log->Log(log_debug, "Server Manager Shutdown.");
	delete server.SM;
	server_log->Log(log_debug, "Database System Shutdown.");
	delete server.db;
	server_log->Log(log_debug, "Config System Shutdown.");
	delete server.config;
	server_log->Log(log_debug, "Log System Shutdown.");
	delete server_log;
	return 0;
}
Ejemplo n.º 15
0
void Log::alloc()
{
	AllocConsole();
	freopen("CONOUT$", "w", stdout);
}
Ejemplo n.º 16
0
int main(int argc, char* argv[])
{
	unsigned int width = 0;
	unsigned int height = 0;

	std::locale::global(boost::locale::generator().generate(""));
	boost::filesystem::path::imbue(std::locale());

	if(!parseArgs(argc, argv, &width, &height))
		return 0;

	// only show the console on Windows if HideConsole is false
#ifdef WIN32
	// MSVC has a "SubSystem" option, with two primary options: "WINDOWS" and "CONSOLE".
	// In "WINDOWS" mode, no console is automatically created for us.  This is good, 
	// because we can choose to only create the console window if the user explicitly 
	// asks for it, preventing it from flashing open and then closing.
	// In "CONSOLE" mode, a console is always automatically created for us before we
	// enter main. In this case, we can only hide the console after the fact, which
	// will leave a brief flash.
	// TL;DR: You should compile ES under the "WINDOWS" subsystem.
	// I have no idea how this works with non-MSVC compilers.
	if(!Settings::getInstance()->getBool("HideConsole"))
	{
		// we want to show the console
		// if we're compiled in "CONSOLE" mode, this is already done.
		// if we're compiled in "WINDOWS" mode, no console is created for us automatically;
		// the user asked for one, so make one and then hook stdin/stdout/sterr up to it
		if(AllocConsole()) // should only pass in "WINDOWS" mode
		{
			freopen("CONIN$", "r", stdin);
			freopen("CONOUT$", "wb", stdout);
			freopen("CONOUT$", "wb", stderr);
		}
	}else{
		// we want to hide the console
		// if we're compiled with the "WINDOWS" subsystem, this is already done.
		// if we're compiled with the "CONSOLE" subsystem, a console is already created; 
		// it'll flash open, but we hide it nearly immediately
		if(GetConsoleWindow()) // should only pass in "CONSOLE" mode
			ShowWindow(GetConsoleWindow(), SW_HIDE);
	}
#endif

	//if ~/.emulationstation doesn't exist and cannot be created, bail
	if(!verifyHomeFolderExists())
		return 1;

	//start the logger
	Log::open();
	LOG(LogInfo) << "EmulationStation - v" << PROGRAM_VERSION_STRING << ", built " << PROGRAM_BUILT_STRING;

	//always close the log on exit
	atexit(&onExit);

	Window window;
	ViewController::init(&window);
	window.pushGui(ViewController::get());

	if(!scrape_cmdline)
	{
		if(!window.init(width, height))
		{
			LOG(LogError) << "Window failed to initialize!";
			return 1;
		}

		std::string glExts = (const char*)glGetString(GL_EXTENSIONS);
		LOG(LogInfo) << "Checking available OpenGL extensions...";
		LOG(LogInfo) << " ARB_texture_non_power_of_two: " << (glExts.find("ARB_texture_non_power_of_two") != std::string::npos ? "ok" : "MISSING");

		window.renderLoadingScreen();
	}

	const char* errorMsg = NULL;
	if(!loadSystemConfigFile(&errorMsg))
	{
		// something went terribly wrong
		if(errorMsg == NULL)
		{
			LOG(LogError) << "Unknown error occured while parsing system config file.";
			if(!scrape_cmdline)
				Renderer::deinit();
			return 1;
		}

		// we can't handle es_systems.cfg file problems inside ES itself, so display the error message then quit
		window.pushGui(new GuiMsgBox(&window,
			errorMsg,
			"QUIT", [] { 
				SDL_Event* quit = new SDL_Event();
				quit->type = SDL_QUIT;
				SDL_PushEvent(quit);
			}));
	}

	//run the command line scraper then quit
	if(scrape_cmdline)
	{
		return run_scraper_cmdline();
	}

	//dont generate joystick events while we're loading (hopefully fixes "automatically started emulator" bug)
	SDL_JoystickEventState(SDL_DISABLE);

	// preload what we can right away instead of waiting for the user to select it
	// this makes for no delays when accessing content, but a longer startup time
	ViewController::get()->preload();

	//choose which GUI to open depending on if an input configuration already exists
	if(errorMsg == NULL)
	{
		if(fs::exists(InputManager::getConfigPath()) && InputManager::getInstance()->getNumConfiguredDevices() > 0)
		{
			ViewController::get()->goToStart();
		}else{
			window.pushGui(new GuiDetectDevice(&window, true, [] { ViewController::get()->goToStart(); }));
		}
	}

	//generate joystick events since we're done loading
	SDL_JoystickEventState(SDL_ENABLE);

	int lastTime = SDL_GetTicks();
	bool running = true;

	while(running)
	{
		SDL_Event event;
		while(SDL_PollEvent(&event))
		{
			switch(event.type)
			{
				case SDL_JOYHATMOTION:
				case SDL_JOYBUTTONDOWN:
				case SDL_JOYBUTTONUP:
				case SDL_KEYDOWN:
				case SDL_KEYUP:
				case SDL_JOYAXISMOTION:
				case SDL_TEXTINPUT:
				case SDL_TEXTEDITING:
				case SDL_JOYDEVICEADDED:
				case SDL_JOYDEVICEREMOVED:
					InputManager::getInstance()->parseEvent(event, &window);
					break;
				case SDL_QUIT:
					running = false;
					break;
			}
		}

		if(window.isSleeping())
		{
			lastTime = SDL_GetTicks();
			SDL_Delay(1); // this doesn't need to be accurate, we're just giving up our CPU time until something wakes us up
			continue;
		}

		int curTime = SDL_GetTicks();
		int deltaTime = curTime - lastTime;
		lastTime = curTime;

		// cap deltaTime at 1000
		if(deltaTime > 1000 || deltaTime < 0)
			deltaTime = 1000;

		window.update(deltaTime);
		window.render();
		Renderer::swapBuffers();

		Log::flush();
	}

	while(window.peekGui() != ViewController::get())
		delete window.peekGui();
	window.deinit();

	SystemData::deleteSystems();

	LOG(LogInfo) << "EmulationStation cleanly shutting down.";

	return 0;
}
Ejemplo n.º 17
0
int main(int argc, char** argv) {


#ifdef DEBUGCONSOLE
if(AllocConsole())
{
    freopen("CONOUT$", "wt", stdout);

    SetConsoleTitle("The Outcast : Debug Console");

    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_RED);

}
#endif




	DEBUGPRINT(DEBUGPRINT_LEVEL_OBLIGATORY, DEBUGPRINT_NORMAL, "THE OUTCAST 0.4\n");
	DEBUGPRINT(DEBUGPRINT_LEVEL_OBLIGATORY, DEBUGPRINT_NORMAL, "===============\n");


    DEBUGPRINT(DEBUGPRINT_LEVEL_OBLIGATORY, DEBUGPRINT_NORMAL, "Reading cmd line arguments\n");

    for (int i=1;i<argc;i++) {
        if (!strcmp(argv[i], "sprplayground")) {
        	sprplayground = true;
        }
        #ifndef WIN32
        // linux only arguments:
        if (!strcmp(argv[i], "softwarerenderer")) {
            setenv("LIBGL_ALWAYS_INDIRECT", "1", 1);
        }
        #endif
    }

	DEBUGPRINT(DEBUGPRINT_LEVEL_USEFUL, DEBUGPRINT_NORMAL, "Setting up net\n");
	NetInit();
	DEBUGPRINT(DEBUGPRINT_LEVEL_USEFUL, DEBUGPRINT_NORMAL, "Setting up database\n");
	DBInit();
	DEBUGPRINT(DEBUGPRINT_LEVEL_USEFUL, DEBUGPRINT_NORMAL, "Setting up sound system\n");
	SoundInit(NULL);

	DEBUGPRINT(DEBUGPRINT_LEVEL_USEFUL, DEBUGPRINT_NORMAL, "Setting up windowing system\n");

    win_Init(&argc, argv);
    options.Load();

    win_CreateDisplay();



	DEBUGPRINT(DEBUGPRINT_LEVEL_USEFUL, DEBUGPRINT_NORMAL, "Setting up GL\n");
	GLInit();

	if (!sprplayground) {
	    DEBUGPRINT(DEBUGPRINT_LEVEL_USEFUL, DEBUGPRINT_NORMAL, "Loading skin\n");
	    skin = new Skin;
        skin->Load(options.skin.c_str());
	}


	DEBUGPRINT(DEBUGPRINT_LEVEL_USEFUL, DEBUGPRINT_NORMAL, "Loading mousepointer\n");
	win_SetMousePointer("DEFAULT");

	// game must be inited LAST.
	DEBUGPRINT(DEBUGPRINT_LEVEL_USEFUL, DEBUGPRINT_NORMAL, "Setting up game\n");
	GameInit();



    win_MainLoop();

	return 0;
}
Ejemplo n.º 18
0
Archivo: mew.c Proyecto: redtower/rc
/******************************************************************
 *                     main                                       *
 ******************************************************************/
int WINAPI WinMain( HINSTANCE hInstance,
		    HINSTANCE hPrevInstance,
		    LPSTR     lpCmdLine,
		    int       nCmdShow )
{
  BOOL fLogTime = FALSE;
  BOOL fCompile = TRUE;
  BOOL fInstall = TRUE;
  BOOL fSetup   = FALSE;
  BOOL fQuiet   = FALSE;
  char szPBuf[256];
  char szEPBuf[256];
  char szJPBuf[256];
  char seps[] = " \t";
  char *token;
  char     *pt;
  HMODULE  hModule;

  hInst = hInstance;
  memset( szMeadowVersion, 0, sizeof(szMeadowVersion) );

  token = strtok( lpCmdLine, seps );
  while ( token ){
    if ( ! strcmp(token,"-cd") ||
	 ! strcmp(token,"-nc") )
      fCompile = FALSE;		/* install only (not compile) */
    if ( ! strcmp(token,"-ni") )
      fInstall = FALSE;		/* compile only (not install) */
    if ( ! strcmp(token,"-s") )
      fSetup = TRUE;		/* setup mode */
    if ( ! strcmp(token,"-q") )
      fQuiet = TRUE;		/* quiet mode */
    if ( ! strcmp(token,"-h") ){
      ShowUsage();
      return 0;
    }      
    token = strtok( NULL, seps );
  } /* while ( token ){ */

  /* Setup log module
   * After this, OutputLog function could be used.
   */
  SetupLog( LOGFILE_NAME, TRUE, TRUE, fLogTime, TRUE, 0, fQuiet );

  /* Startup Log Message */
  sprintf(szPBuf,"Mew installer for Win32  Version %s",MEWINST_VERSION);
  OutputLog(szPBuf);
  sprintf(szPBuf,"          Copyright (C) %s  Shuichi Kitaguchi",
	  COPYRIGHT_YEARS);
  OutputLog(szPBuf);
  OutputLog("");

  /* Startup window */
  if (!fQuiet && !DialogBoxParam(hInst,
				 MAKEINTRESOURCE(IDD_TITLE),
				 0, TitleDlgProc, 0)){
      OutputLog("Installation is canceled or title window is failed to create.");
      return -1;
  }
  
  /* Ini file name */
  hModule = GetModuleHandle(NULL);
  GetModuleFileName(hModule,szCurrentPath,sizeof(szCurrentPath));
  if ( (pt = strrchr(szCurrentPath,'\\')) )
    *pt = (char)0;
  sprintf(szIniFile,"%s\\%s",szCurrentPath,MEWINST_DEFAULT);


#if 0  
  /* parent process's console? xxx */
  AllocConsole();
  hConsole = CreateConsoleScreenBuffer( GENERIC_READ|GENERIC_WRITE,
					0,
					NULL,
					CONSOLE_TEXTMODE_BUFFER,
					NULL );
  if ( hConsole == INVALID_HANDLE_VALUE ) goto Error;
  if ( ! SetStdHandle( STD_OUTPUT_HANDLE, hConsole ) ){
    OutputLog("SetStdhandle fails.");
    goto Error;
  }
  if ( ! SetConsoleActiveScreenBuffer( hConsole ) ){
    OutputLog("SetConsoleActiveScreenBuffer fails.");
    goto Error;
  }
#endif

  if ( ! GetEnvironments() ) goto Error;
  if ( ! ReadEnvironments() ) goto Error;
  PrintEnvironments();

  if ( ! CheckFile(MEWINST_DEFAULT) ){
    sprintf(szEPBuf,"[%s] is not found!",MEWINST_DEFAULT);
    sprintf(szJPBuf,"[%s] が見付かりません!",MEWINST_DEFAULT);
    BilErrorMessageBox( szEPBuf, szJPBuf );
    goto Error;
  }
  /*
  if ( ! CheckFile("mew.dot.emacs") ){
    BilErrorMessageBox( "Archive Extraction Error!\nCheck your archiver program(support long filename?).",
			"アーカイブの解凍に失敗しています\n解凍プログラムがロングファイルネームをサポートしているか、確認して下さい");
    goto Error;
  }
  */
  /* selecting Emacs type */
  if ( CheckFile( szIniFile ) ){
    GetPrivateProfileString("Make","EMACS","Default",
			    szPBuf,sizeof(szPBuf),
			    szIniFile);
    if ( !strcmp( szPBuf, "Default" ) && !fQuiet ){
      if ( ! SelectEmacsen() ){
	BilErrorMessageBox( "Any Emacsen cannot found!\nHas Emacs been installed correctly?",
			    "Emacs が見付かりませんでした\nEmacs を正しくインストールしましたか?" );
	goto Error;
      }
    }
  } /* if ( CheckFile( szIniFile ) ) */
  
  if ( langId == LANGID_JAPANESE ){
    OutputLog(">>INI ファイルを読み込んでいます...");
  } else {
    OutputLog(">>Read INI File...");
  }
  if ( ! ReadIniFile() ) goto Error;

  if ( langId == LANGID_JAPANESE )
    strcpy(szPBuf,">>>Emacs は [");
  else
    strcpy(szPBuf,">>>Emacs is [");
  switch ( bEmacsType ){
  case EMACS_MEADOW:
    strcat(szPBuf,"Meadow ");
    strcat(szPBuf,szMeadowVersion);
    break;
  case EMACS_EMACS:
    strcat(szPBuf,"Emacs");
    break;
  case EMACS_XEMACS:
    strcat(szPBuf,"XEmacs");
    break;
  default:
    strcat(szPBuf,"unknown");
    break;
  }
  if ( langId == LANGID_JAPANESE )
    strcat(szPBuf,"] です");
  else
    strcat(szPBuf,"]");
  OutputLog(szPBuf);

#if 0				/* XXX: */
  if ( fSetup ){
    if ( langId == LANGID_JAPANESE ){
      OutputLog(">>設定を生成しています...");
    } else {
      OutputLog(">>Creating configuration...");
    }
    if ( ! SetupMew() ) goto Error;
    BilInfoMessageBox( "Add configuration to your ~/.emacs file.\nPlease check it.",
		       "~/.emacs ファイルに設定を追加しました\n確認して下さい");
    return ( 0 );
  }
#endif
  
  if ( fCompile ){
    if ( langId == LANGID_JAPANESE ){
      OutputLog(">>ソースをコンパイルしています...");
    } else {
      OutputLog(">>Compiling sources...");
    }
    if ( ! CompileSources() ) goto Error;
    
    if ( langId == LANGID_JAPANESE ){
      OutputLog(">>実行ファイルを作成しています...");
    } else {
      OutputLog(">>Making Executables...");
    }
  } /* if ( fCompile ){ */
  
  if ( fInstall ){
    if ( langId == LANGID_JAPANESE ){
      OutputLog(">>el/elc/実行 ファイルをインストールしています...");
    } else {
      OutputLog(">>Installing el/elc/executable Files...");
    }
    if ( ! InstallMew() ) goto Error;
    
    if ( langId == LANGID_JAPANESE ){
      OutputLog(">>画像ファイルをインストールしています...");
    } else {
      OutputLog(">>Installing Image files...");
    }
    if ( ! InstallImage() ) goto Error;

    if ( langId == LANGID_JAPANESE ){
      OutputLog(">>Info ファイルをインストールしています...");
    } else {
      OutputLog(">>Installing Info files...");
    }
    if ( ! InstallInfo() ) goto Error;
  } /* if ( fInstall ){ */

#if 0				/* XXX: */
  if ( fInstall && !fQuiet ){
      if ( BilMessageBox( NULL,
			  "Do you want to setup your ~/.emacs?",
			  "~/.emacs の設定を行ないますか?",
			  "Question", MB_YESNO ) == IDYES ){
	  if ( ! SetupMew() ) goto Error;
	  BilInfoMessageBox( "Add configuration to your ~/.emacs file.\nPlease check it.",
			     "~/.emacs ファイルに設定を追加しました\n確認して下さい");
      }
  }
#endif

  if ( fInstall )
    BilInfoMessageBox( "Mew installation complete",
		       "Mew のインストールが終了しました" );

  if ( langId == LANGID_JAPANESE ){
    OutputLog(">>Mew のインストールが終了しました");
  } else {
    OutputLog(">>Mew installation complete.");
  }

  return ( 0 );

 Error:
  BilErrorMessageBox( "Mew installation is NOT complete!\nCheck mew.log file",
		      "Mew のインストールが正常に終了しませんでした。mew.logファイルをチェックしてください" );

  return ( -1 );
}
Ejemplo n.º 19
0
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    // Set data for QSettings
    QCoreApplication::setOrganizationName("ulduzsoft");
    QCoreApplication::setOrganizationDomain("ulduzsoft.com");
    QCoreApplication::setApplicationName("spivak");

    // Init logger after crash settings
    Logger::init();

    QScopedPointer<MainWindow> p (new MainWindow());
    p.data()->show();

    QCommandLineParser parser;

    const QCommandLineOption fullScreenOption(
                QStringList() << "fs" << "fullScreen",
                "Toggle full screen"
                );

    const QCommandLineOption fileNameOption(
                QStringList() << "file" << "fileName",
                "File name to play",
                "File name to play"
                );

    const QCommandLineOption displayOption(
                QStringList() << "d" << "displayNumber",
                "Display number",
                "Screen"
                );

    parser.addOption( fullScreenOption );
    parser.addOption( fileNameOption );
    parser.addOption( displayOption );
    parser.addHelpOption();

#if defined (Q_OS_WIN)
    const QCommandLineOption showConsoleOption(
                QStringList() << "c" << "console",
                "Show debug console"
                );

    parser.addOption( showConsoleOption );
#endif

    parser.process(a);

#if defined (Q_OS_WIN)
    // Show console on Windows
    if ( parser.isSet( showConsoleOption ) )
    {
        AllocConsole();

        freopen("CONOUT$", "w", stdout);
        freopen("CONOUT$", "w", stderr);

        COORD coordInfo;
        coordInfo.X = 130;
        coordInfo.Y = 9000;

        SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), coordInfo);
        SetConsoleMode(GetStdHandle(STD_OUTPUT_HANDLE),ENABLE_QUICK_EDIT_MODE| ENABLE_EXTENDED_FLAGS);
    }
#endif

    const int displayNumber = parser.value(displayOption).toInt();

    if ( displayNumber && displayNumber < a.screens().size() )
    {

        const QRect resolution = a.screens()[displayNumber]
                ->availableGeometry();

        p.data()->move(
                    resolution.x(),
                    resolution.y()
                    );
    }

    if ( parser.isSet(fullScreenOption) )
    {
        p.data()->toggleFullscreen();
    }

    const QString fileName = parser.value(fileNameOption);

    if(!fileName.isEmpty()) {
        p.data()->enqueueSong(fileName);
        QObject::connect(
                    pActionHandler,
                    &ActionHandler::actionKaraokePlayerStop,
                    qApp,
                    &QApplication::quit
                    );
    }

    return a.exec();
}
Ejemplo n.º 20
0
 void Console::allocate()
 {
     enforce<WindowsException>(AllocConsole(), "Failed to allocate the console.");
     inHandle_ = GetStdHandle(STD_INPUT_HANDLE);
     outHandle_ = GetStdHandle(STD_OUTPUT_HANDLE);
 }
Ejemplo n.º 21
0
int WINAPI WinMain(	HINSTANCE	hInstance,			// Instance
					HINSTANCE	hPrevInstance,		// Previous Instance
					LPSTR		lpCmdLine,			// Command Line Parameters
					int			nCmdShow)			// Window Show State
{
	MSG		msg;									// Windows Message Structure
	BOOL	done=FALSE;								// Bool Variable To Exit Loop


	FILE* f;
	AllocConsole();
	freopen_s( &f, "CON", "w", stdout );

	_2RealApp = new GlSingleKinectApp;

	// Create Our OpenGL Window
	if (!CreateGLWindow("2Real Window",800,600,16,false))
	{
		return 0;									// Quit If Window Was Not Created
	}

	while(!done)									// Loop That Runs While done=FALSE
	{
		if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))	// Is There A Message Waiting?
		{
			if (msg.message==WM_QUIT)				// Have We Received A Quit Message?
			{
				done=TRUE;							// If So done=TRUE
			}
			else									// If Not, Deal With Window Messages
			{
				TranslateMessage(&msg);				// Translate The Message
				DispatchMessage(&msg);				// Dispatch The Message
			}
		}
		else										// If There Are No Messages
		{
			// Draw The Scene.  Watch For ESC Key And Quit Messages From DrawGLScene()
			if ((active && !DrawGLScene()) || keys[VK_ESCAPE])	// Active?  Was There A Quit Received?
			{
				done=TRUE;							// ESC or DrawGLScene Signalled A Quit
			}
			else									// Not Time To Quit, Update Screen
			{
				SwapBuffers(hDC);					// Swap Buffers (Double Buffering)
			}

			if (keys[VK_F1])						// Is F1 Being Pressed?
			{
				keys[VK_F1]=FALSE;					// If So Make Key FALSE
				KillGLWindow();						// Kill Our Current Window
				fullscreen=!fullscreen;				// Toggle Fullscreen / Windowed Mode
				// Recreate Our OpenGL Window
				if (!CreateGLWindow("_2Real Window",1024,768,16,fullscreen))
				{
					return 0;						// Quit If Window Was Not Created
				}
			}
		}
	}

	// Shutdown
	KillGLWindow();									// Kill The Window
	delete _2RealApp;
	return (msg.wParam);							// Exit The Program
}
Ejemplo n.º 22
0
int main(int argc, char *argv[])
{
#ifdef _WIN32
	AllocConsole();
#endif
	vector<string> args(argv,argv+argc);

	// initialize Zoidcom
	scoped_ptr<ZoidCom> zcom(new ZoidCom(zoidcom_logger));

	if (!zcom || !zcom->Init())
	{
		throw std::runtime_error("Unable to initialize ZoidCom!");
	}

	zcom->setLogLevel(0);

	intrusive_ptr<IrrlichtDevice> device;

	if(args.size() > 1 && args[1] == "server")
	{
		// Skip graphical interface
		// Dedicated server uses 'null' graphics device..
		device = intrusive_ptr<IrrlichtDevice>(
			createDevice(video::EDT_NULL, core::dimension2d<u32>(640,480), 16, false, true, true),
			false /* don't addref */
		);
		device->getLogger()->setLogLevel(ELL_INFORMATION);
		addHeightMapLoader(get_pointer(device));

		// Start server, run game instances in loop
		while(true)
		{
			std::cout << "Loading server instance...";

			scoped_ptr<Sarona::PhysWorld> serverworld(
				new Sarona::PhysWorld(get_pointer(device))
			);

			serverworld->SetLevel("testlevel/");
			serverworld->Bind(9192, false);

			serverworld->Start();
			serverworld->Wait();
		}
	}
	else
	{
		// Display main menu, graphical interface needed
		device = intrusive_ptr<IrrlichtDevice>(
			createDevice(video::EDT_OPENGL, core::dimension2d<u32>(800,600), 16, false, true, true),
			false /* don't addref */
		);
		device->getLogger()->setLogLevel(ELL_WARNING);
		addHeightMapLoader(get_pointer(device));

		Sarona::GameMenu menu(get_pointer(device));

		bool local_game = true;
		bool server = true;

		if(args.size()>1)
			local_game = server = args[1]!="client";

		// Run the main menu, let user decide what to do
		//menu.Run(local_game, server);

		scoped_ptr<Sarona::NetWorld> clientworld;
		scoped_ptr<Sarona::PhysWorld> serverworld;

		if(server)
		{
			serverworld.reset(new Sarona::PhysWorld(get_pointer(device)));

			serverworld->SetLevel("testlevel/");
			serverworld->Bind(9192, local_game);
			serverworld->Start();
			std::cout << "Server started" << std::endl;
		}

		clientworld.reset(new Sarona::NetWorld(get_pointer(device)));
		clientworld->SetLevel("testlevel/");
		clientworld->Connect("localhost:9192", local_game);


		// The main thread has to run the irrlicht loop, apparently..
		clientworld->Loop();

		if(serverworld)
		{
			serverworld->Shutdown();
			serverworld->Wait();
		}
	}
	return 0;
}
Ejemplo n.º 23
0
// Common main for linux and windows
int CommonMain(const CefMainArgs& args, CefSettings settings, CefRefPtr<MainCefApp> app, void* windows_sandbox_info, std::string userDirectory)
{

#ifdef CLIENT_DEPLOYMENT

	// Disable logging of CEF
	settings.log_severity = LOGSEVERITY_DISABLE;

#else // if no deployment, open console

	// Open Windows console for debugging purposes (even when deployed)
#ifdef _WIN32
	AllocConsole();
	freopen("conin$", "r", stdin);
	freopen("conout$", "w", stdout);
	freopen("conout$", "w", stderr);
#endif // _WIN32

#endif // CLIENT_DEPLOYMENT

	// Set path for CEF data: cache, user data and debug.log
	CefString(&settings.cache_path).FromASCII(std::string(userDirectory + "cache").c_str());
	CefString(&settings.user_data_path).FromASCII(std::string(userDirectory + "user_data").c_str());
	CefString(&settings.log_file).FromASCII(std::string(userDirectory + "debug.log").c_str());
	
	// Set output path of custom log file
	LogPath = userDirectory;

	// Say hello
	LogInfo("####################################################");
	LogInfo("Welcome to GazeTheWeb - Browse!");
	LogInfo("Version: ", CLIENT_VERSION);
	LogInfo("Personal files are saved in: ", userDirectory);

	// Turn on offscreen rendering.
	settings.windowless_rendering_enabled = true;
	settings.remote_debugging_port = 8088;

    // Initialize CEF
    LogInfo("Initializing CEF...");
    CefInitialize(args, settings, app.get(), windows_sandbox_info);
    LogInfo("..done.");

    // Execute our code
    bool shutdownOnExit = Execute(app, userDirectory);

    // Shutdown CEF
    LogInfo("Shutdown CEF...");
    CefShutdown();
    LogInfo("..done.");

    // Return zero
    LogInfo("Successful termination of program.");
    LogInfo("####################################################");

	// Tell computer to shut down
	if (shutdownOnExit)
	{
		shutdown();
	}

	// Exit
    return 0;
}
Ejemplo n.º 24
0
int WINAPI WinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nShowCmd) {

	AllocConsole();
	HANDLE hConsole = GetStdHandle(STD_INPUT_HANDLE);
	DWORD mode;
	GetConsoleMode(hConsole, &mode);
	SetConsoleMode(hConsole, mode & ~ENABLE_MOUSE_INPUT | ENABLE_PROCESSED_INPUT);
	freopen("CONIN$", "r", stdin);
	freopen("CONOUT$", "w", stdout);
	freopen("CONOUT$", "w", stderr);

	std::cout << "Sever initilized.\n";

	WSADATA wsaData;
	int iResult;

	SOCKET ListenSocket = INVALID_SOCKET;
	SOCKET ClientSocket = INVALID_SOCKET;

	struct addrinfo *result = NULL;
	struct addrinfo hints;

	int iSendResult;
	char recvbuf[DEFAULT_BUFLEN];
	int recvbuflen = DEFAULT_BUFLEN;

	// Initialize Winsock
	iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
	if (iResult != 0) {
		printf("WSAStartup failed with error: %d\n", iResult);
		return 1;
	}

	ZeroMemory(&hints, sizeof(hints));
	hints.ai_family = AF_INET;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_protocol = IPPROTO_TCP;
	hints.ai_flags = AI_PASSIVE;

	// Resolve the server address and port
	iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
	if (iResult != 0) {
		printf("getaddrinfo failed with error: %d\n", iResult);
		WSACleanup();
		return 1;
	}

	hostent* host = gethostbyname("fwankie.wicp.net");
	if (host == NULL)
	{
		WSACleanup();
		return FALSE;
	}

	char* pszIP = (char *)inet_ntoa(*(struct in_addr *)(host->h_addr));
	printf("host IP Address: %s\n", pszIP);


	struct sockaddr_in* saddr_in = (struct sockaddr_in*)result->ai_addr;
	printf("hostname: %s\n", inet_ntoa(saddr_in->sin_addr));
	//printf("sockaddr_in size is: %d\n", (int)sizeof(in_addr));
	saddr_in->sin_addr.S_un.S_addr = inet_addr(pszIP);

	//char ip[16];
	//IPuR::GetWanIP(ip, 16);
	//getchar();
	//printf("hostname: %s\n", ip);



	// Create a SOCKET for connecting to server
	ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
	if (ListenSocket == INVALID_SOCKET) {
		printf("socket failed with error: %ld\n", WSAGetLastError());
		freeaddrinfo(result);
		WSACleanup();
		return 1;
	}

	// Setup the TCP listening socket
	iResult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen);
	if (iResult == SOCKET_ERROR) {
		printf("bind failed with error: %d\n", WSAGetLastError());
		freeaddrinfo(result);
		closesocket(ListenSocket);
		WSACleanup();
		return 1;
	}

	freeaddrinfo(result);

	iResult = listen(ListenSocket, SOMAXCONN);
	if (iResult == SOCKET_ERROR) {
		printf("listen failed with error: %d\n", WSAGetLastError());
		closesocket(ListenSocket);
		WSACleanup();
		return 1;
	}

	// Accept a client socket
	ClientSocket = accept(ListenSocket, NULL, NULL);
	if (ClientSocket == INVALID_SOCKET) {
		printf("accept failed with error: %d\n", WSAGetLastError());
		closesocket(ListenSocket);
		WSACleanup();
		return 1;
	}

	// No longer need server socket
	closesocket(ListenSocket);

	// Receive until the peer shuts down the connection
	do {

		iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
		if (iResult > 0) {
			printf("Bytes received: %d\n", iResult);

			// Echo the buffer back to the sender
			iSendResult = send(ClientSocket, recvbuf, iResult, 0);
			if (iSendResult == SOCKET_ERROR) {
				printf("send failed with error: %d\n", WSAGetLastError());
				closesocket(ClientSocket);
				WSACleanup();
				return 1;
			}
			printf("Bytes sent: %d\n", iSendResult);
		}
		else if (iResult == 0)
			printf("Connection closing...\n");
		else  {
			printf("recv failed with error: %d\n", WSAGetLastError());
			closesocket(ClientSocket);
			WSACleanup();
			return 1;
		}

	} while (iResult > 0);

	// shutdown the connection since we're done
	iResult = shutdown(ClientSocket, SD_SEND);
	if (iResult == SOCKET_ERROR) {
		printf("shutdown failed with error: %d\n", WSAGetLastError());
		closesocket(ClientSocket);
		WSACleanup();
		return 1;
	}

	// cleanup
	closesocket(ClientSocket);
	WSACleanup();

	return 0;
}
Ejemplo n.º 25
0
int App::run(void)
{
    const char *QUICK_COCOS2D_MINI = getenv("QUICK_COCOS2D_MINI");
    SimulatorConfig::sharedDefaults()->setQuickCocos2dxRootPath(QUICK_COCOS2D_MINI);

    loadProjectConfig();

    HWND hwndConsole = NULL;
    if (m_project.isShowConsole())
    {
        AllocConsole();
        freopen("CONOUT$", "wt", stdout);
        freopen("CONOUT$", "wt", stderr);

        // disable close console
        hwndConsole = GetConsoleWindow();
        if (hwndConsole != NULL)
        {
            HMENU hMenu = GetSystemMenu(hwndConsole, FALSE);
            if (hMenu != NULL) DeleteMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);

            ShowWindow(hwndConsole, SW_SHOW);
            BringWindowToTop(hwndConsole);
        }
    }

    m_project.dump();

    if (m_project.isWriteDebugLogToFile())
    {
        const string debugLogFilePath = m_project.getDebugLogFilePath();
        m_writeDebugLogFile = fopen(debugLogFilePath.c_str(), "w");
        if (!m_writeDebugLogFile)
        {
            CCLOG("Cannot create debug log file %s", debugLogFilePath.c_str());
        }
    }

    do
    {
        m_exit = TRUE;

        // create the application instance
        m_app = new AppDelegate();
        m_app->setProjectConfig(m_project);

        // set environments
        SetCurrentDirectoryA(m_project.getProjectDir().c_str());
        CCFileUtils::sharedFileUtils()->setSearchRootPath(m_project.getProjectDir().c_str());
        CCFileUtils::sharedFileUtils()->setWritablePath(m_project.getWritableRealPath().c_str());

        // create opengl view
        CCEGLView* eglView = CCEGLView::sharedOpenGLView();
        eglView->setMenuResource(MAKEINTRESOURCE(IDC_LUAHOSTWIN32));
        eglView->setWndProc(WindowProc);
        eglView->setFrameSize(m_project.getFrameSize().width, m_project.getFrameSize().height);
        eglView->setFrameZoomFactor(m_project.getFrameScale());

        // make window actived
        m_hwnd = eglView->getHWnd();
        BringWindowToTop(m_hwnd);
        SetWindowTextA(m_hwnd, "__PROJECT_PACKAGE_LAST_NAME_L__");

        // restore window position
        const CCPoint windowOffset = m_project.getWindowOffset();
        if (windowOffset.x != 0 || windowOffset.y != 0)
        {
            eglView->moveWindow(windowOffset.x, windowOffset.y);
        }

        // set icon
        HICON icon = LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_LUAHOSTWIN32));
        SendMessage(m_hwnd, WM_SETICON, ICON_BIG, (LPARAM)icon);

        if (hwndConsole)
        {
            SendMessage(hwndConsole, WM_SETICON, ICON_BIG, (LPARAM)icon);
        }

        // update menu
        createViewMenu();
        updateMenu();

        // run game
        CCLuaStack *stack = CCLuaEngine::defaultEngine()->getLuaStack();
        const vector<string> arr = m_project.getPackagePathArray();
        for (vector<string>::const_iterator it = arr.begin(); it != arr.end(); ++it)
        {
            stack->addSearchPath(it->c_str());
        }

        m_app->run();

        // cleanup
        CCScriptEngineManager::sharedManager()->removeScriptEngine();
        CCScriptEngineManager::purgeSharedManager();
        CocosDenshion::SimpleAudioEngine::end();

        delete m_app;
        m_app = NULL;
    } while (!m_exit);

    FreeConsole();
    if (m_writeDebugLogFile) fclose(m_writeDebugLogFile);
    return 0;
}
Ejemplo n.º 26
0
void
debugInit ()
{
    if (enableDebug)
        AllocConsole ();
}
Ejemplo n.º 27
0
int
main(int argc, char *argv[])
{
    signal_user_data_t *ud;
    GError *error = NULL;
    GOptionContext *context;

    hb_global_init();

#ifdef ENABLE_NLS
    bindtextdomain(GETTEXT_PACKAGE, PACKAGE_LOCALE_DIR);
    bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8");
    textdomain(GETTEXT_PACKAGE);
#endif

    context = g_option_context_new(_("- Transcode media formats"));
    g_option_context_add_main_entries(context, entries, GETTEXT_PACKAGE);
    g_option_context_add_group(context, gtk_get_option_group(TRUE));
#if defined(_ENABLE_GST)
    g_option_context_add_group(context, gst_init_get_option_group());
#endif
    g_option_context_parse(context, &argc, &argv, &error);
    if (error != NULL)
    {
        g_warning("%s: %s", G_STRFUNC, error->message);
        g_clear_error(&error);
    }
    g_option_context_free(context);

#if defined(_WIN32)
    if (win32_console)
    {
        // Enable console logging
        if(AttachConsole(ATTACH_PARENT_PROCESS) || AllocConsole()){
            close(STDOUT_FILENO);
            freopen("CONOUT$", "w", stdout);
            close(STDERR_FILENO);
            freopen("CONOUT$", "w", stderr);
        }
    }
    else
    {
        // Non-console windows apps do not have a stderr->_file
        // assigned properly
        stderr->_file = STDERR_FILENO;
        stdout->_file = STDOUT_FILENO;
    }
#endif

    if (argc > 1 && dvd_device == NULL && argv[1][0] != '-')
    {
        dvd_device = argv[1];
    }

    gtk_init(&argc, &argv);

    GtkCssProvider *css = gtk_css_provider_new();
    error = NULL;
    gtk_css_provider_load_from_data(css, MyCSS, -1, &error);
    if (error == NULL)
    {
        GdkScreen *ss = gdk_screen_get_default();
        gtk_style_context_add_provider_for_screen(ss, GTK_STYLE_PROVIDER(css),
                                    GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
    }
    else
    {
        g_warning("%s: %s", G_STRFUNC, error->message);
        g_clear_error(&error);
    }

#if !defined(_WIN32)
    notify_init("HandBrake");
#endif
    ghb_resource_init();
    ghb_load_icons();

#if !defined(_WIN32)
    dbus_g_thread_init();
#endif
    ghb_udev_init();

    ghb_write_pid_file();
    ud = g_malloc0(sizeof(signal_user_data_t));
    ud->debug = ghb_debug;
    g_log_set_handler(NULL, G_LOG_LEVEL_DEBUG, debug_log_handler, ud);
    g_log_set_handler("Gtk", G_LOG_LEVEL_WARNING, warn_log_handler, ud);
    //g_log_set_handler("Gtk", G_LOG_LEVEL_CRITICAL, warn_log_handler, ud);

    ud->globals = ghb_dict_new();
    ud->prefs = ghb_dict_new();
    ud->settings_array = ghb_array_new();
    ud->settings = ghb_dict_new();
    ghb_array_append(ud->settings_array, ud->settings);

    ud->builder = create_builder_or_die(BUILDER_NAME);
    // Enable events that alert us to media change events
    watch_volumes(ud);

    //GtkWidget *widget = GHB_WIDGET(ud->builder, "PictureDetelecineCustom");
    //gtk_entry_set_inner_border(widget, 2);

    // Since GtkBuilder no longer assigns object ids to widget names
    // Assign a few that are necessary for style overrides to work
    GtkWidget *widget;
#if defined(_NO_UPDATE_CHECK)
    widget = GHB_WIDGET(ud->builder, "check_updates_box");
    gtk_widget_hide(widget);
#endif

    // Must set the names of the widgets that I want to modify
    // style for.
    gtk_widget_set_name(GHB_WIDGET(ud->builder, "preview_hud"), "preview_hud");
    gtk_widget_set_name(GHB_WIDGET(ud->builder, "preview_frame"), "preview_frame");
    gtk_widget_set_name(GHB_WIDGET(ud->builder, "live_preview_play"), "live_preview_play");
    gtk_widget_set_name(GHB_WIDGET(ud->builder, "live_preview_progress"), "live_preview_progress");
    gtk_widget_set_name(GHB_WIDGET(ud->builder, "live_encode_progress"), "live_encode_progress");
    gtk_widget_set_name(GHB_WIDGET(ud->builder, "live_duration"), "live_duration");
    gtk_widget_set_name(GHB_WIDGET(ud->builder, "preview_show_crop"), "preview_show_crop");
    gtk_widget_set_name(GHB_WIDGET(ud->builder, "preview_fullscreen"), "preview_fullscreen");
    widget = GHB_WIDGET(ud->builder, "preview_hud");
    gtk_widget_set_name(widget, "preview_hud");
    widget = GHB_WIDGET(ud->builder, "preview_window");
    gtk_widget_set_name(widget, "preview_window");

    // Set up the "hud" control overlay for the preview window
    GtkWidget *preview_box, *draw, *hud, *blender;

    preview_box = GHB_WIDGET(ud->builder, "preview_window_box");
    draw = GHB_WIDGET(ud->builder, "preview_image");
    hud = GHB_WIDGET(ud->builder, "preview_hud");

#if 0 // GTK_CHECK_VERSION(3, 0, 0)
    // This uses the new GtkOverlay widget.
    //
    // Unfortunately, GtkOverlay is broken in a couple of ways.
    //
    // First, it doesn't respect gtk_widget_shape_combine_region()
    // on it's child overlays.  It appears to just ignore the clip
    // mask of the child.
    //
    // Second, it doesn't respect window opacity.
    //
    // So for now, I'll just continue using my home-grown overlay
    // widget (GhbCompositor).
    blender = gtk_overlay_new();
    gtk_container_add(GTK_CONTAINER(preview_box), blender);
    gtk_container_add(GTK_CONTAINER(blender), draw);
    gtk_widget_set_valign (hud, GTK_ALIGN_END);
    gtk_widget_set_halign (hud, GTK_ALIGN_CENTER);
    gtk_overlay_add_overlay(GTK_OVERLAY(blender), hud);

    g_signal_connect(G_OBJECT(blender), "get-child-position",
                    G_CALLBACK(position_overlay_cb), ud);

    gtk_widget_show(blender);
#else
    // Set up compositing for hud
    blender = ghb_compositor_new();

    gtk_container_add(GTK_CONTAINER(preview_box), blender);
    ghb_compositor_zlist_insert(GHB_COMPOSITOR(blender), draw, 1, 1);
    ghb_compositor_zlist_insert(GHB_COMPOSITOR(blender), hud, 2, .85);
    gtk_widget_show(blender);
#endif

    // Redirect stderr to the activity window
    ghb_preview_init(ud);
    IoRedirect(ud);
    ghb_log( "%s - %s - %s",
        HB_PROJECT_TITLE, HB_PROJECT_BUILD_TITLE, HB_PROJECT_URL_WEBSITE );
    ghb_init_dep_map();

    // Need to connect x264_options textview buffer to the changed signal
    // since it can't be done automatically
    GtkTextView *textview;
    GtkTextBuffer *buffer;
    textview = GTK_TEXT_VIEW(GHB_WIDGET(ud->builder, "x264Option"));
    buffer = gtk_text_view_get_buffer(textview);
    g_signal_connect(buffer, "changed", (GCallback)x264_entry_changed_cb, ud);

    textview = GTK_TEXT_VIEW(GHB_WIDGET(ud->builder, "VideoOptionExtra"));
    buffer = gtk_text_view_get_buffer(textview);
    g_signal_connect(buffer, "changed", (GCallback)video_option_changed_cb, ud);

    textview = GTK_TEXT_VIEW(GHB_WIDGET(ud->builder, "MetaLongDescription"));
    buffer = gtk_text_view_get_buffer(textview);
    g_signal_connect(buffer, "changed", (GCallback)plot_changed_cb, ud);

    ghb_combo_init(ud);

    g_debug("ud %p\n", ud);
    g_debug("ud->builder %p\n", ud->builder);

    bind_audio_tree_model(ud);
    bind_subtitle_tree_model(ud);
    bind_presets_tree_model(ud);
    bind_queue_tree_model(ud);
    bind_chapter_tree_model(ud);
    // Connect up the signals to their callbacks
    // I wrote my own connector so that I could pass user data
    // to the callbacks.  Builder's standard autoconnect doesn't all this.
    gtk_builder_connect_signals_full(ud->builder, MyConnect, ud);

    ghb_init_audio_defaults_ui(ud);
    ghb_init_subtitle_defaults_ui(ud);

    // Parsing x264 options "" initializes x264 widgets to proper defaults
    ghb_x264_init(ud);

    // Load prefs before presets.  Some preset defaults may depend
    // on preference settings.
    // First load default values
    ghb_settings_init(ud->prefs, "Preferences");
    ghb_settings_init(ud->globals, "Globals");
    ghb_settings_init(ud->settings, "Initialization");
    ghb_settings_init(ud->settings, "OneTimeInitialization");
    // Load user preferences file
    ghb_prefs_load(ud);
    // Store user preferences into ud->prefs
    ghb_prefs_to_settings(ud->prefs);

    int logLevel = ghb_dict_get_int(ud->prefs, "LoggingLevel");
    ghb_backend_init(logLevel);

    // Load the presets files
    ghb_presets_load(ud);
    // Note that ghb_preset_to_settings(ud->settings) is called when
    // the default preset is selected.

    ghb_settings_to_ui(ud, ud->globals);
    ghb_settings_to_ui(ud, ud->prefs);
    // Note that ghb_settings_to_ui(ud->settings) happens when initial
    // empty title is initialized.


    if (ghb_dict_get_bool(ud->prefs, "hbfd"))
    {
        ghb_hbfd(ud, TRUE);
    }
    const gchar *source = ghb_dict_get_string(ud->prefs, "default_source");
    ghb_dvd_set_current(source, ud);

    // Populate the presets tree view
    ghb_presets_list_init(ud, NULL);
    // Get the first preset name
    if (arg_preset != NULL)
    {
        ghb_select_preset(ud->builder, arg_preset);
    }
    else
    {
        ghb_select_default_preset(ud->builder);
    }

    // Grey out widgets that are dependent on a disabled feature
    ghb_check_all_depencencies(ud);

    if (dvd_device != NULL)
    {
        // Source overridden from command line option
        ghb_dict_set_string(ud->globals, "scan_source", dvd_device);
        g_idle_add((GSourceFunc)ghb_idle_scan, ud);
    }
    else
    {
        GhbValue *gval = ghb_dict_get_value(ud->prefs, "default_source");
        ghb_dict_set(ud->globals, "scan_source", ghb_value_dup(gval));
    }
    // Reload and check status of the last saved queue
    g_idle_add((GSourceFunc)ghb_reload_queue, ud);

    // Start timer for monitoring libhb status, 500ms
    g_timeout_add(200, ghb_timer_cb, (gpointer)ud);

    // Add dvd devices to File menu
    ghb_volname_cache_init();
    GHB_THREAD_NEW("Cache Volume Names", (GThreadFunc)ghb_cache_volnames, ud);

    GtkWidget *ghb_window = GHB_WIDGET(ud->builder, "hb_window");

    gint window_width, window_height;
    GdkGeometry geo = {
        -1, -1, 1920, 768, -1, -1, 10, 10, 0, 0, GDK_GRAVITY_NORTH_WEST
    };
    GdkWindowHints geo_mask;
    geo_mask = GDK_HINT_MIN_SIZE | GDK_HINT_MAX_SIZE | GDK_HINT_BASE_SIZE;
    gtk_window_set_geometry_hints(GTK_WINDOW(ghb_window), ghb_window,
                                  &geo, geo_mask);
    window_width = ghb_dict_get_int(ud->prefs, "window_width");
    window_height = ghb_dict_get_int(ud->prefs, "window_height");

    /*
     * Filter objects in GtkBuilder xml
     * Unfortunately, GtkFilter is poorly supported by GtkBuilder,
     * so a lot of the setup must happen in code.
        SourceFilterAll
        SourceFilterVideo
        SourceFilterTS
        SourceFilterMPG
        SourceFilterEVO
        SourceFilterVOB
        SourceFilterMKV
        SourceFilterMP4
        SourceFilterAVI
        SourceFilterMOV
        SourceFilterOGG
        SourceFilterFLV
        SourceFilterWMV
    */
    // Add filters to source chooser
    GtkFileFilter *filter;
    GtkFileChooser *chooser;
    chooser = GTK_FILE_CHOOSER(GHB_WIDGET(ud->builder, "source_dialog"));
    filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterAll"));
    gtk_file_filter_set_name(filter, _("All"));
    gtk_file_filter_add_pattern(filter, "*");
    gtk_file_chooser_add_filter(chooser, filter);
    filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterVideo"));
    gtk_file_filter_set_name(filter, _("Video"));
    gtk_file_filter_add_mime_type(filter, "video/*");
    gtk_file_chooser_add_filter(chooser, filter);
    filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterTS"));
    gtk_file_filter_set_name(filter, "TS");
    gtk_file_filter_add_pattern(filter, "*.ts");
    gtk_file_filter_add_pattern(filter, "*.TS");
    gtk_file_filter_add_pattern(filter, "*.m2ts");
    gtk_file_filter_add_pattern(filter, "*.M2TS");
    gtk_file_chooser_add_filter(chooser, filter);
    filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterMPG"));
    gtk_file_filter_set_name(filter, "MPG");
    gtk_file_filter_add_pattern(filter, "*.mpg");
    gtk_file_filter_add_pattern(filter, "*.MPG");
    gtk_file_filter_add_pattern(filter, "*.mepg");
    gtk_file_filter_add_pattern(filter, "*.MEPG");
    gtk_file_chooser_add_filter(chooser, filter);
    filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterEVO"));
    gtk_file_filter_set_name(filter, "EVO");
    gtk_file_filter_add_pattern(filter, "*.evo");
    gtk_file_filter_add_pattern(filter, "*.EVO");
    gtk_file_chooser_add_filter(chooser, filter);
    filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterVOB"));
    gtk_file_filter_set_name(filter, "VOB");
    gtk_file_filter_add_pattern(filter, "*.vob");
    gtk_file_filter_add_pattern(filter, "*.VOB");
    gtk_file_chooser_add_filter(chooser, filter);
    filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterMKV"));
    gtk_file_filter_set_name(filter, "MKV");
    gtk_file_filter_add_pattern(filter, "*.mkv");
    gtk_file_filter_add_pattern(filter, "*.MKV");
    gtk_file_chooser_add_filter(chooser, filter);
    filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterMP4"));
    gtk_file_filter_set_name(filter, "MP4");
    gtk_file_filter_add_pattern(filter, "*.mp4");
    gtk_file_filter_add_pattern(filter, "*.MP4");
    gtk_file_filter_add_pattern(filter, "*.m4v");
    gtk_file_filter_add_pattern(filter, "*.M4V");
    gtk_file_chooser_add_filter(chooser, filter);
    filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterMOV"));
    gtk_file_filter_set_name(filter, "MOV");
    gtk_file_filter_add_pattern(filter, "*.mov");
    gtk_file_filter_add_pattern(filter, "*.MOV");
    gtk_file_chooser_add_filter(chooser, filter);
    filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterAVI"));
    gtk_file_filter_set_name(filter, "AVI");
    gtk_file_filter_add_pattern(filter, "*.avi");
    gtk_file_filter_add_pattern(filter, "*.AVI");
    gtk_file_chooser_add_filter(chooser, filter);
    filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterOGG"));
    gtk_file_filter_set_name(filter, "OGG");
    gtk_file_filter_add_pattern(filter, "*.ogg");
    gtk_file_filter_add_pattern(filter, "*.OGG");
    gtk_file_filter_add_pattern(filter, "*.ogv");
    gtk_file_filter_add_pattern(filter, "*.OGV");
    gtk_file_filter_add_pattern(filter, "*.ogm");
    gtk_file_filter_add_pattern(filter, "*.OGM");
    gtk_file_chooser_add_filter(chooser, filter);
    filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterFLV"));
    gtk_file_filter_set_name(filter, "FLV");
    gtk_file_filter_add_pattern(filter, "*.flv");
    gtk_file_filter_add_pattern(filter, "*.FLV");
    gtk_file_chooser_add_filter(chooser, filter);
    filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterWMV"));
    gtk_file_filter_set_name(filter, "WMV");
    gtk_file_filter_add_pattern(filter, "*.wmv");
    gtk_file_filter_add_pattern(filter, "*.WMV");
    gtk_file_chooser_add_filter(chooser, filter);

    // Gtk has a really stupid bug.  If the file chooser is showing
    // hidden files AND there is no filter set, it will not select
    // the filename when gtk_file_chooser_set_filename is called.
    // So add a completely unnessary filter to prevent this behavior.
    filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterAll"));
    gtk_file_chooser_set_filter(chooser, filter);

    PangoFontDescription *font_desc;
    font_desc = pango_font_description_from_string("monospace 10");
    textview = GTK_TEXT_VIEW(GHB_WIDGET(ud->builder, "activity_view"));
    gtk_widget_override_font(GTK_WIDGET(textview), font_desc);
    pango_font_description_free(font_desc);

    // Grrrr!  Gtk developers !!!hard coded!!! the width of the
    // radio buttons in GtkStackSwitcher to 100!!!
    //
    // Thankfully, GtkStackSwitcher is a regular container object
    // and we can access the buttons to change their width.
    GList *stack_switcher_children, *link;
    GtkContainer * stack_switcher = GTK_CONTAINER(
                            GHB_WIDGET(ud->builder, "SettingsStackSwitcher"));
    link = stack_switcher_children = gtk_container_get_children(stack_switcher);
    while (link != NULL)
    {
        GtkWidget *widget = link->data;
        gtk_widget_set_size_request(widget, -1, -1);
        gtk_widget_set_hexpand(widget, TRUE);
        gtk_widget_set_halign(widget, GTK_ALIGN_FILL);
        link = link->next;
    }
    g_list_free(stack_switcher_children);

    gtk_window_resize(GTK_WINDOW(ghb_window), window_width, window_height);
    gtk_widget_show(ghb_window);

    // Everything should be go-to-go.  Lets rock!

    gtk_main();
    ghb_backend_close();

    ghb_value_free(&ud->queue);
    ghb_value_free(&ud->settings_array);
    ghb_value_free(&ud->prefs);
    ghb_value_free(&ud->globals);
    ghb_value_free(&ud->x264_priv);

    g_io_channel_unref(ud->activity_log);
    ghb_settings_close();
    ghb_resource_free();
#if !defined(_WIN32)
    notify_uninit();
#endif

    g_object_unref(ud->builder);

    g_free(ud->current_dvd_device);
    g_free(ud);

    return 0;
}
Ejemplo n.º 28
0
		bool Console::AllocateConsole()
		{
			CoreAssert(this != NULL);
#ifdef TARGET_OS_WINDOWS
			m_consoleAllocated = (AllocConsole() == TRUE);
#elif defined (TARGET_OS_MACOSX) && 0
			/* BSD-style pty code. */
			char buf[64];
			const char *ptymajors = "pqrstuvwxyzabcdefghijklmnoABCDEFGHIJKLMNOPQRSTUVWXYZ";
			const char *ptyminors = "0123456789abcdef";
			int num_minors = strlen(ptyminors);
			int num_ptys = strlen(ptymajors) * num_minors;

			for (int i = 0; i < num_ptys; i++) {
				sprintf(buf, "/dev/pty%c%c", ptymajors[i / num_minors], ptyminors[i % num_minors]);
				m_ptyfd = open(buf, O_RDWR | O_NOCTTY);
				if (m_ptyfd < 0)
					continue;

				sprintf(m_slaveName, "/dev/tty%c%c", ptymajors[i / num_minors], ptyminors[i % num_minors]);

				/* Open the slave side. */
				m_ttyfd = open(m_slaveName, O_RDWR | O_NOCTTY);
				if (m_ttyfd < 0) {
					close(m_ptyfd);
					break;
				}

				m_consoleAllocated = true;
				break;
			}

			if (m_consoleAllocated) {
				m_childPID = fork();
				if (m_childPID == -1) {
					m_consoleAllocated = false;
					close(m_ttyfd);
					close(m_ptyfd);
					return m_consoleAllocated;
				}

				if (m_childPID == 0) {
					/* child */
					close(m_ttyfd);
					char call[128];
					char *pt = &m_slaveName[strlen(m_slaveName) - 1];
					const char *xterm = "/usr/X11/bin/xterm";
					sprintf(call, "-S%s/%d", pt, m_ptyfd);
					execl(xterm, xterm, "-bg", "black", "-fg", "white", "-geometry", "132x50", call, NULL);
					exit(0);
				} else {
					/* master */
					close(m_ptyfd);
				}
			}

#elif defined (TARGET_OS_NDSFIRMWARE)
			irqInit();
			irqEnable(IRQ_VBLANK);
			videoSetMode(MODE_0_2D);
			videoSetModeSub(MODE_0_2D | DISPLAY_BG0_ACTIVE);
			vramSetBankC(VRAM_C_SUB_BG);
			SUB_BG0_CR = BG_MAP_BASE(31);
			BG_PALETTE_SUB[255] = RGB15(31, 31, 31);
			consoleInitDefault((u16 *)SCREEN_BASE_BLOCK_SUB(31), (u16 *)CHAR_BASE_BLOCK_SUB(0), 16);
			m_consoleAllocated = true;
#endif
			return m_consoleAllocated;
		}
Ejemplo n.º 29
0
EXPORT_C_(void) s2r_replay(HWND hwnd, HINSTANCE hinst, LPSTR filename, int nCmdShow)
{
#ifndef ENABLE_NEW_IOPDMA_SPU2
	int events=0;

	Running = true;

#ifdef WIN32
	AllocConsole();
	SetConsoleCtrlHandler(HandlerRoutine, TRUE);
	
	conprintf("Playing %s file on %x...",filename,hwnd);

#endif

	// load file
	FILE *file=fopen(filename,"rb");

	if(!file)
	{
		conprintf("Could not open the replay file.");
		return;
	}
	// if successful, init the plugin

#define TryRead(dest,size,count,file) if(fread(dest,size,count,file)<count) { conprintf("Error reading from file.");  goto Finish;  /* Need to exit the while() loop and maybe also the switch */ }

	TryRead(&CurrentIOPCycle,4,1,file);
	
	replay_mode=true;

	InitWaitSync(); // Initialize the WaitSync stuff

	SPU2init();
	SPU2irqCallback(dummy1,dummy4,dummy7);
	SPU2setClockPtr(&CurrentIOPCycle);
	SPU2open(&hwnd);

	CurrentIOPCycle=0;

	SPU2async(0);

	while(!feof(file) && Running)
	{
		u32 ccycle=0;
		u32 evid=0;
		u32 sval=0;
		u32 tval=0;

		TryRead(&ccycle,4,1,file);
		TryRead(&sval,4,1,file);

		evid=sval>>29;
		sval&=0x1FFFFFFF;

		u32 TargetCycle = ccycle * 768;

		while(TargetCycle > CurrentIOPCycle)
		{
			u32 delta = WaitSync(TargetCycle);
			SPU2async(delta);
		}
		
		switch(evid)
		{
		case 0:
			SPU2read(sval);
			break;
		case 1:
			TryRead(&tval,2,1,file);
			SPU2write(sval,tval);
			break;
		case 2:
			TryRead(dmabuffer,sval,2,file);
			SPU2writeDMA4Mem(dmabuffer,sval);
			break;
		case 3:
			TryRead(dmabuffer,sval,2,file);
			SPU2writeDMA7Mem(dmabuffer,sval);
			break;
		default:
			// not implemented
			return;
			break;
		}
		events++;
	}

Finish:

	//shutdown
	SPU2close();
	SPU2shutdown();
	fclose(file);

	conprintf("Finished playing %s file (%d cycles, %d events).",filename,CurrentIOPCycle,events);

#ifdef WIN32
	FreeConsole();
#endif

	replay_mode=false;
#endif
}
Ejemplo n.º 30
0
static void _console()
{
    DWORD dwError;
    char szError[4096];

    // standard handles that are not redirected to console will already
    // have been initialized correctly - mscrt obeys pipe/file redirections
    // even if we are not in a console process.

    sprintf(szError, "%d %d %d\n",
        (int) GetStdHandle(STD_INPUT_HANDLE),
        (int) GetStdHandle(STD_OUTPUT_HANDLE),
        (int) GetStdHandle(STD_ERROR_HANDLE));
    OutputDebugString(szError);


    // however console handles are not inherited, so first we attach a console
    if (GetConsoleWindow() == NULL)
        AttachConsole(ATTACH_PARENT_PROCESS);

    sprintf(szError, "%d %d %d\n",
        (int) GetStdHandle(STD_INPUT_HANDLE),
        (int) GetStdHandle(STD_OUTPUT_HANDLE),
        (int) GetStdHandle(STD_ERROR_HANDLE));
    OutputDebugString(szError);

    // for some reason this doesn't now work. is it windows 10 or excel 2016
    // or 32 bit on 64. something changed post windows 7 that stops AllocConsole?

    // if we have no console, and no redirection, then allocate a new console
    if (GetConsoleWindow() == NULL)
    {
        if (!AllocConsole())
        {
            sprintf(szError, "%d %d %d\n",
            (int) GetStdHandle(STD_INPUT_HANDLE),
            (int) GetStdHandle(STD_OUTPUT_HANDLE),
            (int) GetStdHandle(STD_ERROR_HANDLE));
        OutputDebugString(szError);

            dwError = GetLastError();
            sprintf(szError, "GetLastError: %d\n", dwError);
            OutputDebugString(szError);
            return;
        }
    }

    // -2 means we had no console window at startup, so fixup the streams
    // that aren't propertly initialized
    _reopen_console("CONIN$", stdin, "rb");
    _reopen_console("CONOUT$", stdout, "ab");
    _reopen_console("CONOUT$", stderr, "ab");

    // some packacges (pytest) assume that file descriptors 0, 1, 2
    // are always stdin/out/err, so dup them back so it works
    if (_fileno(stdin) != 0)
        _dup2(_fileno(stdin), 0);
    if (_fileno(stdout) != 1)
        _dup2(_fileno(stdout), 1);
    if (_fileno(stderr) != 2)
        _dup2(_fileno(stderr), 2);

    printf("Hello From The Other Side.\n");
}