int app::run(void)
{
    loadProjectConfig();

    AllocConsole();
    freopen("CONOUT$", "wt", stdout);
    freopen("CONOUT$", "wt", stderr);

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

    do
    {
        m_exit = TRUE;

        if (m_project.isShowConsole())
        {
            ShowWindow(hwndConsole, SW_SHOW);
            BringWindowToTop(hwndConsole);
        }
        else
        {
            ShowWindow(hwndConsole, SW_HIDE);
        }

        // create the application instance
        m_app = new AppDelegate();
        m_app->setStartupScriptFilename(m_project.getScriptFilePath());

        // set environments
        SetCurrentDirectoryA(m_project.getProjectDir().c_str());
        CCFileUtils::sharedFileUtils()->setSearchRootPath(m_project.getProjectDir().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);

        // 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);
        SendMessage(hwndConsole, WM_SETICON, ICON_BIG, (LPARAM)icon);

        // 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();
    return 0;
}
Esempio n. 2
0
void CloseConsole(){//关闭控制台
#ifdef _OUT
//	fclose(g_stdOut);
	FreeConsole();
#endif
}
Esempio n. 3
0
/**
 * Detach from terminal.
 *
 * @param sctx service context
 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
 */
static int
detach_terminal (struct GNUNET_SERVICE_Context *sctx)
{
#ifndef MINGW
  pid_t pid;
  int nullfd;
  int filedes[2];

  if (0 != PIPE (filedes))
  {
    LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "pipe");
    return GNUNET_SYSERR;
  }
  pid = fork ();
  if (pid < 0)
  {
    LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "fork");
    return GNUNET_SYSERR;
  }
  if (0 != pid)
  {
    /* Parent */
    char c;

    GNUNET_break (0 == CLOSE (filedes[1]));
    c = 'X';
    if (1 != READ (filedes[0], &c, sizeof (char)))
      LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "read");
    fflush (stdout);
    switch (c)
    {
    case '.':
      exit (0);
    case 'I':
      LOG (GNUNET_ERROR_TYPE_INFO, _("Service process failed to initialize\n"));
      break;
    case 'S':
      LOG (GNUNET_ERROR_TYPE_INFO,
           _("Service process could not initialize server function\n"));
      break;
    case 'X':
      LOG (GNUNET_ERROR_TYPE_INFO,
           _("Service process failed to report status\n"));
      break;
    }
    exit (1);                   /* child reported error */
  }
  GNUNET_break (0 == CLOSE (0));
  GNUNET_break (0 == CLOSE (1));
  GNUNET_break (0 == CLOSE (filedes[0]));
  nullfd = OPEN ("/dev/null", O_RDWR | O_APPEND);
  if (nullfd < 0)
    return GNUNET_SYSERR;
  /* set stdin/stdout to /dev/null */
  if ((dup2 (nullfd, 0) < 0) || (dup2 (nullfd, 1) < 0))
  {
    LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "dup2");
    (void) CLOSE (nullfd);
    return GNUNET_SYSERR;
  }
  (void) CLOSE (nullfd);
  /* Detach from controlling terminal */
  pid = setsid ();
  if (-1 == pid)
    LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "setsid");
  sctx->ready_confirm_fd = filedes[1];
#else
  /* FIXME: we probably need to do something else
   * elsewhere in order to fork the process itself... */
  FreeConsole ();
#endif
  return GNUNET_OK;
}
Esempio n. 4
0
File: app.cpp Progetto: yinjimmy/qmm
int App::run(void)
{
    const char *QMM_ROOT = getenv("QMM_ROOT");
    SimulatorConfig::sharedDefaults()->setQuickCocos2dxRootPath(QMM_ROOT);

    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;
}
Esempio n. 5
0
//
// KillConsole
//
void KillConsole(void)
{
	FreeConsole( );  // Free Console Window

} // end of the function 
Esempio n. 6
0
int APIENTRY WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow)
{

	RECT rect;
	int cc;
	wc.style = CS_OWNDC | CS_VREDRAW | CS_HREDRAW;
	wc.lpfnWndProc = WndProc;
	wc.cbClsExtra = wc.cbWndExtra = 0;
	wc.hInstance = 0;
	wc.hIcon = NULL;
	wc.hCursor = LoadCursor(0,IDC_ARROW);
	wc.hbrBackground = NULL;
	wc.lpszMenuName = NULL;
	wc.lpszClassName = "raytracer";
	if (!RegisterClass(&wc)) return FALSE;
	rect.left = rect.top = 0;
	rect.right = SCRWIDTH, rect.bottom = SCRHEIGHT;
	AdjustWindowRect( &rect, WS_POPUP|WS_SYSMENU|WS_CAPTION, 0 );
	rect.right -= rect.left, rect.bottom -= rect.top;
	wnd = CreateWindowEx( 0, "raytracer", "raytracer", WS_OVERLAPPEDWINDOW & ~WS_MAXIMIZEBOX & ~WS_THICKFRAME,
		CW_USEDEFAULT, CW_USEDEFAULT, rect.right, rect.bottom, 0, 0, 0, 0 );
	ShowWindow(wnd,SW_NORMAL);
	for ( cc = 0; cc < sizeof( BITMAPINFOHEADER ) + 16; cc++ ) bitmapbuffer[cc] = 0;
	bh = (BITMAPINFO *)&bitmapbuffer;
	bh->bmiHeader.biSize = sizeof( BITMAPINFOHEADER );
	bh->bmiHeader.biPlanes = 1;
	bh->bmiHeader.biBitCount = 32;
	bh->bmiHeader.biCompression = BI_BITFIELDS;
	bh->bmiHeader.biWidth = SCRWIDTH, bh->bmiHeader.biHeight = -SCRHEIGHT;
	((unsigned long*)bh->bmiColors)[0] = 255 << 16;
	((unsigned long*)bh->bmiColors)[1] = 255 << 8;
	((unsigned long*)bh->bmiColors)[2] = 255;
	window_hdc = GetDC(wnd);
	SystemParametersInfo(SPI_SETSCREENSAVEACTIVE, 0, 0, 0);
	initConf(config);
	// prepare output canvas
	surface = new Surface(SCRWIDTH,SCRHEIGHT);
	buffer = surface->GetBuffer();
	surface->Clear(0);
	AllocConsole();   //Sortie Console
	freopen("CONOUT$","wb",stdout);


	clock_scene.begin(); // ---> start clock_scene

	// prepare renderer
	Scene* maScene = new Scene();
	maScene->chargerScene(config.filename);
	maScene->afficherScene();

	tracer = new Engine(config);
	tracer->SetScene(maScene);
	tracer->SetTarget(surface->GetBuffer(),SCRWIDTH, SCRHEIGHT );
	int tpos = 60;

	clock_scene.end(); // ---> end clock_scene		

	system("Pause");

	
		tracer->InitRender();
	clock_render.begin(); // ---> start clock_render
		tracer->Render(); //calcul de l'image
	clock_render.end(); // ---> end clock_render

	SaveImage("test.ppm",tracer->GetImage());
	
	SaveLogFile("Resultat.log",config);
	afficherClock();

	while (1)
	{
		DrawWindow();
	}

FreeConsole();  // Close the console window

	return 1;
}
Esempio n. 7
0
/**
 * This function initializes libcaca vout method.
 */
static int Open(vlc_object_t *object)
{
    vout_display_t *vd = (vout_display_t *)object;
    vout_display_sys_t *sys;

#if !defined(__APPLE__) && !defined(WIN32)
# ifndef X_DISPLAY_MISSING
    if (!vlc_xlib_init(object))
        return VLC_EGENERIC;
# endif
#endif

#if defined(WIN32)
    CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
    SMALL_RECT rect;
    COORD coord;
    HANDLE hstdout;

    if (!AllocConsole()) {
        msg_Err(vd, "cannot create console");
        return VLC_EGENERIC;
    }

    hstdout =
        CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE,
                                  FILE_SHARE_READ | FILE_SHARE_WRITE,
                                  NULL, CONSOLE_TEXTMODE_BUFFER, NULL);
    if (!hstdout || hstdout == INVALID_HANDLE_VALUE) {
        msg_Err(vd, "cannot create screen buffer");
        FreeConsole();
        return VLC_EGENERIC;
    }

    if (!SetConsoleActiveScreenBuffer(hstdout)) {
        msg_Err(vd, "cannot set active screen buffer");
        FreeConsole();
        return VLC_EGENERIC;
    }

    coord = GetLargestConsoleWindowSize(hstdout);
    msg_Dbg(vd, "SetConsoleWindowInfo: %ix%i", coord.X, coord.Y);

    /* Force size for now */
    coord.X = 100;
    coord.Y = 40;

    if (!SetConsoleScreenBufferSize(hstdout, coord))
        msg_Warn(vd, "SetConsoleScreenBufferSize %i %i",
                  coord.X, coord.Y);

    /* Get the current screen buffer size and window position. */
    if (GetConsoleScreenBufferInfo(hstdout, &csbiInfo)) {
        rect.Top = 0; rect.Left = 0;
        rect.Right = csbiInfo.dwMaximumWindowSize.X - 1;
        rect.Bottom = csbiInfo.dwMaximumWindowSize.Y - 1;
        if (!SetConsoleWindowInfo(hstdout, TRUE, &rect))
            msg_Dbg(vd, "SetConsoleWindowInfo failed: %ix%i",
                     rect.Right, rect.Bottom);
    }
#endif

    /* Allocate structure */
    vd->sys = sys = calloc(1, sizeof(*sys));
    if (!sys)
        goto error;

    sys->cv = cucul_create_canvas(0, 0);
    if (!sys->cv) {
        msg_Err(vd, "cannot initialize libcucul");
        goto error;
    }

    const char *driver = NULL;
#ifdef __APPLE__
    // Make sure we don't try to open a window.
    driver = "ncurses";
#endif

    sys->dp = caca_create_display_with_driver(sys->cv, driver);
    if (!sys->dp) {
        msg_Err(vd, "cannot initialize libcaca");
        goto error;
    }
    vout_display_DeleteWindow(vd, NULL);

    if (vd->cfg->display.title)
        caca_set_display_title(sys->dp,
                               vd->cfg->display.title);
    else
        caca_set_display_title(sys->dp,
                               VOUT_TITLE "(Colour AsCii Art)");

    /* Fix format */
    video_format_t fmt = vd->fmt;
    if (fmt.i_chroma != VLC_CODEC_RGB32) {
        fmt.i_chroma = VLC_CODEC_RGB32;
        fmt.i_rmask = 0x00ff0000;
        fmt.i_gmask = 0x0000ff00;
        fmt.i_bmask = 0x000000ff;
    }

    /* TODO */
    vout_display_info_t info = vd->info;

    /* Setup vout_display now that everything is fine */
    vd->fmt = fmt;
    vd->info = info;

    vd->pool    = Pool;
    vd->prepare = Prepare;
    vd->display = PictureDisplay;
    vd->control = Control;
    vd->manage  = Manage;

    /* Fix initial state */
    vout_display_SendEventFullscreen(vd, false);
    Refresh(vd);

    return VLC_SUCCESS;

error:
    if (sys) {
        if (sys->pool)
            picture_pool_Delete(sys->pool);
        if (sys->dither)
            cucul_free_dither(sys->dither);
        if (sys->dp)
            caca_free_display(sys->dp);
        if (sys->cv)
            cucul_free_canvas(sys->cv);

        free(sys);
    }
#if defined(WIN32)
    FreeConsole();
#endif
    return VLC_EGENERIC;
}
Esempio n. 8
0
LRESULT CALLBACK GetMsgProc(int nCode, WPARAM wParam, LPARAM lParam)
{
	//sprintf_s(s_buf, "GetMsgProc\n");
	//WriteConsole(s_out, s_buf, strlen(s_buf), &s_ccount, 0);
	if (!s_initialized)
	{
		if (!AttachConsole(g_consoleId))
		{
			FreeConsole();
			AttachConsole(g_consoleId);
		}
		s_out = GetStdHandle(STD_OUTPUT_HANDLE); // TODO: we don't really close it
		sprintf_s(s_buf, "Attached console\n");
		WriteConsole(s_out, s_buf, strlen(s_buf), &s_ccount, 0);

		if (!g_mouseHook)
		{
			g_mouseHook = SetWindowsHookEx(WH_MOUSE_LL, LowLevelMouseProc, g_this, 0); // mouse_ll global only (requires process with message loop)
			if (g_mouseHook)
			{
				sprintf_s(s_buf, "Installed mouse hook\n");
				WriteConsole(s_out, s_buf, strlen(s_buf), &s_ccount, 0);
			}
			else
			{
				sprintf_s(s_buf, "Could not install mouse hook\n");
				WriteConsole(s_out, s_buf, strlen(s_buf), &s_ccount, 0);
			}
		}

		if (g_detect_screen_size)
		{
			HWND win = GetDesktopWindow();
			RECT rec;
			GetWindowRect(win, &rec);
			g_screen_height = rec.bottom;
			g_screen_width = rec.right;
		}

		sprintf_s(s_buf, "X-Offset: %i Y-Offset: %i Width: %i Height: %i\n", g_screen_offsetX, g_screen_offsetY, g_screen_width, g_screen_height);
		WriteConsole(s_out, s_buf, strlen(s_buf), &s_ccount, 0);

		s_cursors.reset(new CursorMap);
		s_cursorBuf.reset(new CursorMap);

		s_server.reset(new TUIO::TuioServer(g_host, g_serverPort));
		sprintf_s(s_buf, "Created server (%s:%i)\n", g_host, g_serverPort);
		WriteConsole(s_out, s_buf, strlen(s_buf), &s_ccount, 0);

		s_timer = SetTimer(g_targetWnd, TIMER_IDENTIFIER, TIMER_CALL_TIME, 0);

		s_initialized = true;
	}

	if (nCode < 0) // do not process message 
	{
		return CallNextHookEx(0, nCode, wParam, lParam);
	}

	switch (nCode) 
	{ 
	case HC_ACTION: 
		{
			LPMSG msg = (LPMSG)lParam;

			// register everything for touch
			// Note: pretty ugly but seems to be the only possibility to register every window
			RegisterTouchWindow(msg->hwnd, TOUCH_FLAGS);

			switch (msg->message)
			{
			case WM_TOUCH:
				{
					//sprintf_s(s_buf, "Touches received:\n");
					//WriteConsole(s_out, s_buf, strlen(s_buf), &s_ccount, 0);

					UINT cInputs = LOWORD(msg->wParam);
					PTOUCHINPUT pInputs = new TOUCHINPUT[cInputs];
					if (NULL != pInputs)
					{
						if (GetTouchInputInfo((HTOUCHINPUT)msg->lParam,
							cInputs,
							pInputs,
							sizeof(TOUCHINPUT)))
						{
							s_server->initFrame(TUIO::TuioTime::getSessionTime());

							// process pInputs
							for (UINT i=0; i<cInputs; ++i)
							{
								//sprintf_s(s_buf, "ID: %i, X: %i, Y: %i\n", pInputs[i].dwID, pInputs[i].x, pInputs[i].y);
								//WriteConsole(s_out, s_buf, strlen(s_buf), &s_ccount, 0);

								std::map<DWORD, TUIO::TuioCursor*>::iterator cursorIt = s_cursors->find(pInputs[i].dwID);
								if (cursorIt != s_cursors->end())
								{
									// found
									s_server->updateTuioCursor(cursorIt->second,
															   ((pInputs[i].x*0.01f)+g_screen_offsetX)/(float)(g_screen_width+g_screen_offsetX),
															   ((pInputs[i].y*0.01f)+g_screen_offsetY)/(float)(g_screen_height+g_screen_offsetY));
									(*s_cursorBuf)[pInputs[i].dwID] = cursorIt->second;
									s_cursors->erase(cursorIt);
								}
								else
								{
									// not found
									(*s_cursorBuf)[pInputs[i].dwID] = s_server->addTuioCursor(
															((pInputs[i].x*0.01f)+g_screen_offsetX)/(float)(g_screen_width+g_screen_offsetX),
															((pInputs[i].y*0.01f)+g_screen_offsetY)/(float)(g_screen_height+g_screen_offsetY));
								}
							}
							
							for (std::map<DWORD, TUIO::TuioCursor*>::iterator it = s_cursors->begin(); it != s_cursors->end(); ++it)
							{
								s_server->removeTuioCursor(it->second);
							}
							
							s_cursors->clear();
							std::auto_ptr<CursorMap> tmp(s_cursorBuf);
							s_cursorBuf = s_cursors;
							s_cursors = tmp;	
							s_server->commitFrame();
						}
					}
					delete[] pInputs;
				}
				break;
			case WM_TIMER:
				{
					//if (msg->wParam == TIMER_IDENTIFIER)
					//{
						BOOL frameOpen(false);
						for (std::map<DWORD, TUIO::TuioCursor*>::iterator it = s_cursors->begin(); it != s_cursors->end();)
						{
							long delta = TUIO::TuioTime::getSessionTime().getTotalMilliseconds() - it->second->getTuioTime().getTotalMilliseconds();
							if (delta > MAX_CURSOR_IDLE_TIME)
							{
								if (!frameOpen)
								{
									s_server->initFrame(TUIO::TuioTime::getSessionTime());
									frameOpen = true;
								}
								s_server->removeTuioCursor(it->second);
								std::map<DWORD, TUIO::TuioCursor*>::iterator tmp = it++;
								s_cursors->erase(tmp);
								//sprintf_s(s_buf, "Removed cursor due to time limit\n");
								//WriteConsole(s_out, s_buf, strlen(s_buf), &s_ccount, 0);
							}
							else
							{
								++it;
							}
						}
						if (frameOpen)
						{
							s_server->commitFrame();
						}
					//}
				}
				break;
			}
		}
		break; 
	}

	return CallNextHookEx(0, nCode, wParam, lParam); 
}
Esempio n. 9
0
int main()
{
	FreeConsole();
	App::App();
	g_app->Run();
}
Esempio n. 10
0
void NsConsole::Hide()
{
	FreeConsole();

	_bShowing = false;
}
Esempio n. 11
0
int main(int argc, char **argv)
#endif /* __APPLE__ */
{
	bool commit_dune_cfg = false;
#if defined(_WIN32)
	#if defined(__MINGW32__) && defined(__STRICT_ANSI__)
		int __cdecl __MINGW_NOTHROW _fileno (FILE*);
	#endif
	FILE *err = fopen("error.log", "w");
	FILE *out = fopen("output.log", "w");

	#if defined(_MSC_VER)
		_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
	#endif

	if (err != NULL) _dup2(_fileno(err), _fileno(stderr));
	if (out != NULL) _dup2(_fileno(out), _fileno(stdout));
	FreeConsole();
#endif
	CrashLog_Init();

	VARIABLE_NOT_USED(argc);
	VARIABLE_NOT_USED(argv);

	/* Load opendune.ini file */
	Load_IniFile();

	if (!File_Init()) {
		Error("Cannot initialise files. Does %s directory exist ?\n", DATA_DIR);
		exit(1);
	}

	/* Loading config from dune.cfg */
	if (!Config_Read("dune.cfg", &g_config)) {
		Config_Default(&g_config);
		commit_dune_cfg = true;
	}
	/* reading config from opendune.ini which prevail over dune.cfg */
	SetLanguage_From_IniFile(&g_config);

	/* Writing config to dune.cfg */
	if (commit_dune_cfg && !Config_Write("dune.cfg", &g_config)) {
		Error("Error writing to dune.cfg file.\n");
		exit(1);
	}

	Input_Init();

	Drivers_All_Init();

	if (!Unknown_25C4_000E()) exit(1);

	g_var_7097 = 0;

	GameLoop_Main();

	printf("%s\n", String_Get_ByIndex(STR_THANK_YOU_FOR_PLAYING_DUNE_II));

	PrepareEnd();
	Free_IniFile();
	exit(0);
}
Esempio n. 12
0
int main(int argc, char *argv[]) {
    pa_core *c = NULL;
    pa_strbuf *buf = NULL;
    pa_daemon_conf *conf = NULL;
    pa_mainloop *mainloop = NULL;
    char *s;
    int r = 0, retval = 1, d = 0;
    pa_bool_t valid_pid_file = FALSE;
    pa_bool_t ltdl_init = FALSE;
    int passed_fd = -1;
    const char *e;
#ifdef HAVE_FORK
    int daemon_pipe[2] = { -1, -1 };
#endif
#ifdef OS_IS_WIN32
    pa_time_event *win32_timer;
    struct timeval win32_tv;
#endif
    int autospawn_fd = -1;
    pa_bool_t autospawn_locked = FALSE;
#ifdef HAVE_DBUS
    pa_dbus_connection *dbus = NULL;
#endif

    pa_log_set_ident("pulseaudio");
    pa_log_set_level(PA_LOG_NOTICE);
    pa_log_set_flags(PA_LOG_COLORS|PA_LOG_PRINT_FILE|PA_LOG_PRINT_LEVEL, PA_LOG_RESET);

#if defined(__linux__) && defined(__OPTIMIZE__)
    /*
       Disable lazy relocations to make usage of external libraries
       more deterministic for our RT threads. We abuse __OPTIMIZE__ as
       a check whether we are a debug build or not. This all is
       admittedly a bit snake-oilish.
    */

    if (!getenv("LD_BIND_NOW")) {
        char *rp;
        char *canonical_rp;

        /* We have to execute ourselves, because the libc caches the
         * value of $LD_BIND_NOW on initialization. */

        pa_set_env("LD_BIND_NOW", "1");

        if ((canonical_rp = pa_realpath(PA_BINARY))) {

            if ((rp = pa_readlink("/proc/self/exe"))) {

                if (pa_streq(rp, canonical_rp))
                    pa_assert_se(execv(rp, argv) == 0);
                else
                    pa_log_warn("/proc/self/exe does not point to %s, cannot self execute. Are you playing games?", canonical_rp);

                pa_xfree(rp);

            } else
                pa_log_warn("Couldn't read /proc/self/exe, cannot self execute. Running in a chroot()?");

            pa_xfree(canonical_rp);

        } else
            pa_log_warn("Couldn't canonicalize binary path, cannot self execute.");
    }
#endif

    if ((e = getenv("PULSE_PASSED_FD"))) {
        passed_fd = atoi(e);

        if (passed_fd <= 2)
            passed_fd = -1;
    }

    /* We might be autospawned, in which case have no idea in which
     * context we have been started. Let's cleanup our execution
     * context as good as possible */

    pa_reset_personality();
    pa_drop_root();
    pa_close_all(passed_fd, -1);
    pa_reset_sigs(-1);
    pa_unblock_sigs(-1);
    pa_reset_priority();

    setlocale(LC_ALL, "");
    pa_init_i18n();

    conf = pa_daemon_conf_new();

    if (pa_daemon_conf_load(conf, NULL) < 0)
        goto finish;

    if (pa_daemon_conf_env(conf) < 0)
        goto finish;

    if (pa_cmdline_parse(conf, argc, argv, &d) < 0) {
        pa_log(_("Failed to parse command line."));
        goto finish;
    }

    pa_log_set_level(conf->log_level);
    pa_log_set_target(conf->auto_log_target ? PA_LOG_STDERR : conf->log_target);
    if (conf->log_meta)
        pa_log_set_flags(PA_LOG_PRINT_META, PA_LOG_SET);
    if (conf->log_time)
        pa_log_set_flags(PA_LOG_PRINT_TIME, PA_LOG_SET);
    pa_log_set_show_backtrace(conf->log_backtrace);

    LTDL_SET_PRELOADED_SYMBOLS();
    pa_ltdl_init();
    ltdl_init = TRUE;

    if (conf->dl_search_path)
        lt_dlsetsearchpath(conf->dl_search_path);

#ifdef OS_IS_WIN32
    {
        WSADATA data;
        WSAStartup(MAKEWORD(2, 0), &data);
    }
#endif

    pa_random_seed();

    switch (conf->cmd) {
        case PA_CMD_DUMP_MODULES:
            pa_dump_modules(conf, argc-d, argv+d);
            retval = 0;
            goto finish;

        case PA_CMD_DUMP_CONF: {

            if (d < argc) {
                pa_log("Too many arguments.\n");
                goto finish;
            }

            s = pa_daemon_conf_dump(conf);
            fputs(s, stdout);
            pa_xfree(s);
            retval = 0;
            goto finish;
        }

        case PA_CMD_DUMP_RESAMPLE_METHODS: {
            int i;

            if (d < argc) {
                pa_log("Too many arguments.\n");
                goto finish;
            }

            for (i = 0; i < PA_RESAMPLER_MAX; i++)
                if (pa_resample_method_supported(i))
                    printf("%s\n", pa_resample_method_to_string(i));

            retval = 0;
            goto finish;
        }

        case PA_CMD_HELP :
            pa_cmdline_help(argv[0]);
            retval = 0;
            goto finish;

        case PA_CMD_VERSION :

            if (d < argc) {
                pa_log("Too many arguments.\n");
                goto finish;
            }

            printf(PACKAGE_NAME" "PACKAGE_VERSION"\n");
            retval = 0;
            goto finish;

        case PA_CMD_CHECK: {
            pid_t pid;

            if (d < argc) {
                pa_log("Too many arguments.\n");
                goto finish;
            }

            if (pa_pid_file_check_running(&pid, "pulseaudio") < 0)
                pa_log_info(_("Daemon not running"));
            else {
                pa_log_info(_("Daemon running as PID %u"), pid);
                retval = 0;
            }

            goto finish;

        }
        case PA_CMD_KILL:

            if (d < argc) {
                pa_log("Too many arguments.\n");
                goto finish;
            }

            if (pa_pid_file_kill(SIGINT, NULL, "pulseaudio") < 0)
                pa_log(_("Failed to kill daemon: %s"), pa_cstrerror(errno));
            else
                retval = 0;

            goto finish;

        case PA_CMD_CLEANUP_SHM:

            if (d < argc) {
                pa_log("Too many arguments.\n");
                goto finish;
            }

            if (pa_shm_cleanup() >= 0)
                retval = 0;

            goto finish;

        default:
            pa_assert(conf->cmd == PA_CMD_DAEMON || conf->cmd == PA_CMD_START);
    }

    if (d < argc) {
        pa_log("Too many arguments.\n");
        goto finish;
    }

    if (getuid() == 0 && !conf->system_instance)
        pa_log_warn(_("This program is not intended to be run as root (unless --system is specified)."));
    else if (getuid() != 0 && conf->system_instance) {
        pa_log(_("Root privileges required."));
        goto finish;
    }

    if (conf->cmd == PA_CMD_START && conf->system_instance) {
        pa_log(_("--start not supported for system instances."));
        goto finish;
    }

    if (conf->system_instance && !conf->disallow_exit)
        pa_log_warn(_("Running in system mode, but --disallow-exit not set!"));

    if (conf->system_instance && !conf->disallow_module_loading)
        pa_log_warn(_("Running in system mode, but --disallow-module-loading not set!"));

    if (conf->system_instance && !conf->disable_shm) {
        pa_log_notice(_("Running in system mode, forcibly disabling SHM mode!"));
        conf->disable_shm = TRUE;
    }

    if (conf->system_instance && conf->exit_idle_time >= 0) {
        pa_log_notice(_("Running in system mode, forcibly disabling exit idle time!"));
        conf->exit_idle_time = -1;
    }

    if (conf->cmd == PA_CMD_START) {
        /* If we shall start PA only when it is not running yet, we
         * first take the autospawn lock to make things
         * synchronous. */

        if ((autospawn_fd = pa_autospawn_lock_init()) < 0) {
            pa_log("Failed to initialize autospawn lock");
            goto finish;
        }

        if ((pa_autospawn_lock_acquire(TRUE) < 0)) {
            pa_log("Failed to acquire autospawn lock");
            goto finish;
        }

        autospawn_locked = TRUE;
    }

    if (conf->daemonize) {
        pid_t child;
        int tty_fd;

        if (pa_stdio_acquire() < 0) {
            pa_log(_("Failed to acquire stdio."));
            goto finish;
        }

#ifdef HAVE_FORK
        if (pipe(daemon_pipe) < 0) {
            pa_log(_("pipe failed: %s"), pa_cstrerror(errno));
            goto finish;
        }

        if ((child = fork()) < 0) {
            pa_log(_("fork() failed: %s"), pa_cstrerror(errno));
            goto finish;
        }

        if (child != 0) {
            ssize_t n;
            /* Father */

            pa_assert_se(pa_close(daemon_pipe[1]) == 0);
            daemon_pipe[1] = -1;

            if ((n = pa_loop_read(daemon_pipe[0], &retval, sizeof(retval), NULL)) != sizeof(retval)) {

                if (n < 0)
                    pa_log(_("read() failed: %s"), pa_cstrerror(errno));

                retval = 1;
            }

            if (retval)
                pa_log(_("Daemon startup failed."));
            else
                pa_log_info(_("Daemon startup successful."));

            goto finish;
        }

        if (autospawn_fd >= 0) {
            /* The lock file is unlocked from the parent, so we need
             * to close it in the child */

            pa_autospawn_lock_release();
            pa_autospawn_lock_done(TRUE);

            autospawn_locked = FALSE;
            autospawn_fd = -1;
        }

        pa_assert_se(pa_close(daemon_pipe[0]) == 0);
        daemon_pipe[0] = -1;
#endif

        if (conf->auto_log_target)
            pa_log_set_target(PA_LOG_SYSLOG);

#ifdef HAVE_SETSID
        setsid();
#endif
#ifdef HAVE_SETPGID
        setpgid(0,0);
#endif

#ifndef OS_IS_WIN32
        pa_close(0);
        pa_close(1);
        pa_close(2);

        pa_assert_se(open("/dev/null", O_RDONLY) == 0);
        pa_assert_se(open("/dev/null", O_WRONLY) == 1);
        pa_assert_se(open("/dev/null", O_WRONLY) == 2);
#else
        FreeConsole();
#endif

#ifdef SIGTTOU
        signal(SIGTTOU, SIG_IGN);
#endif
#ifdef SIGTTIN
        signal(SIGTTIN, SIG_IGN);
#endif
#ifdef SIGTSTP
        signal(SIGTSTP, SIG_IGN);
#endif

#ifdef TIOCNOTTY
        if ((tty_fd = open("/dev/tty", O_RDWR)) >= 0) {
            ioctl(tty_fd, TIOCNOTTY, (char*) 0);
            pa_assert_se(pa_close(tty_fd) == 0);
        }
#endif
    }

    pa_set_env_and_record("PULSE_INTERNAL", "1");
    pa_assert_se(chdir("/") == 0);
    umask(0022);

#ifdef HAVE_SYS_RESOURCE_H
    set_all_rlimits(conf);
#endif
    pa_rtclock_hrtimer_enable();

    pa_raise_priority(conf->nice_level);

    if (conf->system_instance)
        if (change_user() < 0)
            goto finish;

    pa_set_env_and_record("PULSE_SYSTEM", conf->system_instance ? "1" : "0");

    pa_log_info(_("This is PulseAudio %s"), PACKAGE_VERSION);
    pa_log_debug(_("Compilation host: %s"), CANONICAL_HOST);
    pa_log_debug(_("Compilation CFLAGS: %s"), PA_CFLAGS);

    s = pa_uname_string();
    pa_log_debug(_("Running on host: %s"), s);
    pa_xfree(s);

    pa_log_debug(_("Found %u CPUs."), pa_ncpus());

    pa_log_info(_("Page size is %lu bytes"), (unsigned long) PA_PAGE_SIZE);

#ifdef HAVE_VALGRIND_MEMCHECK_H
    pa_log_debug(_("Compiled with Valgrind support: yes"));
#else
    pa_log_debug(_("Compiled with Valgrind support: no"));
#endif

    pa_log_debug(_("Running in valgrind mode: %s"), pa_yes_no(pa_in_valgrind()));

    pa_log_debug(_("Running in VM: %s"), pa_yes_no(pa_running_in_vm()));

#ifdef __OPTIMIZE__
    pa_log_debug(_("Optimized build: yes"));
#else
    pa_log_debug(_("Optimized build: no"));
#endif

#ifdef NDEBUG
    pa_log_debug(_("NDEBUG defined, all asserts disabled."));
#elif defined(FASTPATH)
    pa_log_debug(_("FASTPATH defined, only fast path asserts disabled."));
#else
    pa_log_debug(_("All asserts enabled."));
#endif

    if (!(s = pa_machine_id())) {
        pa_log(_("Failed to get machine ID"));
        goto finish;
    }
    pa_log_info(_("Machine ID is %s."), s);
    pa_xfree(s);

    if ((s = pa_session_id())) {
        pa_log_info(_("Session ID is %s."), s);
        pa_xfree(s);
    }

    if (!(s = pa_get_runtime_dir()))
        goto finish;
    pa_log_info(_("Using runtime directory %s."), s);
    pa_xfree(s);

    if (!(s = pa_get_state_dir()))
        goto finish;
    pa_log_info(_("Using state directory %s."), s);
    pa_xfree(s);

    pa_log_info(_("Using modules directory %s."), conf->dl_search_path);

    pa_log_info(_("Running in system mode: %s"), pa_yes_no(pa_in_system_mode()));

    if (pa_in_system_mode())
        pa_log_warn(_("OK, so you are running PA in system mode. Please note that you most likely shouldn't be doing that.\n"
                      "If you do it nonetheless then it's your own fault if things don't work as expected.\n"
                      "Please read http://pulseaudio.org/wiki/WhatIsWrongWithSystemMode for an explanation why system mode is usually a bad idea."));

    if (conf->use_pid_file) {
        int z;

        if ((z = pa_pid_file_create("pulseaudio")) != 0) {

            if (conf->cmd == PA_CMD_START && z > 0) {
                /* If we are already running and with are run in
                 * --start mode, then let's return this as success. */

                retval = 0;
                goto finish;
            }

            pa_log(_("pa_pid_file_create() failed."));
            goto finish;
        }

        valid_pid_file = TRUE;
    }

    pa_disable_sigpipe();

    if (pa_rtclock_hrtimer())
        pa_log_info(_("Fresh high-resolution timers available! Bon appetit!"));
    else
        pa_log_info(_("Dude, your kernel stinks! The chef's recommendation today is Linux with high-resolution timers enabled!"));

    if (conf->lock_memory) {
#ifdef HAVE_SYS_MMAN_H
        if (mlockall(MCL_FUTURE) < 0)
            pa_log_warn("mlockall() failed: %s", pa_cstrerror(errno));
        else
            pa_log_info("Sucessfully locked process into memory.");
#else
        pa_log_warn("Memory locking requested but not supported on platform.");
#endif
    }

    pa_memtrap_install();

    if (!getenv("PULSE_NO_SIMD")) {
        pa_cpu_init_x86();
        pa_cpu_init_arm();
    }

    pa_assert_se(mainloop = pa_mainloop_new());

    if (!(c = pa_core_new(pa_mainloop_get_api(mainloop), !conf->disable_shm, conf->shm_size))) {
        pa_log(_("pa_core_new() failed."));
        goto finish;
    }

    c->default_sample_spec = conf->default_sample_spec;
    c->default_channel_map = conf->default_channel_map;
    c->default_n_fragments = conf->default_n_fragments;
    c->default_fragment_size_msec = conf->default_fragment_size_msec;
    c->exit_idle_time = conf->exit_idle_time;
    c->scache_idle_time = conf->scache_idle_time;
    c->resample_method = conf->resample_method;
    c->realtime_priority = conf->realtime_priority;
    c->realtime_scheduling = !!conf->realtime_scheduling;
    c->disable_remixing = !!conf->disable_remixing;
    c->disable_lfe_remixing = !!conf->disable_lfe_remixing;
    c->running_as_daemon = !!conf->daemonize;
    c->disallow_exit = conf->disallow_exit;
    c->flat_volumes = conf->flat_volumes;

    pa_assert_se(pa_signal_init(pa_mainloop_get_api(mainloop)) == 0);
    pa_signal_new(SIGINT, signal_callback, c);
    pa_signal_new(SIGTERM, signal_callback, c);
#ifdef SIGUSR1
    pa_signal_new(SIGUSR1, signal_callback, c);
#endif
#ifdef SIGUSR2
    pa_signal_new(SIGUSR2, signal_callback, c);
#endif
#ifdef SIGHUP
    pa_signal_new(SIGHUP, signal_callback, c);
#endif

#ifdef OS_IS_WIN32
    win32_timer = pa_mainloop_get_api(mainloop)->rtclock_time_new(pa_mainloop_get_api(mainloop), pa_gettimeofday(&win32_tv), message_cb, NULL);
#endif

    if (!conf->no_cpu_limit)
        pa_assert_se(pa_cpu_limit_init(pa_mainloop_get_api(mainloop)) == 0);

    buf = pa_strbuf_new();
    if (conf->load_default_script_file) {
        FILE *f;

        if ((f = pa_daemon_conf_open_default_script_file(conf))) {
            r = pa_cli_command_execute_file_stream(c, f, buf, &conf->fail);
            fclose(f);
        }
    }

    if (r >= 0)
        r = pa_cli_command_execute(c, conf->script_commands, buf, &conf->fail);

    pa_log_error("%s", s = pa_strbuf_tostring_free(buf));
    pa_xfree(s);

    /* We completed the initial module loading, so let's disable it
     * from now on, if requested */
    c->disallow_module_loading = !!conf->disallow_module_loading;

    if (r < 0 && conf->fail) {
        pa_log(_("Failed to initialize daemon."));
        goto finish;
    }

    if (!c->modules || pa_idxset_size(c->modules) == 0) {
        pa_log(_("Daemon startup without any loaded modules, refusing to work."));
        goto finish;
    }

#ifdef HAVE_FORK
    if (daemon_pipe[1] >= 0) {
        int ok = 0;
        pa_loop_write(daemon_pipe[1], &ok, sizeof(ok), NULL);
        pa_close(daemon_pipe[1]);
        daemon_pipe[1] = -1;
    }
#endif

#ifdef HAVE_DBUS
    dbus = register_dbus(c);
#endif

    pa_log_info(_("Daemon startup complete."));

    retval = 0;
    if (pa_mainloop_run(mainloop, &retval) < 0)
        goto finish;

    pa_log_info(_("Daemon shutdown initiated."));

finish:
#ifdef HAVE_DBUS
    if (dbus)
        pa_dbus_connection_unref(dbus);
#endif

    if (autospawn_fd >= 0) {
        if (autospawn_locked)
            pa_autospawn_lock_release();

        pa_autospawn_lock_done(FALSE);
    }

#ifdef OS_IS_WIN32
    if (win32_timer)
        pa_mainloop_get_api(mainloop)->time_free(win32_timer);
#endif

    if (c) {
        pa_core_unref(c);
        pa_log_info(_("Daemon terminated."));
    }

    if (!conf->no_cpu_limit)
        pa_cpu_limit_done();

    pa_signal_done();

#ifdef HAVE_FORK
    if (daemon_pipe[1] >= 0)
        pa_loop_write(daemon_pipe[1], &retval, sizeof(retval), NULL);

    pa_close_pipe(daemon_pipe);
#endif

    if (mainloop)
        pa_mainloop_free(mainloop);

    if (conf)
        pa_daemon_conf_free(conf);

    if (valid_pid_file)
        pa_pid_file_remove();

    /* This has no real purpose except making things valgrind-clean */
    pa_unset_env_recorded();

#ifdef OS_IS_WIN32
    WSACleanup();
#endif

    if (ltdl_init)
        pa_ltdl_done();

#ifdef HAVE_DBUS
    dbus_shutdown();
#endif

    return retval;
}
Esempio n. 13
0
// N.B. On Windows, this should be called from WinMain. Link against qtmain and specify
// /SubSystem:Windows
int main(int argc, char* argv[])
{
#ifdef _WIN32
  const bool console_attached = AttachConsole(ATTACH_PARENT_PROCESS) != FALSE;
  HANDLE stdout_handle = ::GetStdHandle(STD_OUTPUT_HANDLE);
  if (console_attached && stdout_handle)
  {
    freopen("CONOUT$", "w", stdout);
    freopen("CONOUT$", "w", stderr);
  }
#endif

  QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
  QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
  QCoreApplication::setOrganizationName(QStringLiteral("Dolphin Emulator"));
  QCoreApplication::setOrganizationDomain(QStringLiteral("dolphin-emu.org"));
  QCoreApplication::setApplicationName(QStringLiteral("dolphin-emu"));

  QApplication app(argc, argv);

#ifdef _WIN32
  // Get the default system font because Qt's way of obtaining it is outdated
  NONCLIENTMETRICS metrics = {};
  LOGFONT& logfont = metrics.lfMenuFont;
  metrics.cbSize = sizeof(NONCLIENTMETRICS);

  if (SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(metrics), &metrics, 0))
  {
    // Sadly Qt 5 doesn't support turning a native font handle into a QFont so this is the next best
    // thing
    QFont font = QApplication::font();
    font.setFamily(QString::fromStdString(UTF16ToUTF8(logfont.lfFaceName)));

    font.setItalic(logfont.lfItalic);
    font.setStrikeOut(logfont.lfStrikeOut);
    font.setUnderline(logfont.lfUnderline);

    // The default font size is a bit too small
    font.setPointSize(QFontInfo(font).pointSize() * 1.2);

    QApplication::setFont(font);
  }
#endif

  auto parser = CommandLineParse::CreateParser(CommandLineParse::ParserOptions::IncludeGUIOptions);
  const optparse::Values& options = CommandLineParse::ParseArguments(parser.get(), argc, argv);
  const std::vector<std::string> args = parser->args();

#ifdef _WIN32
  FreeConsole();
#endif

  UICommon::SetUserDirectory(static_cast<const char*>(options.get("user")));
  UICommon::CreateDirectories();
  UICommon::Init();
  Resources::Init();
  Settings::Instance().SetBatchModeEnabled(options.is_set("batch"));

  // Hook up alerts from core
  RegisterMsgAlertHandler(QtMsgAlertHandler);

  // Hook up translations
  Translation::Initialize();

  // Whenever the event loop is about to go to sleep, dispatch the jobs
  // queued in the Core first.
  QObject::connect(QAbstractEventDispatcher::instance(), &QAbstractEventDispatcher::aboutToBlock,
                   &app, &Core::HostDispatchJobs);

  std::unique_ptr<BootParameters> boot;
  if (options.is_set("exec"))
  {
    const std::list<std::string> paths_list = options.all("exec");
    const std::vector<std::string> paths{std::make_move_iterator(std::begin(paths_list)),
                                         std::make_move_iterator(std::end(paths_list))};
    boot = BootParameters::GenerateFromFile(paths);
  }
  else if (options.is_set("nand_title"))
  {
    const std::string hex_string = static_cast<const char*>(options.get("nand_title"));
    if (hex_string.length() == 16)
    {
      const u64 title_id = std::stoull(hex_string, nullptr, 16);
      boot = std::make_unique<BootParameters>(BootParameters::NANDTitle{title_id});
    }
    else
    {
      QMessageBox::critical(nullptr, QObject::tr("Error"), QObject::tr("Invalid title ID."));
    }
  }
  else if (!args.empty())
  {
    boot = BootParameters::GenerateFromFile(args.front());
  }

  int retval;

  {
    DolphinAnalytics::Instance()->ReportDolphinStart("qt");

    MainWindow win{std::move(boot)};
    if (options.is_set("debugger"))
      Settings::Instance().SetDebugModeEnabled(true);
    win.Show();

#if defined(USE_ANALYTICS) && USE_ANALYTICS
    if (!SConfig::GetInstance().m_analytics_permission_asked)
    {
      QMessageBox analytics_prompt(&win);

      analytics_prompt.setIcon(QMessageBox::Question);
      analytics_prompt.setWindowModality(Qt::WindowModal);
      analytics_prompt.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
      analytics_prompt.setWindowTitle(QObject::tr("Allow Usage Statistics Reporting"));
      analytics_prompt.setText(
          QObject::tr("Do you authorize Dolphin to report information to Dolphin's developers?"));
      analytics_prompt.setInformativeText(
          QObject::tr("If authorized, Dolphin can collect data on its performance, "
                      "feature usage, and configuration, as well as data on your system's "
                      "hardware and operating system.\n\n"
                      "No private data is ever collected. This data helps us understand "
                      "how people and emulated games use Dolphin and prioritize our "
                      "efforts. It also helps us identify rare configurations that are "
                      "causing bugs, performance and stability issues.\n"
                      "This authorization can be revoked at any time through Dolphin's "
                      "settings."));

      const int answer = analytics_prompt.exec();

      SConfig::GetInstance().m_analytics_permission_asked = true;
      Settings::Instance().SetAnalyticsEnabled(answer == QMessageBox::Yes);

      DolphinAnalytics::Instance()->ReloadConfig();
    }
#endif

    auto* updater = new Updater(&win);
    updater->start();

    retval = app.exec();
  }

  Core::Shutdown();
  UICommon::Shutdown();
  Host::GetInstance()->deleteLater();

  return retval;
}
Esempio n. 14
0
/* Called from main thread only (Passes Event) */
int sdl_init(int mode)
{
#if !defined(NO_X) && defined(__unix__)
	dll_handle	dl;
	const char *libnames[2]={"X11", NULL};
#endif

	if(init_sdl_video()) {
		fprintf(stderr, "SDL Video Init Failed\n");
		return(-1);
	}

	bitmap_init(sdl_drawrect, sdl_flush);

	if(mode==CIOLIB_MODE_SDL_FULLSCREEN)
		fullscreen=1;
	if(mode==CIOLIB_MODE_SDL_YUV)
		yuv.enabled=1;
	if(mode==CIOLIB_MODE_SDL_YUV_FULLSCREEN) {
		yuv.enabled=1;
		fullscreen=1;
	}
#if (SDL_MAJOR_VERSION > 1) || (SDL_MINOR_VERSION > 2) || (SDL_PATCHLEVEL > 9)
	if(yuv.enabled) {
		const SDL_version	*linked=sdl.Linked_Version();
		if(linked->major > 1 || linked->minor > 2 || linked->patch > 9) {
			yuv.screen_width=sdl.initial_videoinfo.current_w;
			yuv.screen_height=sdl.initial_videoinfo.current_h;
		}
	}
#endif
	sdl_init_mode(3);
	if(yuv.enabled && yuv.overlay==NULL) {
		fprintf(stderr, "YUV Enabled, but overlay is NULL\n");
		sdl_init_good=0;
	}
	sdl_user_func_ret(SDL_USEREVENT_INIT);

	if(sdl_init_good) {
		cio_api.mode=fullscreen?CIOLIB_MODE_SDL_FULLSCREEN:CIOLIB_MODE_SDL;
#ifdef _WIN32
		FreeConsole();
#endif
#if !defined(NO_X) && defined(__unix__)
		dl=xp_dlopen(libnames,RTLD_LAZY|RTLD_GLOBAL,7);
		if(dl!=NULL) {
			sdl_x11available=TRUE;
			if(sdl_x11available && (sdl_x11.XFree=xp_dlsym(dl,XFree))==NULL) {
				xp_dlclose(dl);
				sdl_x11available=FALSE;
			}
			if(sdl_x11available && (sdl_x11.XGetSelectionOwner=xp_dlsym(dl,XGetSelectionOwner))==NULL) {
				xp_dlclose(dl);
				sdl_x11available=FALSE;
			}
			if(sdl_x11available && (sdl_x11.XConvertSelection=xp_dlsym(dl,XConvertSelection))==NULL) {
				xp_dlclose(dl);
				sdl_x11available=FALSE;
			}
			if(sdl_x11available && (sdl_x11.XGetWindowProperty=xp_dlsym(dl,XGetWindowProperty))==NULL) {
				xp_dlclose(dl);
				sdl_x11available=FALSE;
			}
			if(sdl_x11available && (sdl_x11.XChangeProperty=xp_dlsym(dl,XChangeProperty))==NULL) {
				xp_dlclose(dl);
				sdl_x11available=FALSE;
			}
			if(sdl_x11available && (sdl_x11.XSendEvent=xp_dlsym(dl,XSendEvent))==NULL) {
				xp_dlclose(dl);
				sdl_x11available=FALSE;
			}
			if(sdl_x11available && (sdl_x11.XSetSelectionOwner=xp_dlsym(dl,XSetSelectionOwner))==NULL) {
				xp_dlclose(dl);
				sdl_x11available=FALSE;
			}
		}
		if(sdl_x11available)
			sdl.EventState(SDL_SYSWMEVENT, SDL_ENABLE);
#endif
		return(0);
	}

	return(-1);
}
Esempio n. 15
0
/********************* Main*/
int omain(int argc, char *argv[]){
	int i, cnt, cntt, cnttt, way;
	static char file[MAXC], attr[MAXC], val[MAXC], *p, *binver;
	#if defined(ALLEGRO_WINDOWS)
	binver = "Windows binary";
	#elif defined(ALLEGRO_DOS)
	binver = "DOS binary";
	#elif defined(ALLEGRO_LINUX)
	binver = "Linux binary";
	#elif defined(ALLEGRO_BEOS)
	binver = "BEOS binary";
	#elif defined(ALLEGRO_QNX)
	binver = "QNX binary";
	#elif defined(ALLEGRO_UNIX)
	binver = "UNIX binary";
	#elif defined(ALLEGRO_MPW)
	binver = "MacOS binary";
	#else
	binver = "Unknown binary";
	#endif
	printf("%s %s\n","\nO2EM v" O2EM_VERSION " " RELEASE_DATE "  - ", binver);
	printf("Free Odyssey2 / Videopac+ Emulator - http://o2em.sourceforge.net\n");
	printf("Created by Daniel Boris (c)1996/1998\n");
    printf("Developed by:\n");
	printf("     Andre de la Rocha since version 0.80\n");
	printf("     Arlindo M. de Oliveira since version 1.16\n");
    printf("\n");

    app_data.debug = 0;
	app_data.stick[0] = app_data.stick[1] = 1;
	app_data.sticknumber[0] = app_data.sticknumber[1] = 0;
	set_defjoykeys(0,0);
	set_defjoykeys(1,1);
	set_defsystemkeys();
	app_data.bank = 0;
	app_data.limit = 1;
	app_data.sound_en = 1;
	app_data.speed = 100;
	app_data.wsize = 2;
	#ifdef ALLEGRO_DOS
	app_data.fullscreen = 1;
	#else
	app_data.fullscreen = 0;
	#endif
	app_data.scanlines = 0;
	app_data.voice = 1;
	app_data.window_title = "O2EM v" O2EM_VERSION;
	app_data.svolume = 100;
	app_data.vvolume = 100;
	app_data.filter = 0;
	app_data.exrom = 0;
	app_data.three_k = 0;
	app_data.crc = 0;
	app_data.scshot = scshot;
	app_data.statefile = statefile;
	app_data.euro = 0;
	app_data.openb = 0;
	app_data.vpp = 0;
	app_data.bios = 0;
	app_data.scoretype = 0;
	app_data.scoreaddress = 0;
	app_data.default_highscore = 0;
	app_data.breakpoint = 65535;
	app_data.megaxrom = 0;
	strcpy(file,"");
	strcpy(file_l,"");
	strcpy(bios_l,"");
    strcpy(bios,"");
	strcpy(scshot,"");
	strcpy(statefile,"");
    strcpy(xrom,"");
	strcpy(scorefile,"highscore.txt");
	read_default_config();
	if (argc >= 2){
    for(i=1; i<argc; i++) {
		if (argv[i][0] != '-') 	{
			strncat(file,argv[i],MAXC-1);
	        file[MAXC-1]=0;
	        strcpy(file_v,file);
		} else {
			p=strtok(argv[i],"=");
	        if (p){
				strncpy(attr,p+1,MAXC-1);
				attr[MAXC-1]=0;
			   } else
				strcpy(attr,"");
			    p=strtok(NULL,"=");
			if (p){
				strncpy(val,p,MAXC-1);
				val[MAXC-1]=0;
			    if (!strcmp(attr,"romdir")||!strcmp(attr,"ROMDIR"))
                   {
                    strcpy(romdir,val);
                    strcat(romdir,file);
                    strcpy(file,romdir);
                    strcpy(romdir,val);
                   }
                if (!strcmp(attr,"biosdir")||!strcmp(attr,"BIOSDIR"))
                   {
                    strcpy(biosdir,val);
                   }                                       
            } else
			strcpy(val,"");
			strlwr(attr);
			if (!parse_option(attr, val)) exit(EXIT_FAILURE);
		}
    }
    if (helpflag) helpus();
    if (strlen(file)==0) {
		fprintf(stderr,"Error: file name missing\n");
		exit(EXIT_FAILURE);
	}

#ifdef __LIBRETRO__
sprintf(statefile,"%s.state\0",file);
#endif
	printf("Starting emulation ...\n");
#ifndef __LIBRETRO__
	allegro_init();
	install_timer();
#endif
	init_audio();

#ifndef __LIBRETRO__
	printf("Using Allegro %s\n",allegro_id);
#endif 


/********************** ROMs if Launcher running... */
    k = strchr(romdir, '/'); 

    launcher_flag_r = strchr(file, '\\');

    if (k != 0) {
                 strcpy (xrom,romdir);
                }
                else if (!launcher_flag_r)
                        {

                        strcpy(xrom,"roms/");
                        strcpy(romdir,file);
#ifndef __LIBRETRO__
                        strcpy(file,xrom);
                        strcat(file,romdir);
#endif
                        strcpy(romdir,xrom);

                        }
                        else
                        {    
         
                        cnt = 0;
                        cntt = 0;
                        cnttt = 0;
                        way = 0;
                        for (cnt=0; file[cnt] != '\0'; cnt=cnt+1) 
                        { 
                        if ( file[cnt] == '\\' ) 
                           {
                           cnttt = cnt;
                           }
                        } 
                        for (cnt=0; cnt<=cnttt; cnt++)
                        { 
                        file_l[cnt] = file[cnt];
                        } 

                        strcpy (romdir,file_l);
                        strcpy (xrom,romdir);
                        }

#ifdef __LIBRETRO__
#ifdef AND
	sprintf(xrom,"%s\0","/mnt/sdcard/O2EM/roms/");
	strcpy(romdir,xrom);
#else
	sprintf(xrom,"%s\0","./roms/");
	strcpy(romdir,xrom);
#endif
#endif


    file_name(xrom);

    if (contax < 3)
                 {
                 printf("\nROMs directory empty!\n");
                 exit(EXIT_FAILURE);
                 }

    app_data.crc = crc32_file(file);

    crcx = app_data.crc;
    suck_roms(); 

/********************** BIOSs if Launcher running... */     
launcher_flag_b = strchr(bios, '\\');

if (!launcher_flag_b){
    k = strchr(biosdir, '/');

    if (k != 0) {    
                 strcpy (xbios,biosdir);
                }
                else           
                        {
                        strcpy (xbios,"bios/");
                        strcpy (biosdir,xbios);
                        }
#ifdef __LIBRETRO__
#ifdef AND
	sprintf(xbios,"%s\0","/mnt/sdcard/O2EM/bios/");
	strcpy (biosdir,xbios);
#else	
	sprintf(xbios,"%s\0","./bios/");
	strcpy (biosdir,xbios);
#endif
#endif

    file_name(xbios);

    if (contax < 3)
                 {
                 printf("\nBIOS directory empty!\n");
                 exit(EXIT_FAILURE);                 
                 }

    suck_bios();

    c_j = strcmp(bios,"jopac");
    if ((rom_f!=1) && (c_j!=0)) strcpy(bios,g7400);
    if ((!o2flag) && (!jopflag) && (!c52flag) && (!g74flag))
                                              {
                                             printf("\ndir '%s' without BIOS !",biosdir);
                                             exit(EXIT_FAILURE);
                                              }
    printf("BIOS found:\n");
    if (!strcmp(bios,"g7400")){
                               strcpy(bios,g7400);
                               if (g74flag != 1) {
                                             printf("\nG7400 BIOS not found !");
                                             exit(EXIT_FAILURE);
                                             } 
                               }
    if (g74flag) printf("  G7400 VP+\n");
    if (!strcmp(bios,"c52")){ 
                             strcpy(bios,c52);
                             if (c52flag != 1) {
                                             printf("\nC52 BIOS not found !");
                                             exit(EXIT_FAILURE);
                                             } 
                                 }
    if (c52flag) printf("  C52\n");
    if (!strcmp(bios,"jopac")){
                               strcpy(bios,jopac);
                               if (jopflag != 1) {
                                          printf("\nJOPAC BIOS not found !");
                                          exit(EXIT_FAILURE);
                                             } 
                               }
    if (jopflag) printf("  JOPAC VP+\n");
    if ((!strcmp(bios,"")) || (!strcmp(bios,"o2rom")))
                            {
                            strcpy(bios,odyssey2);
                            if ((!o2flag)&&(!c52flag)&&(rom_f)){
                                             printf("Odyssey2 BIOS not found !\n");
                                             exit(EXIT_FAILURE);
                                             } 
                            if ((!o2flag)&&(c52flag)&&(rom_f)){
                                             printf("\nOdyssey2 BIOS not found !\n");
                                             printf("Loading C52 BIOS ... ");
                                             strcpy(bios,c52);
                                             }
                            }
    if (o2flag) printf("  Odyssey 2\n");
    }                                           
    if (launcher_flag_b)
       {
       identify_bios(bios);
                if (rom_f!=1)
                   {
                   if (!((g74flag)||(jopflag)))
                      {
                      fprintf(stderr,"\nError: ROM only VP+ BIOS");
                      exit(EXIT_FAILURE);
                      }
                   }
       }      


      if (!launcher_flag_b)
                  {  
                  if (rom_f!=1)
                     {  
                     if (!((g74flag)||(jopflag)))
                         {
                         printf("\nROM only VP+ BIOS\n");
                         exit(EXIT_FAILURE);
                         }
                     if (!(g74flag))
                         {
                         printf("\nVP+ G7400 BIOS not found !");
                         printf("\nLoading VP+ Jopac BIOS ...");
                         strcpy(bios,jopac);
                         }
                     }
                  }
    load_bios(bios);

	load_cart(file);
	if (app_data.voice) load_voice_samples(path);

	init_display();

	init_cpu();

	init_system();

	set_score(app_data.scoretype, app_data.scoreaddress, app_data.default_highscore);
	int stateError;
	if ((stateError=loadstate(app_data.statefile))==0)
	{
		printf("Savefile loaded.");
	}
	else if (stateError>=199)
	{
		if (stateError==199) fprintf(stderr,"Wrong ROM-File for Savefile.");
		else if (stateError==200+ROM_O2) fprintf(stderr,"Wrong BIOS for Savefile: O2ROM needed.");
		else if (stateError==200+ROM_G7400) fprintf(stderr,"Wrong BIOS for Savefile: G7400 ROM needed.");
		else if (stateError==200+ROM_C52) fprintf(stderr,"Wrong BIOS for Savefile: C52 ROM needed.");
		else if (stateError==200+ROM_JOPAC) fprintf(stderr,"Wrong BIOS for Savefile: JOPAC ROM needed.");
		else fprintf(stderr,"Wrong BIOS for Savefile: UNKNOWN ROM needed.");
		return(0);
	}
	if (app_data.debug) key_debug=1;
	#ifndef _DEBUG
	#ifdef ALLEGRO_WINDOWS
	FreeConsole();
	#endif
	#endif

#ifdef __LIBRETRO__
return 1;
#endif
	run();

    if (app_data.scoretype!=0) save_highscore(get_score(app_data.scoretype, app_data.scoreaddress), scorefile);
	exit(EXIT_SUCCESS);
 }
if (!strcmp(attr,"help")||!strcmp(attr,"HELP")) helpus();
printf("type o2em -help");
exit(EXIT_SUCCESS);
}
Esempio n. 16
0
 ~ConsoleAttacher() {
     if(isAttached) {
         FreeConsole();
     }
     isAttached = false;
 }
Esempio n. 17
0
VOID CConsole::Free()
{
	FreeConsole();
}
Esempio n. 18
0
int main( int argc, char * * argv )
{
#ifdef LMMS_DEBUG_FPE
	// Enable exceptions for certain floating point results
	feenableexcept( FE_INVALID   |
			FE_DIVBYZERO |
			FE_OVERFLOW  |
			FE_UNDERFLOW);

	// Install the trap handler
	// register signal SIGFPE and signal handler
	signal(SIGFPE, signalHandler);
#endif

#ifdef LMMS_BUILD_WIN32
	// Don't touch redirected streams here
	// GetStdHandle should be called before AttachConsole
	HANDLE hStdIn = GetStdHandle(STD_INPUT_HANDLE);
	HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
	HANDLE hStdErr = GetStdHandle(STD_ERROR_HANDLE);
	FILE *fIn, *fOut, *fErr;
	// Enable console output if available
	if (AttachConsole(ATTACH_PARENT_PROCESS))
	{
		if (!hStdIn)
		{
			freopen_s(&fIn, "CONIN$", "r", stdin);
		}
		if (!hStdOut)
		{
			freopen_s(&fOut, "CONOUT$", "w", stdout);
		}
		if (!hStdErr)
		{
			freopen_s(&fErr, "CONOUT$", "w", stderr);
		}
	}
	// Make Qt's debug message handlers work
	qInstallMessageHandler(consoleMessageHandler);
#endif

	// initialize memory managers
	NotePlayHandleManager::init();

	// intialize RNG
	srand( getpid() + time( 0 ) );

	disable_denormals();

	bool coreOnly = false;
	bool fullscreen = true;
	bool exitAfterImport = false;
	bool allowRoot = false;
	bool renderLoop = false;
	bool renderTracks = false;
	QString fileToLoad, fileToImport, renderOut, profilerOutputFile, configFile;

	// first of two command-line parsing stages
	for( int i = 1; i < argc; ++i )
	{
		QString arg = argv[i];

		if( arg == "--help"    || arg == "-h" ||
		    arg == "--version" || arg == "-v" ||
		    arg == "render" || arg == "--render" || arg == "-r" )
		{
			coreOnly = true;
		}
		else if( arg == "rendertracks" || arg == "--rendertracks" )
		{
			coreOnly = true;
			renderTracks = true;
		}
		else if( arg == "--allowroot" )
		{
			allowRoot = true;
		}
		else if( arg == "--geometry" || arg == "-geometry")
		{
			if( arg == "--geometry" )
			{
				// Delete the first "-" so Qt recognize the option
				strcpy(argv[i], "-geometry");
			}
			// option -geometry is filtered by Qt later,
			// so we need to check its presence now to
			// determine, if the application should run in
			// fullscreen mode (default, no -geometry given).
			fullscreen = false;
		}
	}

#if !defined(LMMS_BUILD_WIN32) && !defined(LMMS_BUILD_HAIKU)
	if ( ( getuid() == 0 || geteuid() == 0 ) && !allowRoot )
	{
		printf( "LMMS cannot be run as root.\nUse \"--allowroot\" to override.\n\n" );
		return EXIT_FAILURE;
	}
#endif
#ifdef LMMS_BUILD_LINUX
	// don't let OS steal the menu bar. FIXME: only effective on Qt4
	QCoreApplication::setAttribute( Qt::AA_DontUseNativeMenuBar );
#endif
#if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
	QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
	QCoreApplication * app = coreOnly ?
			new QCoreApplication( argc, argv ) :
					new MainApplication( argc, argv );

	Mixer::qualitySettings qs( Mixer::qualitySettings::Mode_HighQuality );
	OutputSettings os( 44100, OutputSettings::BitRateSettings(160, false), OutputSettings::Depth_16Bit, OutputSettings::StereoMode_JointStereo );
	ProjectRenderer::ExportFileFormats eff = ProjectRenderer::WaveFile;

	// second of two command-line parsing stages
	for( int i = 1; i < argc; ++i )
	{
		QString arg = argv[i];

		if( arg == "--version" || arg == "-v" )
		{
			printVersion( argv[0] );
			return EXIT_SUCCESS;
		}
		else if( arg == "--help" || arg  == "-h" )
		{
			printHelp();
			return EXIT_SUCCESS;
		}
		else if( arg == "upgrade" || arg == "--upgrade" || arg  == "-u")
		{
			++i;

			if( i == argc )
			{
				return noInputFileError();
			}


			DataFile dataFile( QString::fromLocal8Bit( argv[i] ) );

			if( argc > i+1 ) // output file specified
			{
				dataFile.writeFile( QString::fromLocal8Bit( argv[i+1] ) );
			}
			else // no output file specified; use stdout
			{
				QTextStream ts( stdout );
				dataFile.write( ts );
				fflush( stdout );
			}

			return EXIT_SUCCESS;
		}
		else if( arg == "--allowroot" )
		{
			// Ignore, processed earlier
#ifdef LMMS_BUILD_WIN32
			if( allowRoot )
			{
				printf( "\nOption \"--allowroot\" will be ignored on this platform.\n\n" );
			}
#endif

		}
		else if( arg == "dump" || arg == "--dump" || arg  == "-d" )
		{
			++i;

			if( i == argc )
			{
				return noInputFileError();
			}


			QFile f( QString::fromLocal8Bit( argv[i] ) );
			f.open( QIODevice::ReadOnly );
			QString d = qUncompress( f.readAll() );
			printf( "%s\n", d.toUtf8().constData() );

			return EXIT_SUCCESS;
		}
		else if( arg == "render" || arg == "--render" || arg == "-r" ||
			arg == "rendertracks" || arg == "--rendertracks" )
		{
			++i;

			if( i == argc )
			{
				return noInputFileError();
			}


			fileToLoad = QString::fromLocal8Bit( argv[i] );
			renderOut = fileToLoad;
		}
		else if( arg == "--loop" || arg == "-l" )
		{
			renderLoop = true;
		}
		else if( arg == "--output" || arg == "-o" )
		{
			++i;

			if( i == argc )
			{
				return usageError( "No output file specified" );
			}


			renderOut = QString::fromLocal8Bit( argv[i] );
		}
		else if( arg == "--format" || arg == "-f" )
		{
			++i;

			if( i == argc )
			{
				return usageError( "No output format specified" );
			}


			const QString ext = QString( argv[i] );

			if( ext == "wav" )
			{
				eff = ProjectRenderer::WaveFile;
			}
#ifdef LMMS_HAVE_OGGVORBIS
			else if( ext == "ogg" )
			{
				eff = ProjectRenderer::OggFile;
			}
#endif
#ifdef LMMS_HAVE_MP3LAME
			else if( ext == "mp3" )
			{
				eff = ProjectRenderer::MP3File;
			}
#endif
			else if (ext == "flac")
			{
				eff = ProjectRenderer::FlacFile;
			}
			else
			{
				return usageError( QString( "Invalid output format %1" ).arg( argv[i] ) );
			}
		}
		else if( arg == "--samplerate" || arg == "-s" )
		{
			++i;

			if( i == argc )
			{
				return usageError( "No samplerate specified" );
			}


			sample_rate_t sr = QString( argv[i] ).toUInt();
			if( sr >= 44100 && sr <= 192000 )
			{
				os.setSampleRate(sr);
			}
			else
			{
				return usageError( QString( "Invalid samplerate %1" ).arg( argv[i] ) );
			}
		}
		else if( arg == "--bitrate" || arg == "-b" )
		{
			++i;

			if( i == argc )
			{
				return usageError( "No bitrate specified" );
			}


			int br = QString( argv[i] ).toUInt();

			if( br >= 64 && br <= 384 )
			{
				OutputSettings::BitRateSettings bitRateSettings = os.getBitRateSettings();
				bitRateSettings.setBitRate(br);
				os.setBitRateSettings(bitRateSettings);
			}
			else
			{
				return usageError( QString( "Invalid bitrate %1" ).arg( argv[i] ) );
			}
		}
		else if( arg == "--mode" || arg == "-m" )
		{
			++i;

			if( i == argc )
			{
				return usageError( "No stereo mode specified" );
			}

			QString const mode( argv[i] );

			if( mode == "s" )
			{
				os.setStereoMode(OutputSettings::StereoMode_Stereo);
			}
			else if( mode == "j" )
			{
				os.setStereoMode(OutputSettings::StereoMode_JointStereo);
			}
			else if( mode == "m" )
			{
				os.setStereoMode(OutputSettings::StereoMode_Mono);
			}
			else
			{
				return usageError( QString( "Invalid stereo mode %1" ).arg( argv[i] ) );
			}
		}
		else if( arg =="--float" || arg == "-a" )
		{
			os.setBitDepth(OutputSettings::Depth_32Bit);
		}
		else if( arg == "--interpolation" || arg == "-i" )
		{
			++i;

			if( i == argc )
			{
				return usageError( "No interpolation method specified" );
			}


			const QString ip = QString( argv[i] );

			if( ip == "linear" )
			{
		qs.interpolation = Mixer::qualitySettings::Interpolation_Linear;
			}
			else if( ip == "sincfastest" )
			{
		qs.interpolation = Mixer::qualitySettings::Interpolation_SincFastest;
			}
			else if( ip == "sincmedium" )
			{
		qs.interpolation = Mixer::qualitySettings::Interpolation_SincMedium;
			}
			else if( ip == "sincbest" )
			{
		qs.interpolation = Mixer::qualitySettings::Interpolation_SincBest;
			}
			else
			{
				return usageError( QString( "Invalid interpolation method %1" ).arg( argv[i] ) );
			}
		}
		else if( arg == "--oversampling" || arg == "-x" )
		{
			++i;

			if( i == argc )
			{
				return usageError( "No oversampling specified" );
			}


			int o = QString( argv[i] ).toUInt();

			switch( o )
			{
				case 1:
		qs.oversampling = Mixer::qualitySettings::Oversampling_None;
		break;
				case 2:
		qs.oversampling = Mixer::qualitySettings::Oversampling_2x;
		break;
				case 4:
		qs.oversampling = Mixer::qualitySettings::Oversampling_4x;
		break;
				case 8:
		qs.oversampling = Mixer::qualitySettings::Oversampling_8x;
		break;
				default:
				return usageError( QString( "Invalid oversampling %1" ).arg( argv[i] ) );
			}
		}
		else if( arg == "--import" )
		{
			++i;

			if( i == argc )
			{
				return usageError( "No file specified for importing" );
			}

			fileToImport = QString::fromLocal8Bit( argv[i] );

			// exit after import? (only for debugging)
			if( QString( argv[i + 1] ) == "-e" )
			{
				exitAfterImport = true;
				++i;
			}
		}
		else if( arg == "--profile" || arg == "-p" )
		{
			++i;

			if( i == argc )
			{
				return usageError( "No profile specified" );
			}


			profilerOutputFile = QString::fromLocal8Bit( argv[i] );
		}
		else if( arg == "--config" || arg == "-c" )
		{
			++i;

			if( i == argc )
			{
				return usageError( "No configuration file specified" );
			}

			configFile = QString::fromLocal8Bit( argv[i] );
		}
		else
		{
			if( argv[i][0] == '-' )
			{
				return usageError( QString( "Invalid option %1" ).arg( argv[i] ) );
			}
			fileToLoad = QString::fromLocal8Bit( argv[i] );
		}
	}

	// Test file argument before continuing
	if( !fileToLoad.isEmpty() )
	{
		fileCheck( fileToLoad );
	}
	else if( !fileToImport.isEmpty() )
	{
		fileCheck( fileToImport );
	}

	ConfigManager::inst()->loadConfigFile(configFile);

	// Hidden settings
	MixHelpers::setNaNHandler( ConfigManager::inst()->value( "app",
						"nanhandler", "1" ).toInt() );

	// set language
	QString pos = ConfigManager::inst()->value( "app", "language" );
	if( pos.isEmpty() )
	{
		pos = QLocale::system().name().left( 2 );
	}

#ifdef LMMS_BUILD_WIN32
#undef QT_TRANSLATIONS_DIR
#define QT_TRANSLATIONS_DIR ConfigManager::inst()->localeDir()
#endif

#ifdef QT_TRANSLATIONS_DIR
	// load translation for Qt-widgets/-dialogs
	loadTranslation( QString( "qt_" ) + pos,
					QString( QT_TRANSLATIONS_DIR ) );
#endif
	// load actual translation for LMMS
	loadTranslation( pos );


	// try to set realtime priority
#ifdef LMMS_BUILD_LINUX
#ifdef LMMS_HAVE_SCHED_H
#ifndef __OpenBSD__
	struct sched_param sparam;
	sparam.sched_priority = ( sched_get_priority_max( SCHED_FIFO ) +
				sched_get_priority_min( SCHED_FIFO ) ) / 2;
	if( sched_setscheduler( 0, SCHED_FIFO, &sparam ) == -1 )
	{
		printf( "Notice: could not set realtime priority.\n" );
	}
#endif
#endif
#endif

#ifdef LMMS_BUILD_WIN32
	if( !SetPriorityClass( GetCurrentProcess(), HIGH_PRIORITY_CLASS ) )
	{
		printf( "Notice: could not set high priority.\n" );
	}
#endif

#if _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_SOURCE
	struct sigaction sa;
	sa.sa_handler = SIG_IGN;
	sa.sa_flags = SA_SIGINFO;
	if ( sigemptyset( &sa.sa_mask ) )
	{
		fprintf( stderr, "Signal initialization failed.\n" );
	}
	if ( sigaction( SIGPIPE, &sa, NULL ) )
	{
		fprintf( stderr, "Signal initialization failed.\n" );
	}
#endif

	bool destroyEngine = false;

	// if we have an output file for rendering, just render the song
	// without starting the GUI
	if( !renderOut.isEmpty() )
	{
		Engine::init( true );
		destroyEngine = true;

		printf( "Loading project...\n" );
		Engine::getSong()->loadProject( fileToLoad );
		if( Engine::getSong()->isEmpty() )
		{
			printf("The project %s is empty, aborting!\n", fileToLoad.toUtf8().constData() );
			exit( EXIT_FAILURE );
		}
		printf( "Done\n" );

		Engine::getSong()->setExportLoop( renderLoop );

		// when rendering multiple tracks, renderOut is a directory
		// otherwise, it is a file, so we need to append the file extension
		if ( !renderTracks )
		{
			renderOut = baseName( renderOut ) +
				ProjectRenderer::getFileExtensionFromFormat(eff);
		}

		// create renderer
		RenderManager * r = new RenderManager( qs, os, eff, renderOut );
		QCoreApplication::instance()->connect( r,
				SIGNAL( finished() ), SLOT( quit() ) );

		// timer for progress-updates
		QTimer * t = new QTimer( r );
		r->connect( t, SIGNAL( timeout() ),
				SLOT( updateConsoleProgress() ) );
		t->start( 200 );

		if( profilerOutputFile.isEmpty() == false )
		{
			Engine::mixer()->profiler().setOutputFile( profilerOutputFile );
		}

		// start now!
		if ( renderTracks )
		{
			r->renderTracks();
		}
		else
		{
			r->renderProject();
		}
	}
	else // otherwise, start the GUI
	{
		new GuiApplication();

		// re-intialize RNG - shared libraries might have srand() or
		// srandom() calls in their init procedure
		srand( getpid() + time( 0 ) );

		// recover a file?
		QString recoveryFile = ConfigManager::inst()->recoveryFile();

		bool recoveryFilePresent = QFileInfo( recoveryFile ).exists() &&
				QFileInfo( recoveryFile ).isFile();
		bool autoSaveEnabled =
			ConfigManager::inst()->value( "ui", "enableautosave" ).toInt();
		if( recoveryFilePresent )
		{
			QMessageBox mb;
			mb.setWindowTitle( MainWindow::tr( "Project recovery" ) );
			mb.setText( QString(
				"<html>"
				"<p style=\"margin-left:6\">%1</p>"
				"<table cellpadding=\"3\">"
				"  <tr>"
				"    <td><b>%2</b></td>"
				"    <td>%3</td>"
				"  </tr>"
				"  <tr>"
				"    <td><b>%4</b></td>"
				"    <td>%5</td>"
				"  </tr>"
				"</table>"
				"</html>" ).arg(
				MainWindow::tr( "There is a recovery file present. "
					"It looks like the last session did not end "
					"properly or another instance of LMMS is "
					"already running. Do you want to recover the "
					"project of this session?" ),
				MainWindow::tr( "Recover" ),
				MainWindow::tr( "Recover the file. Please don't run "
					"multiple instances of LMMS when you do this." ),
				MainWindow::tr( "Discard" ),
				MainWindow::tr( "Launch a default session and delete "
					"the restored files. This is not reversible." )
							) );

			mb.setIcon( QMessageBox::Warning );
			mb.setWindowIcon( embed::getIconPixmap( "icon_small" ) );
			mb.setWindowFlags( Qt::WindowCloseButtonHint );

			QPushButton * recover;
			QPushButton * discard;
			QPushButton * exit;

			// setting all buttons to the same roles allows us
			// to have a custom layout
			discard = mb.addButton( MainWindow::tr( "Discard" ),
								QMessageBox::AcceptRole );
			recover = mb.addButton( MainWindow::tr( "Recover" ),
								QMessageBox::AcceptRole );

			// have a hidden exit button
			exit = mb.addButton( "", QMessageBox::RejectRole);
			exit->setVisible(false);

			// set icons
			recover->setIcon( embed::getIconPixmap( "recover" ) );
			discard->setIcon( embed::getIconPixmap( "discard" ) );

			mb.setDefaultButton( recover );
			mb.setEscapeButton( exit );

			mb.exec();
			if( mb.clickedButton() == discard )
			{
				gui->mainWindow()->sessionCleanup();
			}
			else if( mb.clickedButton() == recover ) // Recover
			{
				fileToLoad = recoveryFile;
				gui->mainWindow()->setSession( MainWindow::SessionState::Recover );
			}
			else // Exit
			{
				return 0;
			}
		}

		// first show the Main Window and then try to load given file

		// [Settel] workaround: showMaximized() doesn't work with
		// FVWM2 unless the window is already visible -> show() first
		gui->mainWindow()->show();
		if( fullscreen )
		{
			gui->mainWindow()->showMaximized();
		}

		// Handle macOS-style FileOpen QEvents
		QString queuedFile = static_cast<MainApplication *>( app )->queuedFile();
		if ( !queuedFile.isEmpty() ) {
			fileToLoad = queuedFile;
		}

		if( !fileToLoad.isEmpty() )
		{
			if( fileToLoad == recoveryFile )
			{
				Engine::getSong()->createNewProjectFromTemplate( fileToLoad );
			}
			else
			{
				Engine::getSong()->loadProject( fileToLoad );
			}
		}
		else if( !fileToImport.isEmpty() )
		{
			ImportFilter::import( fileToImport, Engine::getSong() );
			if( exitAfterImport )
			{
				return EXIT_SUCCESS;
			}
		}
		// If enabled, open last project if there is one. Else, create
		// a new one.
		else if( ConfigManager::inst()->
				value( "app", "openlastproject" ).toInt() &&
			!ConfigManager::inst()->
				recentlyOpenedProjects().isEmpty() &&
				!recoveryFilePresent )
		{
			QString f = ConfigManager::inst()->
					recentlyOpenedProjects().first();
			QFileInfo recentFile( f );

			if ( recentFile.exists() &&
				recentFile.suffix().toLower() != "mpt" )
			{
				Engine::getSong()->loadProject( f );
			}
			else
			{
				Engine::getSong()->createNewProject();
			}
		}
		else
		{
			Engine::getSong()->createNewProject();
		}

		// Finally we start the auto save timer and also trigger the
		// autosave one time as recover.mmp is a signal to possible other
		// instances of LMMS.
		if( autoSaveEnabled )
		{
			gui->mainWindow()->autoSaveTimerReset();
		}
	}

	const int ret = app->exec();
	delete app;

	if( destroyEngine )
	{
		Engine::destroy();
	}

	// ProjectRenderer::updateConsoleProgress() doesn't return line after render
	if( coreOnly )
	{
		printf( "\n" );
	}

#ifdef LMMS_BUILD_WIN32
	// Cleanup console
	HWND hConsole = GetConsoleWindow();
	if (hConsole)
	{
		SendMessage(hConsole, WM_CHAR, (WPARAM)VK_RETURN, (LPARAM)0);
		FreeConsole();
	}
#endif

	return ret;
}
Esempio n. 19
0
static int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) {
	AllocConsole(); //create a console
	freopen( "conin$","r",stdin );
	freopen( "conout$","w",stdout );
	freopen( "conout$","w",stderr );
	printf( "Program Started, console initialized\n" );

	const char WindowName[] = "Wet Clay";

	int64 mSecsPerFrame = 16; //60FPS
	System system = { };
	system.windowHeight = 680;
	system.windowWidth = 1080;
	system.ReadWholeFile = &ReadWholeFile;
	system.GetMostRecentMatchingFile = &GetMostRecentMatchingFile;
	system.TrackFileUpdates = &TrackFileUpdates;
	system.DidFileUpdate = &DidFileUpdate;
	system.WriteFile = &WriteFile;
	system.HasFocus = &HasFocus;

	//Center position of window
	uint16 fullScreenWidth = GetSystemMetrics( SM_CXSCREEN );
	uint16 fullScreenHeight = GetSystemMetrics( SM_CYSCREEN );
	uint16 windowPosX = ( fullScreenWidth / 2 ) - (system.windowWidth / 2 );
	uint16 windowPosY = ( fullScreenHeight / 2 ) - (system.windowHeight / 2 );

	WNDCLASSEX wc = { };
	wc.cbSize = sizeof(WNDCLASSEX);
	wc.style = CS_OWNDC;
	wc.lpfnWndProc = WndProc;
	wc.cbClsExtra = 0;
	wc.cbWndExtra = 0;
	wc.hInstance = hInstance;
	wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
	wc.hCursor = LoadCursor(NULL, IDC_ARROW);
	wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
	wc.lpszMenuName = NULL;
	wc.lpszClassName = WindowName;
	wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);

	if( !RegisterClassEx( &wc ) ) {
		printf( "Failed to register class\n" );
		return -1;
	}

	EnableCrashingOnCrashes();
 
	// at this point WM_CREATE message is sent/received
	// the WM_CREATE branch inside WinProc function will execute here
	HWND hwnd = CreateWindowEx(
		0, 
		WindowName, 
		"Wet Clay App", 
		WS_BORDER, 
		windowPosX, 
		windowPosY, 
		system.windowWidth, 
		system.windowHeight,
		NULL, 
		NULL, 
		hInstance, 
		NULL
	);

	RECT windowRect = { };
	GetClientRect( hwnd, &windowRect );

	SetWindowLong( hwnd, GWL_STYLE, 0 );
	ShowWindow ( hwnd, SW_SHOWNORMAL );
	UpdateWindow( hwnd );

	LARGE_INTEGER timerResolution;
	BOOL canSupportHiResTimer = QueryPerformanceFrequency( &timerResolution );
	assert( canSupportHiResTimer );

	size_t systemsMemorySize = MEGABYTES( 8 );
	Stack gameSlab;
	gameSlab.size = SIZEOF_GLOBAL_HEAP + systemsMemorySize;
	gameSlab.start = VirtualAlloc( 
		NULL, 
		gameSlab.size, 
		MEM_COMMIT | MEM_RESERVE, 
		PAGE_EXECUTE_READWRITE 
	);
	gameSlab.current = gameSlab.start;
	assert( gameSlab.start != NULL );

	Stack systemsMemory = AllocateNewStackFromStack( &gameSlab, systemsMemorySize );

	InitWin32WorkerThread( &systemsMemory );

	GLRendererGlobalState glRendererStorage = { };
	globalGLRendererStorageRef = &glRendererStorage;
	GLRenderDriver glDriver = Win32InitGLRenderer( hwnd, &system, globalGLRendererStorageRef );
	Win32Sound win32Sound = Win32InitSound( hwnd, 60, &systemsMemory );

	void* imguistate = InitImGui_LimeStone(	&systemsMemory,	(RenderDriver*)&glDriver, system.windowWidth, system.windowHeight );

	printf( "Remaining System Memory: %Id\n", SPACE_IN_STACK( (&gameSlab) ) );

	LoadGameCode( &gameapp );
	assert( gameapp.GameInit != NULL );

	fileTracking = { };
	fileTracking.writeHead = &fileTracking.stringBuffer[0];

	int dllTrackingIndex = TrackFileUpdates( GAME_CODE_FILEPATH );
	assert( dllTrackingIndex != -1 );

	void* gameMemoryPtr = gameapp.GameInit( 
		&gameSlab, 
		(RenderDriver*)&glDriver,
		&win32Sound.driver,
		&system
	);

	appIsRunning = true;

	InputState inputSnapshot1 = { };
	InputState inputSnapshot2 = { };
	inputSnapshot1.prevState = &inputSnapshot2;
	inputSnapshot2.prevState = &inputSnapshot1;
	InputState* currentSnapshotStorage = &inputSnapshot1;

	MSG Msg;
	while( appIsRunning ) {
		if( DidFileUpdate( dllTrackingIndex ) ) {
			LoadGameCode( &gameapp );
		}

		static LARGE_INTEGER startTime;
		LARGE_INTEGER elapsedTime;
		LARGE_INTEGER lastTime = startTime;
		QueryPerformanceCounter( &startTime );

		elapsedTime.QuadPart = startTime.QuadPart - lastTime.QuadPart;
		elapsedTime.QuadPart *= 1000;
		elapsedTime.QuadPart /= timerResolution.QuadPart;

		//GAME LOOP
		if(	gameapp.UpdateAndRender != NULL && gameapp.MixSound != NULL ) {

			currentSnapshotStorage = currentSnapshotStorage->prevState;
		    QueryInput( 
		    	system.windowWidth, 
		    	system.windowHeight,
		    	windowPosX,
		    	windowPosY,
		    	currentSnapshotStorage
		    );
		    keypressHistoryIndex = 0;

		    UpdateImgui( currentSnapshotStorage, imguistate, system.windowWidth, system.windowHeight );

			appIsRunning = gameapp.UpdateAndRender( 
				gameMemoryPtr, 
				(float)elapsedTime.QuadPart, 
				currentSnapshotStorage,
				&win32Sound.driver,
				(RenderDriver*)&glDriver,
				&system,
				imguistate
			);

		    PushAudioToSoundCard( &gameapp, &win32Sound );

		    ImGui::Render();

			BOOL swapBufferSuccess = SwapBuffers( deviceContext );
			glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
		} else {
			printf( "Game code was not loaded...\n" );
		}

		//Windows Message pump is here, so if there is a system level Close or
		//Destory command, the UpdateAndRender method does not reset the appIsRunning
		//flag to true
		while( PeekMessage( &Msg, NULL, 0, 0, PM_REMOVE ) ) {
			TranslateMessage( &Msg );
			DispatchMessage( &Msg );
		}

		//End loop timer query
		LARGE_INTEGER endTime, computeTime;
		{
			QueryPerformanceCounter( &endTime );
			computeTime.QuadPart = endTime.QuadPart - startTime.QuadPart;
			computeTime.QuadPart *= 1000;
			computeTime.QuadPart /= timerResolution.QuadPart;
		}

		if( computeTime.QuadPart <= mSecsPerFrame ) {
			Sleep(mSecsPerFrame - computeTime.QuadPart );
		} else {
			printf("Didn't sleep, compute was %ld\n", computeTime.QuadPart );
		}
	};

	FreeConsole();

	return Msg.wParam;
}
Esempio n. 20
0
int WINAPI WinMain (HINSTANCE hInstance,
					HINSTANCE legacy,
					LPSTR lpCmdLine,
					int nCmdShow)
{
	__EXPN__ = new ExceptionData_t (20, "ExceptionErrors.txt");
	srand (static_cast<UINT>(time (nullptr)));

	

	try
	{
		WindowClass window (int (SCREEN_WIDTH * 0.98f), int (SCREEN_HEIGHT * 0.9f));
		AllocConsole ();
		FILE* file = nullptr;
		freopen_s (&file, "CONOUT$", "w", stdout);

		Direct3DProcessor d3dProc (&window);
		d3dProc.ApplyBlendState (d3dProc.AddBlendState (true));

		//d3dProc.ApplyRasterizerState (d3dProc.AddRasterizerState (false, false, true));

		//XMMATRIX world = XMMatrixTranslation (0.0f, 0.0f, 0.0f);
		CamInfo_t camInfo = { { BASE_X, BASE_Y, BASE_Z, 1.0f }, {}, 0.01f , 0.0f};
		Direct3DCamera cam (&window,
							camInfo.pos.x, camInfo.pos.y, camInfo.pos.z,
							0.0f, -1.0f, 1.0f,
							0.0, 1.0f, 0.0f,
							FOV, 0.5f);

		XMStoreFloat4(&camInfo.dir, cam.GetDir());

		ConstantBufferIndex_t camBuf = d3dProc.RegisterConstantBuffer (&camInfo,
																	   sizeof (camInfo),
																	   1);
		d3dProc.UpdateConstantBuffer (camBuf);

		MeteoObject meteo ("Data/COSMOMESH", "Data/Fronts", "Data/H", &camInfo.step, 0.01f, &d3dProc, &cam);
		cam.Update ();

		meteo.RunPolygonalBuilding();
		//SetForegroundWindow (window.hwnd ());


		printf("Processing\n");
		d3dProc.ProcessObjects ();


		MSG msg = {};
		bool rotate = true;
		bool wasPressedSpace = false;
		uint64_t ticksOld = 0;
		uint64_t ticksNew = GetTickCount64 ();
		char ticksN = 0;

		printf("Drawing\n");
		
		int hour = 0;
		while (true)
		{
			if (PeekMessage (&msg, nullptr, 0, 0, PM_REMOVE))
			{
				TranslateMessage (&msg);
				DispatchMessage (&msg);

				if (msg.message == WM_QUIT) break;
			}
			// SCENE PROCESSING

			/*if (rotate) meteo.Rotate (0.01f);
			if (GetAsyncKeyState (VK_SPACE) & 0x8000)
			{
				if (!wasPressedSpace)
				{
					rotate = !rotate;
					wasPressedSpace = true;
				}
			}
			else wasPressedSpace = false;*/
			if (GetAsyncKeyState('J') & 0x8000)
			{
				while (GetAsyncKeyState('J'));
				camInfo.noise = 2.0f - camInfo.noise;
			}

			ProcessCam (&cam, &camInfo);

			meteo.PreDraw ();

			cam.Update ();
			cam.StorePos (camInfo.pos);
			d3dProc.UpdateConstantBuffer (camBuf);

			d3dProc.SendCBToGS (camBuf);
			d3dProc.SendCBToPS (camBuf);
			d3dProc.ProcessDrawing (&cam, true);
			d3dProc.Present ();
			if (ticksN >= 10)
			{
				ticksN = 0;
				ticksOld = ticksNew;
				ticksNew = GetTickCount64();

				printf ("%.2f fps %f step noise %s          \r", 10000.0f/(ticksNew - ticksOld), camInfo.step, camInfo.noise > 1.0f ? "ON" : "OFF");

				/*if (10000.0f / (ticksNew - ticksOld) - TARGET_FPS > 10.0f)
					 camInfo.step -= 0.0005f;
				else 
				if (10000.0f / (ticksNew - ticksOld) - TARGET_FPS < -10.0f)
					camInfo.step += 0.0005f;
				if (camInfo.step < 0.0f) camInfo.step = 0.0001f;*/
				
			}
			ticksN++;
			//_getch();
			//break;
		}
		FreeConsole ();
	}
	catch (ExceptionHandler_t& ex)
	{
		_MessageBox ("Exception occurred\nCheck \"ExceptionErrors.txt\"");
		ex.WriteLog (__EXPN__);
		system ("start ExceptionErrors.txt");
	}
	catch (std::exception err)
	{
		_MessageBox ("Exception occurred: %s\n", err.what ());
	}
	catch (...)
	{
		_MessageBox ("Exception occurred\n");
	}

	delete __EXPN__;


	return 0;
}
Esempio n. 21
0
//
// The ConStream constructor initializes the object to point to the 
// NUL device. It does this by calling two consecutive constructors.
// First, the member variable m_Nul is initialized with a FILE object
// created by opening device "nul", the bit bucket. Second, the base
// class constructor is called with a reference to m_Nul, which is
// an ofstream object. This sets up ConStream so that it will direct
// its output to the given file.
//
ConStream::ConStream() : m_Nul( m_fNul = fopen( "nul", "w" ) ), m_fConsole(0),
#ifdef _UNICODE
                         basic_ostream<wchar_t>( &m_Nul ) 
#else
                         basic_ostream<char>( &m_Nul ) 
#endif
{
    m_FileBuf = 0;
    m_hConsole = INVALID_HANDLE_VALUE;
}

//
// The ConStream destructor always has to close the m_fNul FILE object
// which was created in the constructor. Even if the Open() method has
// been called and the bit bucket isn't being used, the FILE object is
// still using memory and a system file handle.
//
// If the ConStream object has been opened with a call to member function
// Open(), we have to call the Win32 API function FreeConsole() to close
// the console window. If the console window was open, we also call the
// C fclose() function on the m_fConsole member.
//
ConStream::~ConStream()
{
    delete m_FileBuf;
    if ( m_hConsole != INVALID_HANDLE_VALUE ) {
        FreeConsole();
        fclose( m_fConsole );
    }
    fclose( m_fNul );
}

//
// Opening the stream means doing these things:
//   1) Opening a Win32 console using the Win32 API
//   2) Getting an O/S handle to the console
//   3) Converting the O/S handle to a C stdio file handle
//   4) Converting the C stdio file handler to a C FILE object
//   5) Attaching the C FILE object to a C++ filebuf
//   6) Attaching the filebuf object to this
//   7) Disabling buffering so we see our output in real time.
//
void ConStream::Open()
{
    if ( m_hConsole == INVALID_HANDLE_VALUE ) {
		AllocConsole();
		m_hConsole = GetStdHandle( STD_OUTPUT_HANDLE );
		int handle = _open_osfhandle((INT_PTR)m_hConsole, _O_TEXT );
		m_fConsole = _fdopen( handle, "w" );
#ifdef _UNICODE
		m_FileBuf = new basic_filebuf<wchar_t>( m_fConsole );
#else
		m_FileBuf = new basic_filebuf<char>( m_fConsole );
#endif
		init( m_FileBuf );
		setf(ios::unitbuf);
	}
};

//
// Closing the ConStream is considerably simpler. We just use the
// init() call to attach this to the NUL file stream, then close
// the console descriptors.
//
void ConStream::Close()
{
    if ( m_hConsole != INVALID_HANDLE_VALUE ) {
        init( &m_Nul );
        FreeConsole();
        fclose( m_fConsole );
        m_hConsole = INVALID_HANDLE_VALUE;
    }
};
Esempio n. 22
0
myPRINT::myPRINT(BOOL bUseConsole)
{
	m__bAllocConsole	= FALSE;
	m__bUseConsole		= bUseConsole;
	INT	iReturnVal = 0;

	m__lpFile = NULL;
	if (m__bUseConsole == FALSE)
		return;

	// STD_INPUT_HANDLE 과 STD_OUTPUT_HANDLE 은 Redirected 됐을 수도
	// 있으므로, 먼저 STD_ERROR_HANDLE 을 얻는다.
	// 만약 성공하면 이미 유용한 콘솔은 있고 그렇지 않다면
	// AllocConsole() 을 이용해서 필요한 콘솔을 생성한다.
	m__CONERR = GetStdHandle(STD_ERROR_HANDLE);
	if (m__CONERR == INVALID_HANDLE_VALUE) {
		(VOID) MessageBox(
			NULL,
			TEXT("GetStdHandle(STD_ERROR_HANDLE) failed!"),
			TEXT("Message Box: Error!"),
			MB_OK
		);
		iReturnVal = -1;
		goto NEXT;
	} else if (m__CONERR == NULL) {
		// 유용한 콘솔이 없다!
		// AllocConsole() 을 이용해서 새로 만들자.
		if (!AllocConsole()) {
			(VOID) MessageBox(
				NULL,
				TEXT("AllocHandle(VOID) failed!"),
				TEXT("Message Box: Error!"),
				MB_OK
			);
			iReturnVal = -1;
			goto NEXT;
		}
		m__bAllocConsole = TRUE;

		m__CONERR = GetStdHandle(STD_ERROR_HANDLE);
		if (m__CONERR == INVALID_HANDLE_VALUE || m__CONERR == NULL) {
			INT	i = *((PINT) 0);
		}
	}

	// 사용가능한 콘솔이 있다!
	m__CONOUT = GetStdHandle(STD_OUTPUT_HANDLE);
	if (m__CONOUT == INVALID_HANDLE_VALUE) {
		(VOID) MessageBox(
			NULL,
			TEXT("GetStdHandle(STD_OUTPUT_HANDLE) failed!"),
			TEXT("Message Box: Error!"),
			MB_OK
		);
		iReturnVal = -1;
		goto NEXT;
	} else if (m__CONOUT == NULL) {
		// 이럴수가...
		// 이미 사용가능한 콘솔이 있지 않나?...
		(VOID) MessageBox(
			NULL,
			TEXT("GetStdHandle(STD_OUTPUT_HANDLE): ")
			TEXT("No Associated Standard Output Handle!"),
			TEXT("Message Box: Warning!"),
			MB_OK
		);
		iReturnVal = -1;
		goto NEXT;
	}


NEXT:
	if (iReturnVal != 0) {
		if (m__bAllocConsole == TRUE) {
			if (0 && !FreeConsole()) {
				(VOID) MessageBox(
					NULL,
					TEXT("FreeConsole(VOID) failed!"),
					TEXT("Message Box: Error!"),
					MB_OK
				);
			}
			m__bAllocConsole = FALSE;
		}
		m__CONOUT = NULL;
		m__CONERR = NULL;
	}
}
Esempio n. 23
0
cConsol::~cConsol()
{
	if(hout) FreeConsole();
}
Esempio n. 24
0
void CLog::UnInitConsole()
{
	FreeConsole();
	m_hConsloe = NULL;
}
Esempio n. 25
0
virtual bool Free() const override
{
	return FreeConsole()!=FALSE;
}
Esempio n. 26
0
int mkill(void)
{
	FreeConsole();

	return 1;
}
Esempio n. 27
0
// Default destructor
Console::~Console()
{
	FreeConsole();
	//CloseHandle(consoleHandle);
}