Ejemplo n.º 1
0
JNIEXPORT jboolean JNICALL Java_com_jogamp_newt_impl_opengl_kd_KDWindow_initIDs
  (JNIEnv *env, jclass clazz)
{
#ifdef VERBOSE_ON
    #ifdef _WIN32_WCE
        _wfreopen(TEXT(STDOUT_FILE),L"w",stdout);
        _wfreopen(TEXT(STDERR_FILE),L"w",stderr);
    #endif
#endif
    windowCreatedID = (*env)->GetMethodID(env, clazz, "windowCreated", "(J)V");
    sizeChangedID = (*env)->GetMethodID(env, clazz, "sizeChanged", "(II)V");
    windowDestroyNotifyID = (*env)->GetMethodID(env, clazz, "windowDestroyNotify",    "()V");
    windowDestroyedID = (*env)->GetMethodID(env, clazz, "windowDestroyed", "()V");
    enqueueMouseEventID = (*env)->GetMethodID(env, clazz, "enqueueMouseEvent", "(IIIIII)V");
    enqueueKeyEventID = (*env)->GetMethodID(env, clazz, "enqueueKeyEvent", "(IIIC)V");
    if (windowCreatedID == NULL ||
        sizeChangedID == NULL ||
        windowDestroyNotifyID == NULL ||
        windowDestroyedID == NULL ||
        enqueueMouseEventID == NULL ||
        enqueueKeyEventID == NULL) {
        DBG_PRINT( "initIDs failed\n" );
        return JNI_FALSE;
    }
    DBG_PRINT( "initIDs ok\n" );
    return JNI_TRUE;
}
JNIEXPORT jboolean JNICALL Java_jogamp_opengl_util_av_impl_OMXGLMediaPlayer_initIDs0
  (JNIEnv *env, jclass clazz)
{
#ifdef _WIN32_WCE
    _wfreopen(TEXT(STDOUT_FILE),L"w",stdout);
    _wfreopen(TEXT(STDERR_FILE),L"w",stderr);
#endif
    JoglCommon_init(env);

    jclass c;
    if (omxGLMediaPlayerClazz != NULL) {
        return;
    }

    c = (*env)->FindClass(env, ClazzNameOMXGLMediaPlayer);
    if(NULL==c) {
        JoglCommon_FatalError(env, "JOGL OMX: can't find %s", ClazzNameOMXGLMediaPlayer);
    }
    omxGLMediaPlayerClazz = (jclass)(*env)->NewGlobalRef(env, c);
    (*env)->DeleteLocalRef(env, c);
    if(NULL==omxGLMediaPlayerClazz) {
        JoglCommon_FatalError(env, "JOGL OMX: can't use %s", ClazzNameOMXGLMediaPlayer);
    }

    jni_mid_updateAttributes = (*env)->GetMethodID(env, omxGLMediaPlayerClazz, "updateAttributes", "(IIIIIFIILjava/lang/String;Ljava/lang/String;)V");

    if(jni_mid_updateAttributes == NULL) {
        return JNI_FALSE;
    }
    return JNI_TRUE;
}
Ejemplo n.º 3
0
int WINAPI wWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,
                    LPWSTR szCmdLine, int iCmdShow)
{
#ifdef _WIN32
	if (fileno (stdout) != -1 &&
		_get_osfhandle (fileno (stdout)) != -1)
	{
		/* stdout is fine, presumably redirected to a file or pipe */
	}
    else
    {
		typedef BOOL (WINAPI * AttachConsole_t) (DWORD);

		AttachConsole_t p_AttachConsole =
			(AttachConsole_t) GetProcAddress (GetModuleHandleW(L"kernel32.dll"), "AttachConsole");

		if (p_AttachConsole != NULL && p_AttachConsole (ATTACH_PARENT_PROCESS))
		{
			_wfreopen (L"CONOUT$", L"w", stdout);
			dup2 (fileno (stdout), 1);
			_wfreopen (L"CONOUT$", L"w", stderr);
			dup2 (fileno (stderr), 2);

		}
	}
#endif

	// Dummy ANSI command line
	return AP_Win32App::WinMain("AbiWord", hInstance, hPrevInstance, "abiword.exe", iCmdShow);
}
Ejemplo n.º 4
0
BOOL CreateConsole()
{
	WCHAR szVisible[BUFSIZ] = L"";

	AllocConsole();
	_wfreopen(L"CONIN$",  L"r+t", stdin);
	_wfreopen(L"CONOUT$", L"w+t", stdout);

	hConsole = GetConsoleWindow();

	if (GetEnvironmentVariableW(L"TASKBAR_VISIBLE", szVisible, BUFSIZ-1) && szVisible[0] == L'0')
	{
		ShowWindow(hConsole, SW_HIDE);
	}
	else
	{
		SetForegroundWindow(hConsole);
	}
	
	if (SetConsoleCtrlHandler((PHANDLER_ROUTINE)ConsoleHandler,TRUE)==FALSE)
	{
		printf("Unable to install handler!\n");
		return FALSE;
	}

	return TRUE;
}
Ejemplo n.º 5
0
JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_kd_WindowDriver_initIDs
  (JNIEnv *env, jclass clazz)
{
#ifdef VERBOSE_ON
    #ifdef _WIN32_WCE
        _wfreopen(TEXT(STDOUT_FILE),L"w",stdout);
        _wfreopen(TEXT(STDERR_FILE),L"w",stderr);
    #endif
#endif
    windowCreatedID = (*env)->GetMethodID(env, clazz, "windowCreated", "(J)V");
    sizeChangedID = (*env)->GetMethodID(env, clazz, "sizeChanged", "(ZIIZ)V");
    visibleChangedID = (*env)->GetMethodID(env, clazz, "visibleChanged", "(ZZ)V");
    windowDestroyNotifyID = (*env)->GetMethodID(env, clazz, "windowDestroyNotify", "(Z)Z");
    sendMouseEventID = (*env)->GetMethodID(env, clazz, "sendMouseEvent", "(SIIISF)V");
    sendKeyEventID = (*env)->GetMethodID(env, clazz, "sendKeyEvent", "(SISSC)V");
    if (windowCreatedID == NULL ||
        sizeChangedID == NULL ||
        visibleChangedID == NULL ||
        windowDestroyNotifyID == NULL ||
        sendMouseEventID == NULL ||
        sendKeyEventID == NULL) {
        DBG_PRINT( "initIDs failed\n" );
        return JNI_FALSE;
    }
    DBG_PRINT( "initIDs ok\n" );
    return JNI_TRUE;
}
Ejemplo n.º 6
0
BOOL CreateConsole() {
    AllocConsole();
    _wfreopen(L"CONIN$",  L"r+t", stdin);
    _wfreopen(L"CONOUT$", L"w+t", stdout);

    hConsole = GetConsoleWindow();

    if (szVisible[0] == L'0') {
        ShowWindow(hConsole, SW_HIDE);
    } else {
        SetForegroundWindow(hConsole);
    }

    if (SetConsoleCtrlHandler((PHANDLER_ROUTINE)ConsoleHandler,TRUE)==FALSE) {
        printf("Unable to install handler!\n");
        return FALSE;
    }

    CONSOLE_SCREEN_BUFFER_INFO csbi;
    if (GetConsoleScreenBufferInfo(GetStdHandle(STD_ERROR_HANDLE), &csbi)) {
        COORD size = csbi.dwSize;
        if (size.Y < 2048) {
            size.Y = 2048;
            if (!SetConsoleScreenBufferSize(GetStdHandle(STD_ERROR_HANDLE), size)) {
                printf("Unable to set console screen buffer size!\n");
            }
        }
    }
    return TRUE;
}
Ejemplo n.º 7
0
gboolean
GlibUtils_AttachConsole(void)
{
   typedef BOOL (WINAPI *AttachConsoleFn)(DWORD);
   gboolean ret = TRUE;
   AttachConsoleFn _AttachConsole;
   BOOL reopenStdout;
   BOOL reopenStderr;

   if (GetConsoleWindow() != NULL) {
      goto exit;
   }

   reopenStdout = !GlibUtilsIsRedirected(STD_OUTPUT_HANDLE);
   reopenStderr = !GlibUtilsIsRedirected(STD_ERROR_HANDLE);
   if (!reopenStdout && !reopenStderr) {
      goto exit;
   }

   _AttachConsole = (AttachConsoleFn) GetProcAddress(GetModuleHandleW(L"kernel32.dll"),
                                                     "AttachConsole");
   if ((_AttachConsole != NULL && _AttachConsole(ATTACH_PARENT_PROCESS)) ||
       AllocConsole()) {
      FILE *fptr;

      if (reopenStdout) {
         fptr = _wfreopen(L"CONOUT$", L"a", stdout);
         if (fptr == NULL) {
            g_warning("_wfreopen failed for stdout/CONOUT$: %d (%s)",
                      errno, strerror(errno));
            ret = FALSE;
         }
      }

      if (reopenStderr) {
         fptr = _wfreopen(L"CONOUT$", L"a", stderr);
         if (fptr == NULL) {
            g_warning("_wfreopen failed for stderr/CONOUT$: %d (%s)",
                      errno, strerror(errno));
            ret = FALSE;
         } else {
            setvbuf(fptr, NULL, _IONBF, 0);
         }
      }
   } else {
      ret = FALSE;
   }

exit:
   if (!ret) {
      g_warning("Console redirection unavailable.");
   }
   return ret;
}
Ejemplo n.º 8
0
/**
 * g_freopen:
 * @filename: a pathname in the GLib file name encoding (UTF-8 on Windows)
 * @mode: a string describing the mode in which the file should be
 *   opened
 * @stream: an existing stream which will be reused, or %NULL
 *
 * A wrapper for the POSIX freopen() function. The freopen() function
 * opens a file and associates it with an existing stream.
 *
 * See the C library manual for more details about freopen().
 *
 * Returns: A <type>FILE</type> pointer if the file was successfully
 *    opened, or %NULL if an error occurred.
 *
 * Since: 2.6
 */
FILE *
ws_stdio_freopen (const gchar *filename,
	   const gchar *mode,
	   FILE        *stream)
{
      wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
      wchar_t *wmode;
      FILE *retval;
      int save_errno;

      if (wfilename == NULL)
	{
	  errno = EINVAL;
	  return NULL;
	}

      wmode = g_utf8_to_utf16 (mode, -1, NULL, NULL, NULL);

      if (wmode == NULL)
	{
	  g_free (wfilename);
	  errno = EINVAL;
	  return NULL;
	}

      retval = _wfreopen (wfilename, wmode, stream);
      save_errno = errno;

      g_free (wfilename);
      g_free (wmode);

      errno = save_errno;
      return retval;
}
Ejemplo n.º 9
0
BOOL CreateConsole()
{
	AllocConsole();
	_wfreopen(L"CONIN$",  L"r+t", stdin);
	_wfreopen(L"CONOUT$", L"w+t", stdout);
	hConsole = GetConsoleWindow();
	if (lstrcmp(szVisible, L"") == 0 || lstrcmp(szVisible, L"0") == 0)
	{
		ShowWindow(hConsole, SW_HIDE);
	}
	else
	{
		SetForegroundWindow(hConsole);
	}
	return TRUE;
}
Ejemplo n.º 10
0
/*
** Implementation of freopen() - requires wide char conversion
*/
RTEXP	FILE *freopen( const char *path, const char *mode, FILE *stream ) {
	wchar_t	wpath[BUFSIZ];
	wchar_t	wmode[8];

	MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS, path, -1, wpath, BUFSIZ);
	MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS, mode, -1, wmode, 8);
	return(_wfreopen(wpath, wmode, stream));
}
Ejemplo n.º 11
0
static FILE *rt_file_freopen(EIF_FILENAME name, EIF_FILENAME type, FILE *stream)
{
#ifdef EIF_WINDOWS
	return _wfreopen(name, type, stream);
#else
	return freopen(name, type, stream);
#endif
}
Ejemplo n.º 12
0
FILE* my_wfreopen(const wchar_t * path, const wchar_t * mode, FILE* oldFile)
{
#ifdef _WIN32
	return _wfreopen(path, mode, oldFile);
#else
	return freopen(wideCharToUtf8(path).c_str(), wideCharToUtf8(mode).c_str(), oldFile);
#endif
}
Ejemplo n.º 13
0
WXDLLIMPEXP_BASE FILE* wxMSLU__wfreopen(const wchar_t *name,
                                        const wchar_t* mode,
                                        FILE *stream)
{
    if ( wxUsingUnicowsDll() )
        return freopen(wxConvFile.cWX2MB(name), wxConvFile.cWX2MB(mode), stream);
    else
        return _wfreopen(name, mode, stream);
}
Ejemplo n.º 14
0
    Redirection(FILE* f)
        : fi(Base::FileInfo::getTempFileName()), file(f)
    {
#ifdef WIN32
        _wfreopen(fi.toStdWString().c_str(),L"w",file);
#else
        freopen(fi.filePath().c_str(),"w",file);
#endif
    }
Ejemplo n.º 15
0
BOOL CreateConsole()
{
	WCHAR szVisible[BUFSIZ] = L"";

	AllocConsole();
	_wfreopen(L"CONIN$",  L"r+t", stdin);
	_wfreopen(L"CONOUT$", L"w+t", stdout);

	hConsole = GetConsoleWindow();

	if (GetEnvironmentVariableW(L"TASKBAR_VISIBLE", szVisible, BUFSIZ-1) && szVisible[0] == L'0')
	{
		ShowWindow(hConsole, SW_HIDE);
	}
	else
	{
		SetForegroundWindow(hConsole);
	}

	return TRUE;
}
Ejemplo n.º 16
0
FILE* _ufreopen (const char* filename, const char* mode, FILE* stream){
	wchar_t* wfilename, *wmode;
	if(!(wfilename = utf8_to_ucs2(filename)))
		return NULL;
	if(!(wmode = utf8_to_ucs2(mode))){
		free(wfilename);
		return NULL;
	}
	stream = _wfreopen(wfilename, wmode, stream);
	free(wfilename);
	free(wmode);
	return stream;
}
Ejemplo n.º 17
0
void RedirectStdio()
{
	std::string stdout_path = FileSystem::JoinPath(FileSystem::GetUserDir(), "stdout.txt");
	std::string stderr_path = FileSystem::JoinPath(FileSystem::GetUserDir(), "stderr.txt");
	std::wstring wstdout_path = transcode_utf8_to_utf16(stdout_path);
	std::wstring wstderr_path = transcode_utf8_to_utf16(stderr_path);

	FILE *f;

	f = _wfreopen(wstdout_path.c_str(), L"w", stdout);
	if (!f) {
		fprintf(stderr, "ERROR: Couldn't redirect stdout to '%s': %s\n", stdout_path.c_str(), strerror(errno));
	} else {
		setvbuf(f, 0, _IOLBF, BUFSIZ);
	}

	f = _wfreopen(wstderr_path.c_str(), L"w", stderr);
	if (!f) {
		fprintf(stderr, "ERROR: Couldn't redirect stderr to '%s': %s\n", stderr_path.c_str(), strerror(errno));
	} else {
		setvbuf(f, 0, _IOLBF, BUFSIZ);
	}
}
Ejemplo n.º 18
0
static void _initStatics(JNIEnv *env)
{
    jclass c;
#ifdef _WIN32_WCE
    _wfreopen(TEXT(STDOUT_FILE),L"w",stdout);
    _wfreopen(TEXT(STDERR_FILE),L"w",stderr);
#endif
    fprintf(stdout, "_initstatics ..\n"); fflush(stdout); // JAU
    if (runtimeExceptionClz != NULL) {
        return;
    }

    c = (*env)->FindClass(env, ClazzNameRuntimeException);
    if(NULL==c) {
        fprintf(stdout, "FatalError: can't find %s\n", ClazzNameRuntimeException);
        (*env)->FatalError(env, ClazzNameRuntimeException);
    }
    runtimeExceptionClz = (jclass)(*env)->NewGlobalRef(env, c);
    if(NULL==runtimeExceptionClz) {
        fprintf(stdout, "FatalError: can't use %s\n", ClazzNameRuntimeException);
        (*env)->FatalError(env, ClazzNameRuntimeException);
    }
}
Ejemplo n.º 19
0
        void WinPlatform::initializeLogging(const char* filename)
        {
        #if defined (UNDER_CE)
            int filenameLen = VMPI_strlen(filename);

            TCHAR* logname = new TCHAR[filenameLen+1];

            mbstowcs(logname, filename, filenameLen+1);

            _wfreopen(logname, L"w", stdout);

            delete [] logname;
        #else
            FILE *f = freopen(filename, "w", stdout);
            if (!f)
                AvmLog("freopen %s failed.\n",filename);
        #endif /* UNDER_CE */
        }
Ejemplo n.º 20
0
FILE *u8freopen(const char *fname, const char *mode, FILE *oldfp)
{
	wchar_t *wfname = u8stows(fname);
	wchar_t *wmode = u8stows(mode);
	FILE *fp = NULL;

	if(wfname && wmode)	{
		fp = _wfreopen(wfname, wmode, oldfp);
	}
	if(wfname) {
		free(wfname);
	}
	if(wmode) {
		free(wmode);
	}

	return fp;
}
Ejemplo n.º 21
0
/*!	\relates XsFile
	\brief Reopens a file
	\param filename Name of the file to open after the current one has been close
	\param mode Mode to reopen the file with
	\returns 0 if a file is open, another value otherwise
*/
XsResultValue XsFile_reopen(struct XsFile *thisPtr, const struct XsString* filename, const struct XsString* mode)
{
#ifdef _WIN32
	wchar_t filenameW[XS_MAX_FILENAME_LENGTH];
	wchar_t modeW[16];

	(void)XsString_copyToWCharArray(filename, filenameW, XS_MAX_FILENAME_LENGTH);
	(void)XsString_copyToWCharArray(mode, modeW, 16);

	thisPtr->m_handle = _wfreopen(filenameW, modeW, thisPtr->m_handle);
#else
	thisPtr->m_handle = freopen(filename->m_data, mode->m_data, thisPtr->m_handle);
#endif

	if (thisPtr->m_handle == NULL)
		return XRV_OUTPUTCANNOTBEOPENED;
	else
		return XRV_OK;
}
Ejemplo n.º 22
0
FILE* OpenFile(const char* path, const char* mode, bool mustexist)
{
    FILE* ret;

#ifdef __WIN32__

    int len = MultiByteToWideChar(CP_UTF8, 0, path, -1, NULL, 0);
    if (len < 1) return NULL;
    WCHAR* fatpath = new WCHAR[len];
    int res = MultiByteToWideChar(CP_UTF8, 0, path, -1, fatpath, len);
    if (res != len) { delete[] fatpath; return NULL; } // checkme?

    // this will be more than enough
    WCHAR fatmode[4];
    fatmode[0] = mode[0];
    fatmode[1] = mode[1];
    fatmode[2] = mode[2];
    fatmode[3] = 0;

    if (mustexist)
    {
        ret = _wfopen(fatpath, L"rb");
        if (ret) ret = _wfreopen(fatpath, fatmode, ret);
    }
    else
        ret = _wfopen(fatpath, fatmode);

    delete[] fatpath;

#else

    if (mustexist)
    {
        ret = fopen(path, "rb");
        if (ret) ret = freopen(path, mode, ret);
    }
    else
        ret = fopen(path, mode);

#endif

    return ret;
}
Ejemplo n.º 23
0
/**
 * g_freopen:
 * @filename: (type filename): a pathname in the GLib file name encoding
 *     (UTF-8 on Windows)
 * @mode: a string describing the mode in which the file should be  opened
 * @stream: (nullable): an existing stream which will be reused, or %NULL
 *
 * A wrapper for the POSIX freopen() function. The freopen() function
 * opens a file and associates it with an existing stream.
 * 
 * See your C library manual for more details about freopen().
 *
 * Returns: A FILE* if the file was successfully opened, or %NULL if
 *     an error occurred.
 * 
 * Since: 2.6
 */
FILE *
g_freopen (const gchar *filename,
	   const gchar *mode,
	   FILE        *stream)
{
#ifdef G_OS_WIN32
  wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
  wchar_t *wmode;
  gchar   *mode2;
  FILE *retval;
  int save_errno;

  if (wfilename == NULL)
    {
      errno = EINVAL;
      return NULL;
    }

  mode2 = _g_win32_get_mode_alias (mode);
  wmode = g_utf8_to_utf16 (mode2, -1, NULL, NULL, NULL);
  g_free (mode2);

  if (wmode == NULL)
    {
      g_free (wfilename);
      errno = EINVAL;
      return NULL;
    }
  
  retval = _wfreopen (wfilename, wmode, stream);
  save_errno = errno;

  g_free (wfilename);
  g_free (wmode);

  errno = save_errno;
  return retval;
#else
  return freopen (filename, mode, stream);
#endif
}
Ejemplo n.º 24
0
static void app_init_logging() {
    BOOL outputToConsole = !!wcsstr(GetCommandLine(), L"--console");
    if (outputToConsole) {
        AllocConsole();
        freopen("CONOUT$", "wb", stdout);
        freopen("CONOUT$", "wb", stderr);
    } else {
        WCHAR buf[MAX_PATH];
        MultiByteToWideChar(CP_UTF8, 0, os_log_path, -1, buf, MAX_PATH);
        wcscat(buf, L"\\log.txt");
        _wfreopen(buf, L"w", stderr);
        HANDLE hLogFile = (HANDLE) _get_osfhandle(_fileno(stderr));
        //HANDLE hLogFile = CreateFile(buf, FILE_ALL_ACCESS, FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE, NULL, CREATE_ALWAYS, FILE_FLAG_WRITE_THROUGH, NULL);
        //SetStdHandle(STD_OUTPUT_HANDLE, hLogFile);
        SetStdHandle(STD_ERROR_HANDLE, hLogFile);
    }
    time_t startup_time = time(NULL);
    struct tm *startup_tm = gmtime(&startup_time);
    fprintf(stderr, "%04d-%02d-%02d %02d:%02d:%02d LiveReload " LIVERELOAD_VERSION " launched\n", 1900 + startup_tm->tm_year,
        1 + startup_tm->tm_mon, startup_tm->tm_mday, startup_tm->tm_hour, startup_tm->tm_min, startup_tm->tm_sec);
    fflush(stderr);
}
Ejemplo n.º 25
0
int
rb_freopen(VALUE fname, const char *mode, FILE *file)
{
    WCHAR *wname, wmode[4];
    long len;
    int e = 0, n = MultiByteToWideChar(CP_ACP, 0, mode, -1, NULL, 0);
    if (n > numberof(wmode)) return EINVAL;
    MultiByteToWideChar(CP_ACP, 0, mode, -1, wmode, numberof(wmode));
    wname = rb_w32_mbstr_to_wstr(CP_UTF8, RSTRING_PTR(fname),
                                 rb_long2int(RSTRING_LEN(fname)) + 1, &len);
    wname[len - 1] = L'\0';
    RB_GC_GUARD(fname);
#if RUBY_MSVCRT_VERSION < 80 && !defined(HAVE__WFREOPEN_S)
    e = _wfreopen(wname, wmode, file) ? 0 : errno;
#else
    {
        FILE *newfp = 0;
        e = _wfreopen_s(&newfp, wname, wmode, file);
    }
#endif
    free(wname);
    return e;
}
Ejemplo n.º 26
0
int
Main::run(int argc, char** argv)
{
#ifdef WIN32
	//SDL is used instead of PHYSFS because both create the same path in app data
	//However, PHYSFS is not yet initizlized, and this should be run before anything is initialized
	std::string prefpath = SDL_GetPrefPath("SuperTux", "supertux2");

	std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;

	//All this conversion stuff is necessary to make this work for internationalized usernames
	std::string outpath = prefpath + u8"/console.out";
	std::wstring w_outpath = converter.from_bytes(outpath);
	_wfreopen(w_outpath.c_str(), L"a", stdout);

	std::string errpath = prefpath + u8"/console.err";
	std::wstring w_errpath = converter.from_bytes(errpath);
	_wfreopen(w_errpath.c_str(), L"a", stderr);
#endif

  // Create and install global locale
  std::locale::global(boost::locale::generator().generate(""));
  // Make boost.filesystem use it
  boost::filesystem::path::imbue(std::locale());

  int result = 0;

  try
  {
    CommandLineArguments args;

    try
    {
      args.parse_args(argc, argv);
      g_log_level = args.get_log_level();
    }
    catch(const std::exception& err)
    {
      std::cout << "Error: " << err.what() << std::endl;
      return EXIT_FAILURE;
    }

    PhysfsSubsystem physfs_subsystem(argv[0], args.datadir, args.userdir);
    physfs_subsystem.print_search_path();

    timelog("config");
    ConfigSubsystem config_subsystem;
    args.merge_into(*g_config);

    timelog("tinygettext");
    init_tinygettext();

    switch (args.get_action())
    {
      case CommandLineArguments::PRINT_VERSION:
        args.print_version();
        return 0;

      case CommandLineArguments::PRINT_HELP:
        args.print_help(argv[0]);
        return 0;

      case CommandLineArguments::PRINT_DATADIR:
        args.print_datadir();
        return 0;

      default:
        launch_game();
        break;
    }
  }
  catch(const std::exception& e)
  {
    log_fatal << "Unexpected exception: " << e.what() << std::endl;
    result = 1;
  }
  catch(...)
  {
    log_fatal << "Unexpected exception" << std::endl;
    result = 1;
  }

  g_dictionary_manager.reset();

  return result;
}
Ejemplo n.º 27
0
void SimpleGeometryCreator::Run(const std::vector<String>& arguments)
{
	if(arguments.size() < 3)
		THROW("Must be 3 auguments for command");

	ptr<FileSystem> fileSystem = FolderFileSystem::GetNativeFileSystem();
	//открыть исходный файл
	_wfreopen(Strings::UTF82Unicode(arguments[0]).c_str(), L"rb", stdin);

	//размеры текстуры
	textureWidth = 1;
	textureHeight = 1;
	//размер вершины
	size_t vertexStride = 0;
	//считать поля
	char str[1024];
	while(gets_s(str))
	{
		Field field;
		//считать тип и размеры
		char typeStr[32];
		size_t i;
		for(i = 0; str[i] && isalpha(str[i]); ++i)
			typeStr[i] = str[i];
		typeStr[i] = 0;
		sscanf(str + i, "%dx%d", &field.size1, &field.size2);
		for(; str[i] && !isspace(str[i]); ++i);
		for(; str[i] && isspace(str[i]); ++i);
		field.divider = str[i];

		//получить тип
		size_t fieldSize;
		if(strcmp(typeStr, "float") == 0)
		{
			field.type = Field::typeFloat;
			fieldSize = sizeof(float);
		}
		else if(strcmp(typeStr, "int") == 0)
		{
			field.type = Field::typeInt;
			fieldSize = sizeof(int);
		}
		else if(strcmp(typeStr, "uint") == 0)
		{
			field.type = Field::typeUInt;
			fieldSize = sizeof(unsigned);
		}
		else if(strcmp(typeStr, "end") == 0)
			break;
		else if(strcmp(typeStr, "width") == 0)
		{
			textureWidth = field.size1;
			continue;
		}
		else if(strcmp(typeStr, "height") == 0)
		{
			textureHeight = field.size1;
			continue;
		}
		else
			THROW(String("Unknown field type: ") + typeStr);

		vertexStride += fieldSize * field.size1 * field.size2;

		//добавить поле
		fields.push_back(field);
	}

	//создать поток вывода в памяти
	stream = new MemoryStream();

	//цикл считывания вершин
	bool stop = false, indexed = false;
	while(!stop)
	{
		//проверить, может там начинается слово indexes
		char c;
		scanf(" %c", &c);
		if(c == 'i')
		{
			indexed = true;
			char s[10];
			scanf("%s", s);
			break;
		}
		else
			ungetc(c, stdin);
		//цикл считывания полей в вершине
		for(size_t i = 0; i < fields.size(); ++i)
			//если поле не считалось
			if(!ReadField(fields[i]))
				//если оно не первое в вершине, то это плохо
				if(i)
					THROW("Can't read field");
				//иначе это нормально, просто завершить цикл
				else
				{
					stop = true;
					break;
				}
	}

	//если индексы, считывать и их
	//индексы могут идти как 
	std::vector<short> indices;
	if(indexed)
	{
		for(;;)
		{
			//считать строку
			if(scanf("%s", str) != 1)
				break;
			//если это треугольник
			if(strcmp(str, "t") == 0)
			{
				//считать три индекса
				int a, b, c;
				if(scanf("%d%d%d", &a, &b, &c) != 3)
					THROW("Unexpected end of file: can't read triangle");
				indices.push_back(a);
				indices.push_back(b);
				indices.push_back(c);
			}
			//иначе если это прямоугольник
			else if(strcmp(str, "r") == 0)
			{
				//считать 4 индекса в порядке по часовой стрелке (как и треугольник)
				int a, b, c, d;
				if(scanf("%d%d%d%d", &a, &b, &c, &d) != 4)
					THROW("Unexpected end of file: can't read rectangle");
				indices.push_back(a);
				indices.push_back(b);
				indices.push_back(c);
				indices.push_back(a);
				indices.push_back(c);
				indices.push_back(d);
			}
			//иначе если это комментарий
			else if(strcmp(str, "/*") == 0)
				//найти закрывающий комментарий
				while(scanf("%s", str) == 1 && strcmp(str, "*/") != 0);
			//иначе если это однострочный комментарий
			else if(strcmp(str, "//") == 0)
				//считать все до конца строки
				gets_s(str);
			//иначе это что-то непонятное
			else
				THROW(String("Unknown type of index: ") + str);
		}
		if(indices.size() % 3)
			THROW("Number of indices must be divisible by 3");
	}

	ptr<File> indicesFile;
	if(indexed)
	{
		indicesFile = new MemoryFile(indices.size() * sizeof(short));
		memcpy(indicesFile->GetData(), &*indices.begin(), indicesFile->GetSize());
	}
	//создать геометрию
	ptr<Graphics::Geometry> geometry = NEW(Graphics::Geometry(stream->ToFile(), vertexStride, indicesFile, indexed ? sizeof(short) : 0, nullptr));
	//сохранить файл
	geometry->Serialize(fileSystem->SaveStream(arguments[1]), arguments[2]);
}
Ejemplo n.º 28
0
bool MakefileFactory::apply(const QStringList& commandLineArguments, Options **outopt)
{
    if (m_makefile)
        clear();

    Options *options = new Options;
    if (outopt)
        *outopt = options;
    MacroTable *macroTable = new MacroTable;
    macroTable->setEnvironment(m_environment);

    QString filename;
    if (!options->readCommandLineArguments(commandLineArguments, filename, m_activeTargets, *macroTable)) {
        m_errorType = CommandLineError;
        return false;
    }
    if (options->showUsageAndExit || options->showVersionAndExit)
        return true;

    if (!options->stderrFile.isEmpty()) {
        // Try to open the file for writing.
        const wchar_t *wszFileName = reinterpret_cast<const wchar_t*>(options->stderrFile.utf16());
        FILE *f = _wfopen(wszFileName, L"w");
        if (!f) {
            m_errorString = QLatin1String("Cannot open stderr file for writing.");
            m_errorType = IOError;
            return false;
        }
        fclose(f);
        if (!_wfreopen(wszFileName, L"w", stderr)) {
            m_errorString = QLatin1String("Cannot reopen stderr handle for writing.");
            m_errorType = IOError;
            return false;
        }
    }

    options->fullAppPath = QDir::toNativeSeparators(QCoreApplication::applicationFilePath());

    readEnvironment(m_environment, macroTable, options->overrideEnvVarMacros);
    if (!options->ignorePredefinedRulesAndMacros) {
        macroTable->setMacroValue("MAKE", encloseInDoubleQuotesIfNeeded(options->fullAppPath));
        macroTable->setMacroValue("MAKEDIR", encloseInDoubleQuotesIfNeeded(QDir::currentPath()));
        macroTable->setMacroValue("AS", "ml");       // Macro Assembler
        macroTable->setMacroValue("ASFLAGS", QString());
        macroTable->setMacroValue("BC", "bc");       // Basic Compiler
        macroTable->setMacroValue("BCFLAGS", QString());
        macroTable->setMacroValue("CC", "cl");       // C Compiler
        macroTable->setMacroValue("CCFLAGS", QString());
        macroTable->setMacroValue("COBOL", "cobol"); // COBOL Compiler
        macroTable->setMacroValue("COBOLFLAGS", QString());
        macroTable->setMacroValue("CPP", "cl");      // C++ Compiler
        macroTable->setMacroValue("CPPFLAGS", QString());
        macroTable->setMacroValue("CXX", "cl");      // C++ Compiler
        macroTable->setMacroValue("CXXFLAGS", QString());
        macroTable->setMacroValue("FOR", "fl");      // FORTRAN Compiler
        macroTable->setMacroValue("FORFLAGS", QString());
        macroTable->setMacroValue("PASCAL", "pl");   // Pascal Compiler
        macroTable->setMacroValue("PASCALFLAGS", QString());
        macroTable->setMacroValue("RC", "rc");       // Resource Compiler
        macroTable->setMacroValue("RCFLAGS", QString());
    }

    try {
        m_makefile = new Makefile(filename);
        m_makefile->setOptions(options);
        m_makefile->setMacroTable(macroTable);
        Preprocessor preprocessor;
        preprocessor.setMacroTable(macroTable);
        preprocessor.openFile(filename);
        Parser parser;
        parser.apply(&preprocessor, m_makefile, m_activeTargets);
    } catch (Exception &e) {
        m_errorType = ParserError;
        m_errorString = e.toString();
    }

    return m_errorType == NoError;
}
Ejemplo n.º 29
0
/**
 * Redirects the output streams to point to the log file with the given path.
 *
 * @param path specifies the location of log file, may start with ~
 * @param append should be nonzero if it should not truncate the log file.
 */
static int setup_logging(const char *path, int append) {
#ifdef _WIN32
  // Does it start with a tilde?  Perform tilde expansion if so.
  wchar_t pathw[MAX_PATH * 2];
  size_t offset = 0;
  if (path[0] == '~' && (path[1] == 0 || path[1] == '/' || path[1] == '\\')) {
    // Strip off the tilde.
    ++path;

    // Get the home directory path for the current user.
    if (!SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_PROFILE, NULL, 0, pathw))) {
      return 0;
    }
    offset = wcslen(pathw);
  }

  // We need to convert the rest of the path from UTF-8 to UTF-16.
  if (MultiByteToWideChar(CP_UTF8, 0, path, -1, pathw + offset,
                          (int)(_countof(pathw) - offset)) == 0) {
    return 0;
  }

  DWORD access = append ? FILE_APPEND_DATA : (GENERIC_READ | GENERIC_WRITE);
  int creation = append ? OPEN_ALWAYS : CREATE_ALWAYS;
  HANDLE handle = CreateFileW(pathw, access, FILE_SHARE_DELETE | FILE_SHARE_READ,
                              NULL, creation, FILE_ATTRIBUTE_NORMAL, NULL);

  if (handle == INVALID_HANDLE_VALUE) {
    // Make the parent directories first.
    mkdir_parent(pathw);
    handle = CreateFileW(pathw, access, FILE_SHARE_DELETE | FILE_SHARE_READ,
                         NULL, creation, FILE_ATTRIBUTE_NORMAL, NULL);
  }

  if (handle == INVALID_HANDLE_VALUE) {
    return 0;
  }

  if (append) {
    SetFilePointer(handle, 0, NULL, FILE_END);
  }

  SetStdHandle(STD_OUTPUT_HANDLE, handle);
  SetStdHandle(STD_ERROR_HANDLE, handle);

  // If we are running under the UCRT in a GUI application, we can't be sure
  // that we have valid fds for stdout and stderr, so we have to set them up.
  // One way to do this is to reopen them to something silly (like NUL).
  if (_fileno(stdout) < 0) {
    _close(1);
    _wfreopen(L"\\\\.\\NUL", L"w", stdout);
  }

  if (_fileno(stderr) < 0) {
    _close(2);
    _wfreopen(L"\\\\.\\NUL", L"w", stderr);
  }

  // Now replace the stdout and stderr file descriptors with one pointing to
  // our desired handle.
  int fd = _open_osfhandle((intptr_t)handle, _O_WRONLY | _O_TEXT | (append ? _O_APPEND : 0));
  _dup2(fd, _fileno(stdout));
  _dup2(fd, _fileno(stderr));
  _close(fd);

  return 1;
#else
  // Does it start with a tilde?  Perform tilde expansion if so.
  char buffer[PATH_MAX * 2];
  size_t offset = 0;
  if (path[0] == '~' && (path[1] == 0 || path[1] == '/')) {
    // Strip off the tilde.
    ++path;

    // Get the home directory path for the current user.
    const char *home_dir = getenv("HOME");
    if (home_dir == NULL) {
      home_dir = getpwuid(getuid())->pw_dir;
    }
    offset = strlen(home_dir);
    assert(offset < sizeof(buffer));
    strncpy(buffer, home_dir, sizeof(buffer));
  }

  // Copy over the rest of the path.
  strcpy(buffer + offset, path);

  mode_t mode = O_CREAT | O_WRONLY | (append ? O_APPEND : O_TRUNC);
  int fd = open(buffer, mode, 0644);
  if (fd == -1) {
    // Make the parent directories first.
    mkdir_parent(buffer);
    fd = open(buffer, mode, 0644);
  }

  if (fd == -1) {
    perror(buffer);
    return 0;
  }

  fflush(stdout);
  fflush(stderr);

  dup2(fd, 1);
  dup2(fd, 2);

  close(fd);
  return 1;
#endif
}
Ejemplo n.º 30
0
FILE* tmf_freopen_t(const tmf_char16* filename, const tmf_char16* mode, FILE* current) {
    return _wfreopen(filename, mode, current);
}