示例#1
0
文件: PCMain.cpp 项目: Bigpet/native
int main(int argc, char *argv[]) {
#ifdef RPI
    bcm_host_init();
#endif
    putenv((char*)"SDL_VIDEO_CENTERED=1");

    std::string app_name;
    std::string app_name_nice;
    bool landscape;
    NativeGetAppInfo(&app_name, &app_name_nice, &landscape);

    net::Init();
#ifdef __APPLE__
    // Make sure to request a somewhat modern GL context at least - the
    // latest supported by MacOSX (really, really sad...)
    // Requires SDL 2.0
    // We really should upgrade to SDL 2.0 soon.
    //SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
    //SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
#endif

    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_AUDIO) < 0) {
        fprintf(stderr, "Unable to initialize SDL: %s\n", SDL_GetError());
        return 1;
    }
#ifdef USING_EGL
    if (EGL_Open())
        return 1;
#endif

    // Get the video info before doing anything else, so we don't get skewed resolution results.
    const SDL_VideoInfo* desktopVideoInfo = SDL_GetVideoInfo();
    g_DesktopWidth = desktopVideoInfo->current_w;
    g_DesktopHeight = desktopVideoInfo->current_h;

    SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
    SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
    SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, 1);

    int mode;
#ifdef USING_GLES2
    mode = SDL_SWSURFACE | SDL_FULLSCREEN;
#else
    mode = SDL_OPENGL | SDL_RESIZABLE;
#endif
    int set_xres = -1;
    int set_yres = -1;
    bool portrait = false;
    bool set_ipad = false;
    float set_dpi = 1.0f;
    float set_scale = 1.0f;

    for (int i = 1; i < argc; i++) {
        if (!strcmp(argv[i],"--fullscreen"))
            mode |= SDL_FULLSCREEN;
        if (set_xres == -2) {
            set_xres = parseInt(argv[i]);
        } else if (set_yres == -2) {
            set_yres = parseInt(argv[i]);
        }
        if (set_dpi == -2)
            set_dpi = parseFloat(argv[i]);
        if (set_scale == -2)
            set_scale = parseFloat(argv[i]);

        if (!strcmp(argv[i],"--xres"))
            set_xres = -2;
        if (!strcmp(argv[i],"--yres"))
            set_yres = -2;
        if (!strcmp(argv[i],"--dpi"))
            set_dpi = -2;
        if (!strcmp(argv[i],"--scale"))
            set_scale = -2;

        if (!strcmp(argv[i],"--ipad"))
            set_ipad = true;
        if (!strcmp(argv[i],"--portrait"))
            portrait = true;
    }

    if (mode & SDL_FULLSCREEN) {
        const SDL_VideoInfo* info = SDL_GetVideoInfo();
        pixel_xres = info->current_w;
        pixel_yres = info->current_h;
#ifdef PPSSPP
        g_Config.bFullScreen = true;
#endif
    } else {
        // set a sensible default resolution (2x)
        pixel_xres = 480 * 2 * set_scale;
        pixel_yres = 272 * 2 * set_scale;
        if (portrait) {
            std::swap(pixel_xres, pixel_yres);
        }
#ifdef PPSSPP
        g_Config.bFullScreen = false;
#endif
    }

    set_dpi = 1.0f / set_dpi;

    if (set_ipad) {
        pixel_xres = 1024;
        pixel_yres = 768;
    }
    if (!landscape) {
        std::swap(pixel_xres, pixel_yres);
    }

    if (set_xres > 0) {
        pixel_xres = set_xres;
    }
    if (set_yres > 0) {
        pixel_yres = set_yres;
    }
    float dpi_scale = 1.0f;
    if (set_dpi > 0) {
        dpi_scale = set_dpi;
    }

    dp_xres = (float)pixel_xres * dpi_scale;
    dp_yres = (float)pixel_yres * dpi_scale;

    g_Screen = SDL_SetVideoMode(pixel_xres, pixel_yres, 0, mode);
    if (g_Screen == NULL) {
        fprintf(stderr, "SDL SetVideoMode failed: Unable to create OpenGL screen: %s\n", SDL_GetError());
        SDL_Quit();
        return 2;
    }

#ifdef USING_EGL
    EGL_Init();
#endif

#ifdef PPSSPP
    SDL_WM_SetCaption((app_name_nice + " " + PPSSPP_GIT_VERSION).c_str(), NULL);
#endif

#ifdef MOBILE_DEVICE
    SDL_ShowCursor(SDL_DISABLE);
#endif


#ifndef USING_GLES2
    if (GLEW_OK != glewInit()) {
        printf("Failed to initialize glew!\n");
        return 1;
    }

    if (GLEW_VERSION_2_0) {
        printf("OpenGL 2.0 or higher.\n");
    } else {
        printf("Sorry, this program requires OpenGL 2.0.\n");
        return 1;
    }
#endif

#ifdef _MSC_VER
    // VFSRegister("temp/", new DirectoryAssetReader("E:\\Temp\\"));
    TCHAR path[MAX_PATH];
    SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, path);
    PathAppend(path, (app_name + "\\").c_str());
#else
    // Mac / Linux
    char path[512];
    const char *the_path = getenv("HOME");
    if (!the_path) {
        struct passwd* pwd = getpwuid(getuid());
        if (pwd)
            the_path = pwd->pw_dir;
    }
    strcpy(path, the_path);
    if (path[strlen(path)-1] != '/')
        strcat(path, "/");
#endif

#ifdef _WIN32
    NativeInit(argc, (const char **)argv, path, "D:\\", "BADCOFFEE");
#else
    NativeInit(argc, (const char **)argv, path, "/tmp", "BADCOFFEE");
#endif

    pixel_in_dps = (float)pixel_xres / dp_xres;
    g_dpi_scale = dp_xres / (float)pixel_xres;

    printf("Pixels: %i x %i\n", pixel_xres, pixel_yres);
    printf("Virtual pixels: %i x %i\n", dp_xres, dp_yres);

    NativeInitGraphics();
    NativeResized();

    SDL_AudioSpec fmt, ret_fmt;
    memset(&fmt, 0, sizeof(fmt));
    fmt.freq = 44100;
    fmt.format = AUDIO_S16;
    fmt.channels = 2;
    fmt.samples = 2048;
    fmt.callback = &mixaudio;
    fmt.userdata = (void *)0;

    if (SDL_OpenAudio(&fmt, &ret_fmt) < 0) {
        ELOG("Failed to open audio: %s", SDL_GetError());
    } else {
        if (ret_fmt.freq != 44100 || ret_fmt.format != AUDIO_S16 || ret_fmt.channels != 2 || fmt.samples != 2048) {
            ELOG("Sound buffer format does not match requested format.");
            ELOG("Output audio freq: %d (requested: %d)", ret_fmt.freq, 44100);
            ELOG("Output audio format: %d (requested: %d)", ret_fmt.format, AUDIO_S16);
            ELOG("Output audio channels: %d (requested: %d)", ret_fmt.channels, 2);
            ELOG("Output audio samples: %d (requested: %d)", ret_fmt.samples, 2048);
        }

        if (ret_fmt.freq != 44100 || ret_fmt.format != AUDIO_S16 || ret_fmt.channels != 2) {
            ELOG("Provided output format does not match requirement, turning audio off");
            SDL_CloseAudio();
        } else {
            ELOG("Provided output audio format is usable, thus using it");
        }
    }

    // Audio must be unpaused _after_ NativeInit()
    SDL_PauseAudio(0);
#ifndef _WIN32
    joystick = new SDLJoystick();
#endif
    EnableFZ();

    int framecount = 0;
    float t = 0;
    float lastT = 0;
    uint32_t pad_buttons = 0;	 // legacy pad buttons
    while (true) {
        input_state.accelerometer_valid = false;
        input_state.mouse_valid = true;

        SDL_Event event;
        while (SDL_PollEvent(&event)) {
            float mx = event.motion.x * g_dpi_scale;
            float my = event.motion.y * g_dpi_scale;

            switch (event.type) {
            case SDL_QUIT:
                g_QuitRequested = 1;
                break;
#if !defined(MOBILE_DEVICE)
            case SDL_VIDEORESIZE:
            {
                g_Screen = SDL_SetVideoMode(event.resize.w, event.resize.h, 0, SDL_OPENGL | SDL_RESIZABLE);
                if (g_Screen == NULL) {
                    fprintf(stderr, "SDL SetVideoMode failed: Unable to create OpenGL screen: %s\n", SDL_GetError());
                    SDL_Quit();
                    return 2;
                }
                pixel_xres = event.resize.w;
                pixel_yres = event.resize.h;
                dp_xres = (float)pixel_xres * dpi_scale;
                dp_yres = (float)pixel_yres * dpi_scale;
                NativeResized();
                break;
            }
#endif
            case SDL_KEYDOWN:
            {
                int k = event.key.keysym.sym;
                KeyInput key;
                key.flags = KEY_DOWN;
                key.keyCode = KeyMapRawSDLtoNative.find(k)->second;
                key.deviceId = DEVICE_ID_KEYBOARD;
                NativeKey(key);

                for (int i = 0; i < ARRAY_SIZE(legacyKeyMap); i++) {
                    if (legacyKeyMap[i] == key.keyCode)
                        pad_buttons |= 1 << i;
                }
                break;
            }
            case SDL_KEYUP:
            {
                int k = event.key.keysym.sym;
                KeyInput key;
                key.flags = KEY_UP;
                key.keyCode = KeyMapRawSDLtoNative.find(k)->second;
                key.deviceId = DEVICE_ID_KEYBOARD;
                NativeKey(key);
                for (int i = 0; i < ARRAY_SIZE(legacyKeyMap); i++) {
                    if (legacyKeyMap[i] == key.keyCode)
                        pad_buttons &= ~(1 << i);
                }
                break;
            }
            case SDL_MOUSEBUTTONDOWN:
                switch (event.button.button) {
                case SDL_BUTTON_LEFT:
                {
                    input_state.pointer_x[0] = mx;
                    input_state.pointer_y[0] = my;
                    input_state.pointer_down[0] = true;
                    input_state.mouse_valid = true;
                    TouchInput input;
                    input.x = mx;
                    input.y = my;
                    input.flags = TOUCH_DOWN;
                    input.id = 0;
                    NativeTouch(input);
                    KeyInput key(DEVICE_ID_MOUSE, NKCODE_EXT_MOUSEBUTTON_1, KEY_DOWN);
                    NativeKey(key);
                }
                break;
                case SDL_BUTTON_RIGHT:
                {
                    KeyInput key(DEVICE_ID_MOUSE, NKCODE_EXT_MOUSEBUTTON_2, KEY_DOWN);
                    NativeKey(key);
                }
                break;
                case SDL_BUTTON_WHEELUP:
                {
                    KeyInput key;
                    key.deviceId = DEVICE_ID_MOUSE;
                    key.keyCode = NKCODE_EXT_MOUSEWHEEL_UP;
                    key.flags = KEY_DOWN;
                    NativeKey(key);
                }
                break;
                case SDL_BUTTON_WHEELDOWN:
                {
                    KeyInput key;
                    key.deviceId = DEVICE_ID_MOUSE;
                    key.keyCode = NKCODE_EXT_MOUSEWHEEL_DOWN;
                    key.flags = KEY_DOWN;
                    NativeKey(key);
                }
                break;
                }
                break;
            case SDL_MOUSEMOTION:
                if (input_state.pointer_down[0]) {
                    input_state.pointer_x[0] = mx;
                    input_state.pointer_y[0] = my;
                    input_state.mouse_valid = true;
                    TouchInput input;
                    input.x = mx;
                    input.y = my;
                    input.flags = TOUCH_MOVE;
                    input.id = 0;
                    NativeTouch(input);
                }
                break;
            case SDL_MOUSEBUTTONUP:
                switch (event.button.button) {
                case SDL_BUTTON_LEFT:
                {
                    input_state.pointer_x[0] = mx;
                    input_state.pointer_y[0] = my;
                    input_state.pointer_down[0] = false;
                    input_state.mouse_valid = true;
                    //input_state.mouse_buttons_up = 1;
                    TouchInput input;
                    input.x = mx;
                    input.y = my;
                    input.flags = TOUCH_UP;
                    input.id = 0;
                    NativeTouch(input);
                    KeyInput key(DEVICE_ID_MOUSE, NKCODE_EXT_MOUSEBUTTON_1, KEY_UP);
                    NativeKey(key);
                }
                break;
                case SDL_BUTTON_RIGHT:
                {
                    KeyInput key(DEVICE_ID_MOUSE, NKCODE_EXT_MOUSEBUTTON_2, KEY_UP);
                    NativeKey(key);
                }
                break;
                case SDL_BUTTON_WHEELUP:
                {
                    KeyInput key;
                    key.deviceId = DEVICE_ID_DEFAULT;
                    key.keyCode = NKCODE_EXT_MOUSEWHEEL_UP;
                    key.flags = KEY_UP;
                    NativeKey(key);
                }
                break;
                case SDL_BUTTON_WHEELDOWN:
                {
                    KeyInput key;
                    key.deviceId = DEVICE_ID_DEFAULT;
                    key.keyCode = NKCODE_EXT_MOUSEWHEEL_DOWN;
                    key.flags = KEY_UP;
                    NativeKey(key);
                }
                break;
                }
                break;
            default:
#ifndef _WIN32
                joystick->ProcessInput(event);
#endif
                break;
            }
        }
        if (g_QuitRequested)
            break;
        const uint8 *keys = (const uint8 *)SDL_GetKeyState(NULL);
        SimulateGamepad(keys, &input_state);
        input_state.pad_buttons = pad_buttons;
        UpdateInputState(&input_state, true);
        NativeUpdate(input_state);
        if (g_QuitRequested)
            break;
        NativeRender();
#if defined(PPSSPP) && !defined(MOBILE_DEVICE)
        if (lastUIState != globalUIState) {
            lastUIState = globalUIState;
            if (lastUIState == UISTATE_INGAME && g_Config.bFullScreen && !g_Config.bShowTouchControls)
                SDL_ShowCursor(SDL_DISABLE);
            if (lastUIState != UISTATE_INGAME && g_Config.bFullScreen)
                SDL_ShowCursor(SDL_ENABLE);
        }
#endif

        EndInputState(&input_state);

        if (framecount % 60 == 0) {
            // glsl_refresh(); // auto-reloads modified GLSL shaders once per second.
        }

#ifdef USING_EGL
        eglSwapBuffers(g_eglDisplay, g_eglSurface);
#else
        if (!keys[SDLK_TAB] || t - lastT >= 1.0/60.0)
        {
            SDL_GL_SwapBuffers();
            lastT = t;
        }
#endif

        ToggleFullScreenIfFlagSet();
        time_update();
        t = time_now();
        framecount++;
    }
#ifndef _WIN32
    delete joystick;
#endif
    // Faster exit, thanks to the OS. Remove this if you want to debug shutdown
    // The speed difference is only really noticable on Linux. On Windows you do notice it though
#ifndef MOBILE_DEVICE
    exit(0);
#endif
    NativeShutdownGraphics();
    SDL_PauseAudio(1);
    SDL_CloseAudio();
    NativeShutdown();
#ifdef USING_EGL
    EGL_Close();
#endif
    SDL_Quit();
    net::Shutdown();
#ifdef RPI
    bcm_host_deinit();
#endif

    exit(0);
    return 0;
}
void FFileManagerWindows::Init(UBOOL Startup)
{
	// a shipped PC game will always run as if installed
#if SHIPPING_PC_GAME && !UDK
	// shipping PC game 
	bIsRunningInstalled = TRUE;
#else
	// for development, use a commandline param (-installed)
	bIsRunningInstalled = ParseParam(appCmdLine(),TEXT("installed"));
#endif

	// Allow overriding use of My Documents folder with -NOHOMEDIR
	if( ParseParam(appCmdLine(),TEXT("NOHOMEDIR") ) )
	{
		bIsRunningInstalled = FALSE;
	}

	if (bIsRunningInstalled)
	{
		debugf( TEXT( " ... running in INSTALLED mode" ) );

		TCHAR UserPath[MAX_PATH];
		// get the My Documents directory
		HRESULT Ret = SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, SHGFP_TYPE_CURRENT, UserPath);

		// get the per-game directory name to use inside the My Documents directory 
		FString DefaultIniContents;
		// load the DefaultEngine.ini config file into a string for later parsing (ConvertAbsolutePathToUserPath will use
		// original location since WindowsUserDir hasn't been set yet)
		// can't use GDefaultEngineIni, because that may be something that doesn't have the tag
		if (!appLoadFileToString(DefaultIniContents, *(appGameConfigDir() + TEXT("DefaultEngine.ini")), this))
		{
			// appMsgf won't write to a log if GWarn is NULL, which it should be at this point
			appMsgf(AMT_OK, TEXT("Failed to find default engine .ini file to retrieve My Documents subdirectory to use. Force quitting."));
			exit(1);
			return;
		}

		#define MYDOC_KEY_NAME TEXT("MyDocumentsSubDirName=")

		// find special key in the .ini file (can't use GConfig because it can't be used yet until after filemanager is made)
		INT KeyLocation = DefaultIniContents.InStr(MYDOC_KEY_NAME, FALSE, TRUE);
		if (KeyLocation == INDEX_NONE)
		{
			// appMsgf won't write to a log if GWarn is NULL, which it should be at this point
			appMsgf(AMT_OK, TEXT("Failed to find %s key in DefaultEngine.ini. Force quitting."), MYDOC_KEY_NAME);
			exit(1);
			return;
		}

		// skip over the key to get the value (skip key and = sign) and everything after it
		FString ValueAndLeftover = DefaultIniContents.Mid(KeyLocation + appStrlen(MYDOC_KEY_NAME));
		
		// now chop off this string at an end of line
		TArray<FString> Tokens;
		ValueAndLeftover.ParseIntoArray(&Tokens, TEXT("\r\n"), TRUE);

		// make the base user dir path
		WindowsUserDir = FString(UserPath) 
							+ TEXT("\\My Games\\") 
							+ Tokens(0) 
#if DEMOVERSION
							+ TEXT(" Demo")
#endif
							+ TEXT("\\");

		// find out our executable path
		WindowsRootDir = appBaseDir();
		// strip off the Binaries directory
		WindowsRootDir = WindowsRootDir.Left(WindowsRootDir.InStr(TEXT("\\Binaries\\"), TRUE, TRUE) + 1);

		// Now that the root directory has been set, create directories at startup.
		// Note this must come after the above because MakeDirectory calls
		// ConvertAbsolutePathToUserPath which uses WindowsRootDir and WindowsUserDir.
		#define DIRSTOCREATATSTARTUP_KEY_NAME TEXT("DirsToCreateAtStartup=")
		INT FindStartPos = INDEX_NONE;
		while ( TRUE )
		{
			// find special key in the .ini file (can't use GConfig because it can't be used yet until after filemanager is made)
			const INT KeyLocation = DefaultIniContents.InStr(DIRSTOCREATATSTARTUP_KEY_NAME, FALSE, TRUE, FindStartPos);
			if (KeyLocation == INDEX_NONE)
			{
				break;
			}
			// Advance the find pos because we're doing a multi find.
			FindStartPos = KeyLocation + appStrlen(DIRSTOCREATATSTARTUP_KEY_NAME);

			// skip over the key to get the value (skip key and = sign) and everything after it
			FString ValueAndLeftover = DefaultIniContents.Mid(KeyLocation + appStrlen(DIRSTOCREATATSTARTUP_KEY_NAME));
			
			// now chop off this string at an end of line
			TArray<FString> Tokens;
			ValueAndLeftover.ParseIntoArray(&Tokens, TEXT("\r\n"), TRUE);

			// Create the directory.
			MakeDirectory( *Tokens(0), TRUE );
		}
	}

	FFileManagerGeneric::Init(Startup);
}
示例#3
0
文件: System.cpp 项目: septag/stcore
Path System::GetUserDir()
{
    Path p;
    SHGetFolderPath(NULL, CSIDL_PROFILE, nullptr, SHGFP_TYPE_CURRENT, p.getBuffer());
    return p;
}
示例#4
0
LONG CMiniDumper::TopLevelFilter(struct _EXCEPTION_POINTERS* pExceptionInfo)
{
	   
	LONG lRetValue = EXCEPTION_CONTINUE_SEARCH;
	TCHAR szResult[_MAX_PATH + 1024] = {0};
	MINIDUMPWRITEDUMP pfnMiniDumpWriteDump = NULL;
	HMODULE hDll = GetDebugHelperDll((FARPROC*)&pfnMiniDumpWriteDump, true);
	HINSTANCE	hInstCrashReporter = NULL;	
	if (hDll)
	{
		if (pfnMiniDumpWriteDump)
		{

			{
				// Create full path for BugReport.exe
				TCHAR szSharkPath[_MAX_PATH] = {0};
				TCHAR szDumpPath_no_time[_MAX_PATH] = {0};
				GetModuleFileName(NULL, szSharkPath, wcslen(szSharkPath));
				LPTSTR pszFileName = _tcsrchr(szSharkPath, _T('\\'));
				if (pszFileName) {
					pszFileName++;
					*pszFileName = _T('\0');
				}

				TCHAR szCrashReport[MAX_PATH] = {0};
				_tcsncat(szCrashReport,szSharkPath,wcslen(szCrashReport) - 1);
				_tcsncat(szCrashReport,_T("BugReport.exe"),wcslen(szCrashReport) - 1);

				// Create full path for DUMP file
				TCHAR szDumpPath[MAX_PATH]={0};
				SHGetFolderPath(NULL, CSIDL_APPDATA,NULL,SHGFP_TYPE_CURRENT,szDumpPath);
				_tcsncat(szDumpPath,_T("\\XiaTing\\"),wcslen(szDumpPath) - 1);

				// Replace spaces and dots in file name.
				TCHAR szBaseName[_MAX_PATH] = {0};
				_tcsncat(szBaseName, m_szAppName, wcslen(szBaseName) - 1);
				LPTSTR psz = szBaseName;
				while (*psz != _T('\0')) {
					if (*psz == _T('.'))
						*psz = _T('-');
					else if (*psz == _T(' '))
						*psz = _T('_');
					psz++;
				}
				_tcsncat(szDumpPath, szBaseName, wcslen(szDumpPath) - 1);
				_tcsncat(szDumpPath_no_time, szBaseName, wcslen(szDumpPath_no_time) - 1);				
				
				if (!theCrashDumper.mb_user_mode)
				{
					time_t n_now = time(NULL);
					struct tm* p_time = localtime(&n_now);
					if (p_time != NULL)
					{
						TCHAR s_format[256];
						s_format[0] = 0x0;
						_tcsftime(s_format, 255, _T("-%Y.%m.%d - %H-%M-%S"), p_time);
						_tcsncat(szDumpPath, s_format, _tcslen(s_format) -1);
					}
				}                
				_tcsncat(szDumpPath, _T(".dmp"), wcslen(szDumpPath) - 1);
				_tcsncat(szDumpPath_no_time, _T(".dmp"), wcslen(szDumpPath_no_time) - 1);

               
				HANDLE hFile = CreateFile(szDumpPath, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
				if (hFile != INVALID_HANDLE_VALUE)
				{
					_MINIDUMP_EXCEPTION_INFORMATION ExInfo = {0};
					ExInfo.ThreadId = GetCurrentThreadId();
					ExInfo.ExceptionPointers = pExceptionInfo;
					ExInfo.ClientPointers = NULL;

					BOOL bOK = (*pfnMiniDumpWriteDump)(GetCurrentProcess(), GetCurrentProcessId(), hFile, MiniDumpNormal, &ExInfo, NULL, NULL);
					if (bOK)
					{
						
						_sntprintf(szResult, wcslen(szResult), _T("Saved dump file to \"%s\".\r\n\r\nPlease send this file together with a detailed bug report to [email protected] !\r\n\r\nThank you for helping to improve eMule."), szDumpPath);
						lRetValue = EXCEPTION_EXECUTE_HANDLER;
						
						CString cs_cmd_line;
						cs_cmd_line.Format(_T("%s%s"),_T("Cmd|"),szDumpPath_no_time);						
						
						hInstCrashReporter = ShellExecuteW(NULL, _T("open"), szCrashReport, cs_cmd_line.GetBuffer(), NULL, SW_SHOW);
						if (hInstCrashReporter <= (HINSTANCE)32)
							lRetValue = EXCEPTION_CONTINUE_SEARCH;
						
					}
					else
					{						
						_sntprintf(szResult, wcslen(szResult), _T("Failed to save dump file to \"%s\".\r\n\r\nError: %u"), szDumpPath, GetLastError());
					}
					CloseHandle(hFile);
				}
				else
				{					
					_sntprintf(szResult, wcslen(szResult), _T("Failed to create dump file \"%s\".\r\n\r\nError: %u"), szDumpPath, GetLastError());
				}
			}
		}
		FreeLibrary(hDll);
		hDll = NULL;
		pfnMiniDumpWriteDump = NULL;
	}

#ifndef _DEBUG
	if (EXCEPTION_EXECUTE_HANDLER == lRetValue)		
	{
		exit(0);
	}
	else
		return lRetValue;

#else

	return lRetValue;
#endif
}
示例#5
0
Global::Global() {
	mw = 0;
	db = 0;
	p = 0;
	nam = 0;
	uiSession = 0;
	uiDoublePush = 1000000;
	iPushToTalk = 0;
	iTarget = 0;
	iPrevTarget = 0;
	bPushToMute = false;
	bCenterPosition = false;
	bPosTest = false;
	bInAudioWizard = false;
	iAudioPathTime = 0;
	iAudioBandwidth = -1;
	iMaxBandwidth = -1;

	iCodecAlpha = 0;
	iCodecBeta = 0;
	bPreferAlpha = true;
	bOpus = true;

	bAttenuateOthers = false;

	bAllowHTML = true;
	uiMessageLength = 5000;
	uiImageLength = 131072;

	qs = NULL;

	ocIntercept = NULL;
	bc = NULL;
	lcd = NULL;
	o = NULL;
	l = NULL;

	bHappyEaster = false;

	bQuit = false;

	QStringList qsl;
	qsl << QCoreApplication::instance()->applicationDirPath();
	qsl << QDesktopServices::storageLocation(QDesktopServices::DataLocation);
#if defined(Q_OS_WIN)
	QString appdata;
	wchar_t appData[MAX_PATH];
	if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, SHGFP_TYPE_CURRENT, appData))) {
		appdata = QDir::fromNativeSeparators(QString::fromWCharArray(appData));

		if (!appdata.isEmpty()) {
			appdata.append(QLatin1String("/Mumble"));
			qsl << appdata;
		}
	}
#endif

	foreach(const QString &dir, qsl) {
		QFile inifile(QString::fromLatin1("%1/mumble.ini").arg(dir));
		if (inifile.exists() && inifile.permissions().testFlag(QFile::WriteUser)) {
			qdBasePath = dir;
			qs = new QSettings(inifile.fileName(), QSettings::IniFormat);
			break;
		}
	}
void set_preferences_dir(std::string path)
{
#ifdef _WIN32
	if(path.empty()) {
		game_config::preferences_dir = get_cwd() + "/userdata";
	} else if (path.size() > 2 && path[1] == ':') {
		//allow absolute path override
		game_config::preferences_dir = path;
	} else {
		char my_documents_path[MAX_PATH];
		if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, 0, my_documents_path))) {
            std::string mygames_path = std::string(my_documents_path) + "/" + "My Games";
			boost::algorithm::replace_all(mygames_path, std::string("\\"), std::string("/"));
			create_directory_if_missing(mygames_path);
			game_config::preferences_dir = mygames_path + "/" + path;

			// unicode to utf8
			WCHAR wc[MAX_PATH];
			SHGetFolderPathW(NULL, CSIDL_PERSONAL, NULL, 0, wc);
			WideCharToMultiByte(CP_UTF8, 0, wc, -1, my_documents_path, MAX_PATH, NULL, NULL);
			mygames_path = std::string(my_documents_path) + "/" + "My Games";
			boost::algorithm::replace_all(mygames_path, std::string("\\"), std::string("/"));
			game_config::preferences_dir_utf8 = mygames_path + "/" + path;
		} else {
			game_config::preferences_dir = get_cwd() + "/" + path;
		}
	}
	// conv_ansi_utf8(game_config::preferences_dir, true);

#elif defined(ANDROID)
	game_config::preferences_dir = game_config::path + std::string("/") + path;
	// non-win32, assume no tow-code character.
	game_config::preferences_dir_utf8 = game_config::preferences_dir;
#elif defined(__APPLE__) && !TARGET_OS_IPHONE
	game_config::preferences_dir = get_cwd() + std::string("/../") + path;
	// non-win32, assume no tow-code character.
	game_config::preferences_dir_utf8 = game_config::preferences_dir;
#else
#ifdef PREFERENCES_DIR
	if (path.empty()) path = PREFERENCES_DIR;
#endif

	std::string path2 = ".wesnoth" + game_config::version.substr(0,3);

#ifdef _X11
	const char *home_str = getenv("HOME");

	if (path.empty()) {
		char const *xdg_data = getenv("XDG_DATA_HOME");
		if (!xdg_data || xdg_data[0] == '\0') {
			if (!home_str) {
				path = path2;
				goto other;
			}
			user_data_dir = home_str;
			user_data_dir += "/.local/share";
		} else user_data_dir = xdg_data;
		user_data_dir += "/wesnoth/";
		user_data_dir += game_config::version.substr(0,3);
		create_directory_if_missing_recursive(user_data_dir);
		game_config::preferences_dir = user_data_dir;
	} else {
		other:
		std::string home = home_str ? home_str : ".";

		if (path[0] == '/')
			game_config::preferences_dir = path;
		else
			game_config::preferences_dir = home + "/" + path;
	}
#else
	if (path.empty()) path = path2;

#ifdef __AMIGAOS4__
	game_config::preferences_dir = "PROGDIR:" + path;
#elif defined(__BEOS__)
	if (be_path.InitCheck() != B_OK) {
		BPath tpath;
		if (find_directory(B_USER_SETTINGS_DIRECTORY, &be_path, true) == B_OK) {
			be_path.Append("wesnoth");
		} else {
			be_path.SetTo("/boot/home/config/settings/wesnoth");
		}
		game_config::preferences_dir = be_path.Path();
	}
#else
	const char* home_str = getenv("HOME");
	std::string home = home_str ? home_str : ".";

	if (path[0] == '/')
		game_config::preferences_dir = path;
	else
		game_config::preferences_dir = home + std::string("/") + path;
#endif
#endif
	// non-win32, assume no tow-code character.
	game_config::preferences_dir_utf8 = game_config::preferences_dir;
#endif /*_WIN32*/
	user_data_dir = game_config::preferences_dir;
#ifdef ANDROID
	__android_log_print(ANDROID_LOG_INFO, "SDL", "set_preferences, user_data_dir: %s", user_data_dir.c_str());
#endif
	user_data_dir_utf8 = game_config::preferences_dir_utf8;
	setup_user_data_dir();
}
示例#7
0
void SetUserDirectory(const std::string& custom_path)
{
  if (!custom_path.empty())
  {
    File::CreateFullPath(custom_path + DIR_SEP);
    File::SetUserPath(D_USER_IDX, custom_path + DIR_SEP);
    return;
  }

  std::string user_path = "";
#ifdef _WIN32
  // Detect where the User directory is. There are five different cases
  // (on top of the command line flag, which overrides all this):
  // 1. GetExeDirectory()\portable.txt exists
  //    -> Use GetExeDirectory()\User
  // 2. HKCU\Software\Dolphin Emulator\LocalUserConfig exists and is true
  //    -> Use GetExeDirectory()\User
  // 3. HKCU\Software\Dolphin Emulator\UserConfigPath exists
  //    -> Use this as the user directory path
  // 4. My Documents exists
  //    -> Use My Documents\Dolphin Emulator as the User directory path
  // 5. Default
  //    -> Use GetExeDirectory()\User

  // Check our registry keys
  HKEY hkey;
  DWORD local = 0;
  TCHAR configPath[MAX_PATH] = {0};
  if (RegOpenKeyEx(HKEY_CURRENT_USER, TEXT("Software\\Dolphin Emulator"), 0, KEY_QUERY_VALUE,
                   &hkey) == ERROR_SUCCESS)
  {
    DWORD size = 4;
    if (RegQueryValueEx(hkey, TEXT("LocalUserConfig"), nullptr, nullptr,
                        reinterpret_cast<LPBYTE>(&local), &size) != ERROR_SUCCESS)
      local = 0;

    size = MAX_PATH;
    if (RegQueryValueEx(hkey, TEXT("UserConfigPath"), nullptr, nullptr, (LPBYTE)configPath,
                        &size) != ERROR_SUCCESS)
      configPath[0] = 0;
    RegCloseKey(hkey);
  }

  local = local || File::Exists(File::GetExeDirectory() + DIR_SEP "portable.txt");

  // Get Program Files path in case we need it.
  TCHAR my_documents[MAX_PATH];
  bool my_documents_found = SUCCEEDED(
      SHGetFolderPath(nullptr, CSIDL_MYDOCUMENTS, nullptr, SHGFP_TYPE_CURRENT, my_documents));

  if (local)  // Case 1-2
    user_path = File::GetExeDirectory() + DIR_SEP USERDATA_DIR DIR_SEP;
  else if (configPath[0])  // Case 3
    user_path = TStrToUTF8(configPath);
  else if (my_documents_found)  // Case 4
    user_path = TStrToUTF8(my_documents) + DIR_SEP "Dolphin Emulator" DIR_SEP;
  else  // Case 5
    user_path = File::GetExeDirectory() + DIR_SEP USERDATA_DIR DIR_SEP;

  // Prettify the path: it will be displayed in some places, we don't want a mix
  // of \ and /.
  user_path = ReplaceAll(user_path, "\\", DIR_SEP);

  // Make sure it ends in DIR_SEP.
  if (*user_path.rbegin() != DIR_SEP_CHR)
    user_path += DIR_SEP;

#else
  if (File::Exists(ROOT_DIR DIR_SEP USERDATA_DIR))
  {
    user_path = ROOT_DIR DIR_SEP USERDATA_DIR DIR_SEP;
  }
  else
  {
    const char* env_path = getenv("DOLPHIN_EMU_USERPATH");
    const char* home = getenv("HOME");
    if (!home)
      home = getenv("PWD");
    if (!home)
      home = "";
    std::string home_path = std::string(home) + DIR_SEP;

#if defined(__APPLE__) || defined(ANDROID)
    if (env_path)
    {
      user_path = env_path;
    }
    else
    {
      user_path = home_path + DOLPHIN_DATA_DIR DIR_SEP;
    }
#else
    // We are on a non-Apple and non-Android POSIX system, there are 4 cases:
    // 1. GetExeDirectory()/portable.txt exists
    //    -> Use GetExeDirectory()/User
    // 2. $DOLPHIN_EMU_USERPATH is set
    //    -> Use $DOLPHIN_EMU_USERPATH
    // 3. ~/.dolphin-emu directory exists
    //    -> Use ~/.dolphin-emu
    // 4. Default
    //    -> Use XDG basedir, see
    //    http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
    user_path = home_path + "." DOLPHIN_DATA_DIR DIR_SEP;
    std::string exe_path = File::GetExeDirectory();
    if (File::Exists(exe_path + DIR_SEP "portable.txt"))
    {
      user_path = exe_path + DIR_SEP "User" DIR_SEP;
    }
    else if (env_path)
    {
      user_path = env_path;
    }
    else if (!File::Exists(user_path))
    {
      const char* data_home = getenv("XDG_DATA_HOME");
      std::string data_path =
          std::string(data_home && data_home[0] == '/' ? data_home :
                                                         (home_path + ".local" DIR_SEP "share")) +
          DIR_SEP DOLPHIN_DATA_DIR DIR_SEP;

      const char* config_home = getenv("XDG_CONFIG_HOME");
      std::string config_path =
          std::string(config_home && config_home[0] == '/' ? config_home :
                                                             (home_path + ".config")) +
          DIR_SEP DOLPHIN_DATA_DIR DIR_SEP;

      const char* cache_home = getenv("XDG_CACHE_HOME");
      std::string cache_path =
          std::string(cache_home && cache_home[0] == '/' ? cache_home : (home_path + ".cache")) +
          DIR_SEP DOLPHIN_DATA_DIR DIR_SEP;

      File::SetUserPath(D_USER_IDX, data_path);
      File::SetUserPath(D_CONFIG_IDX, config_path);
      File::SetUserPath(D_CACHE_IDX, cache_path);
      return;
    }
#endif
  }
#endif
  File::SetUserPath(D_USER_IDX, user_path);
}
示例#8
0
// Here is the entry point for the Plugin..this gets called first.
int initaltacast(struct winampDSPModule *this_mod)
{
	char filename[512],*p;
	char	directory[1024] = "";
	char currentDir[1024] = "";
	

	memset(filename, '\000', sizeof(filename));
	GetModuleFileName(this_mod->hDllInstance,filename,sizeof(filename));
	strcpy(currentDir, filename);
	char *pend;
	pend = strrchr(currentDir, '\\');
	if (pend) {
		*pend = '\000';
	}
	p = filename+lstrlen(filename);
	while (p >= filename && *p != '\\') p--;
	p++;

	char	logFile[1024] = "";
	memset(logFile, '\000', sizeof(logFile));
	char *p2 = strchr(p, '.');
	if (p2) {
		strncpy(logFile, p, p2-p);
	}
	else {
		strcpy(logFile, p);
	}

	char tmpfile[MAX_PATH] = "";
	sprintf(tmpfile, "%s\\.tmp", currentDir);

	FILE *filep = fopen(tmpfile, "w");
	if (filep == 0) {
		char path[MAX_PATH] = "";

		SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, path);
		strcpy(currentDir, path);
	}
	else {
		fclose(filep);
	}
    LoadConfigs(currentDir, logFile);


	ghwnd_winamp = this_mod->hwndParent;

    AfxWinInit( this_mod->hDllInstance, NULL, "", SW_HIDE);

    mainWindow = new CMainWindow();
    mainWindow->InitializeWindow();

    strcpy(mainWindow->m_currentDir, currentDir);
    mainWindow->Create((UINT)IDD_ALTACAST, AfxGetMainWnd());
    int x = getLastX();
    int y = getLastY();
    if (x < 0) {
        x = 0;
    }
    if (y < 0) {
        y = 0;
    }
    mainWindow->SetWindowPos(NULL, (int)x, (int)y, -1, -1, SWP_NOSIZE | SWP_SHOWWINDOW);

    mainWindow->SetIcon(mainApp.LoadIcon(IDR_MAINFRAME), TRUE);
    
    mainWindow->ShowWindow(SW_SHOW);

	initializealtacast();

	timerId = SetTimer(NULL, 1, 1000, (TIMERPROC)getCurrentSongTitle);

	return 0;
}
示例#9
0
static void initialize_application(void)
{
#if defined(__WIN32__) && defined(__MINGW32__)
	if (LoadLibrary("exchndl.dll")) option_debug = true;
#endif

	//	SDL_putenv(const_cast<char*>("SDL_VIDEO_ALLOW_SCREENSAVER=1"));

	// Initialize SDL
	int retval = SDL_Init(SDL_INIT_VIDEO |
						  (option_nosound ? 0 : SDL_INIT_AUDIO) |
						  (option_nojoystick ? 0 : SDL_INIT_JOYSTICK) |
						  (option_debug ? SDL_INIT_NOPARACHUTE : 0));
	if (retval < 0)
	{
		const char *sdl_err = SDL_GetError();
		if (sdl_err)
			fprintf(stderr, "Couldn't initialize SDL (%s)\n", sdl_err);
		else
			fprintf(stderr, "Couldn't initialize SDL\n");
		exit(1);
	}
#if defined(HAVE_SDL_IMAGE)
	IMG_Init(IMG_INIT_JPG | IMG_INIT_PNG);
#endif

	// Find data directories, construct search path
	InitDefaultStringSets();

#if defined(unix) || defined(__NetBSD__) || defined(__OpenBSD__) || (defined(__APPLE__) && defined(__MACH__) && !defined(HAVE_BUNDLE_NAME))

	default_data_dir = PKGDATADIR;
	const char *home = getenv("HOME");
	if (home)
		local_data_dir = home;
	local_data_dir += ".alephone";
	log_dir = local_data_dir;

#elif defined(__APPLE__) && defined(__MACH__)
	bundle_data_dir = bundle_resource_path;
	bundle_data_dir += "DataFiles";

	data_search_path.push_back(bundle_data_dir);

#ifndef SCENARIO_IS_BUNDLED
	{
		char* buf = getcwd(0, 0);
		default_data_dir = buf;
		free(buf);
	}
#endif
	
	log_dir = app_log_directory;
	preferences_dir = app_preferences_directory;
	local_data_dir = app_support_directory;

#elif defined(__WIN32__)

	char file_name[MAX_PATH];
	GetModuleFileName(NULL, file_name, sizeof(file_name));
	char *sep = strrchr(file_name, '\\');
	*sep = '\0';

	default_data_dir = file_name;

	char login[17];
	DWORD len = 17;

	bool hasName = (GetUserName((LPSTR) login, &len) == TRUE);
	if (!hasName || strpbrk(login, "\\/:*?\"<>|") != NULL)
		strcpy(login, "Bob User");

	DirectorySpecifier legacy_data_dir = file_name;
	legacy_data_dir += "Prefs";
	legacy_data_dir += login;
	
	SHGetFolderPath(NULL,
			CSIDL_PERSONAL | CSIDL_FLAG_CREATE,
			NULL,
			0,
			file_name);
	local_data_dir = file_name;
	local_data_dir += "AlephOne";

	log_dir = local_data_dir;

#else
	default_data_dir = "";
	local_data_dir = "";
//#error Data file paths must be set for this platform.
#endif

#if defined(__WIN32__)
#define LIST_SEP ';'
#else
#define LIST_SEP ':'
#endif
	
	// in case we need to redo search path later:
	size_t dsp_insert_pos = data_search_path.size();
	size_t dsp_delete_pos = (size_t)-1;
	
	if (arg_directory != "")
	{
		default_data_dir = arg_directory;
		dsp_delete_pos = data_search_path.size();
		data_search_path.push_back(arg_directory);
	}

	const char *data_env = getenv("ALEPHONE_DATA");
	if (data_env) {
		// Read colon-separated list of directories
		string path = data_env;
		string::size_type pos;
		while ((pos = path.find(LIST_SEP)) != string::npos) {
			if (pos) {
				string element = path.substr(0, pos);
				data_search_path.push_back(element);
			}
			path.erase(0, pos + 1);
		}
		if (!path.empty())
			data_search_path.push_back(path);
	} else {
		if (arg_directory == "")
		{
			dsp_delete_pos = data_search_path.size();
			data_search_path.push_back(default_data_dir);
		}
#if defined(__WIN32__)
		data_search_path.push_back(legacy_data_dir);
#endif
		data_search_path.push_back(local_data_dir);
	}

	// Subdirectories
#if defined(__MACH__) && defined(__APPLE__)
	DirectorySpecifier legacy_preferences_dir = local_data_dir;
#elif defined(__WIN32__)
	DirectorySpecifier legacy_preferences_dir = legacy_data_dir;
	SHGetFolderPath(NULL, 
			CSIDL_LOCAL_APPDATA | CSIDL_FLAG_CREATE, 
			NULL,
			0,
			file_name);
	preferences_dir = file_name;
	preferences_dir += "AlephOne";
#else
	preferences_dir = local_data_dir;
#endif	
	saved_games_dir = local_data_dir + "Saved Games";
	quick_saves_dir = local_data_dir + "Quick Saves";
	image_cache_dir = local_data_dir + "Image Cache";
	recordings_dir = local_data_dir + "Recordings";
	screenshots_dir = local_data_dir + "Screenshots";
#if defined(__APPLE__) && defined(__MACH__)
    if (app_screenshots_directory)
        screenshots_dir = app_screenshots_directory;
#endif


	DirectorySpecifier local_mml_dir = local_data_dir + "MML";
	DirectorySpecifier local_themes_dir = local_data_dir + "Themes";

	// Setup resource manager
	initialize_resources();

	init_physics_wad_data();
	initialize_fonts(false);

	load_film_profile(FILM_PROFILE_DEFAULT, false);

	// Parse MML files
	LoadBaseMMLScripts();

	// Check for presence of strings
	if (!TS_IsPresent(strERRORS) || !TS_IsPresent(strFILENAMES)) {
		fprintf(stderr, "Can't find required text strings (missing MML?).\n");
		exit(1);
	}
	
	// Check for presence of files (one last chance to change data_search_path)
	if (!have_default_files()) {
		char chosen_dir[256];
		if (alert_choose_scenario(chosen_dir)) {
			// remove original argument (or fallback) from search path
			if (dsp_delete_pos < data_search_path.size())
				data_search_path.erase(data_search_path.begin() + dsp_delete_pos);
			// add selected directory where command-line argument would go
			data_search_path.insert(data_search_path.begin() + dsp_insert_pos, chosen_dir);
			
			default_data_dir = chosen_dir;
			
			// Parse MML files again, now that we have a new dir to search
			initialize_fonts(false);
			LoadBaseMMLScripts();
		}
	}

	initialize_fonts(true);
	Plugins::instance()->enumerate();			
	
#if defined(__WIN32__) || (defined(__MACH__) && defined(__APPLE__))
	preferences_dir.CreateDirectory();
	transition_preferences(legacy_preferences_dir);
#endif

	// Load preferences
	initialize_preferences();

	local_data_dir.CreateDirectory();
	saved_games_dir.CreateDirectory();
	quick_saves_dir.CreateDirectory();
	{
		std::string scen = Scenario::instance()->GetName();
		if (scen.length())
			scen.erase(std::remove_if(scen.begin(), scen.end(), char_is_not_filesafe), scen.end());
		if (!scen.length())
			scen = "Unknown";
		quick_saves_dir += scen;
		quick_saves_dir.CreateDirectory();
	}
	image_cache_dir.CreateDirectory();
	recordings_dir.CreateDirectory();
	screenshots_dir.CreateDirectory();
	local_mml_dir.CreateDirectory();
	local_themes_dir.CreateDirectory();
	
	WadImageCache::instance()->initialize_cache();

#ifndef HAVE_OPENGL
	graphics_preferences->screen_mode.acceleration = _no_acceleration;
#endif
	if (force_fullscreen)
		graphics_preferences->screen_mode.fullscreen = true;
	if (force_windowed)		// takes precedence over fullscreen because windowed is safer
		graphics_preferences->screen_mode.fullscreen = false;
	write_preferences();

	Plugins::instance()->load_mml();

//	SDL_WM_SetCaption(application_name, application_name);

// #if defined(HAVE_SDL_IMAGE) && !(defined(__APPLE__) && defined(__MACH__))
// 	SDL_WM_SetIcon(IMG_ReadXPMFromArray(const_cast<char**>(alephone_xpm)), 0);
// #endif
	atexit(shutdown_application);

#if !defined(DISABLE_NETWORKING)
	// Initialize SDL_net
	if (SDLNet_Init () < 0) {
		fprintf (stderr, "Couldn't initialize SDL_net (%s)\n", SDLNet_GetError());
		exit(1);
	}
#endif

	if (TTF_Init() < 0) {
		fprintf (stderr, "Couldn't initialize SDL_ttf (%s)\n", TTF_GetError());
		exit(1);
	}
	HTTPClient::Init();

	// Initialize everything
	mytm_initialize();
//	initialize_fonts();
	SoundManager::instance()->Initialize(*sound_preferences);
	initialize_marathon_music_handler();
	initialize_keyboard_controller();
	initialize_gamma();
	alephone::Screen::instance()->Initialize(&graphics_preferences->screen_mode);
	initialize_marathon();
	initialize_screen_drawing();
	initialize_dialogs();
	initialize_terminal_manager();
	initialize_shape_handler();
	initialize_fades();
	initialize_images_manager();
	load_environment_from_preferences();
	initialize_game_state();
}
示例#10
0
static int load_vmd_library(const char *fn, t_gmxvmdplugin *vmdplugin)
{
    char            pathname[GMX_PATH_MAX];
    const char     *pathenv;
    const char     *err;
    int             ret = 0;
    char            pathenv_buffer[GMX_PATH_MAX];
#ifndef GMX_NATIVE_WINDOWS
    glob_t          globbuf;
    const char     *defpath_suffix = "/plugins/*/molfile";
    const char     *defpathenv     = GMX_VMD_PLUGIN_PATH;
#else
    WIN32_FIND_DATA ffd;
    HANDLE          hFind = INVALID_HANDLE_VALUE;
    char            progfolder[GMX_PATH_MAX];
    char            defpathenv[GMX_PATH_MAX];
    const char     *defpath_suffix = "\\plugins\\WIN32\\molfile";
    SHGetFolderPath(NULL, CSIDL_PROGRAM_FILES, NULL, SHGFP_TYPE_CURRENT, progfolder);
    sprintf(defpathenv, "%s\\University of Illinois\\VMD\\plugins\\WIN32\\molfile", progfolder);
#endif

    vmdplugin->api      = NULL;
    vmdplugin->filetype = strrchr(fn, '.');
    if (!vmdplugin->filetype)
    {
        return 0;
    }
    vmdplugin->filetype++;

    /* First look for an explicit path given at run time for the
     * plugins, then an implicit run-time path, and finally for one
     * given at configure time. This last might be hard-coded to the
     * default for VMD installs. */
    pathenv = getenv("VMD_PLUGIN_PATH");
    if (pathenv == NULL)
    {
        pathenv = getenv("VMDDIR");
        if (NULL == pathenv)
        {
            printf("\nNeither VMD_PLUGIN_PATH or VMDDIR set. ");
            printf("Using default location:\n%s\n", defpathenv);
            pathenv = defpathenv;
        }
        else
        {
            printf("\nVMD_PLUGIN_PATH no set, but VMDDIR is set. ");
#ifdef _MSC_VER
            _snprintf_s(pathenv_buffer, sizeof(pathenv_buffer), _TRUNCATE, "%s%s", pathenv, defpath_suffix);
#else
            snprintf(pathenv_buffer, sizeof(pathenv_buffer), "%s%s", pathenv, defpath_suffix);
#endif
            printf("Using semi-default location:\n%s\n", pathenv_buffer);
            pathenv = pathenv_buffer;
        }
    }
    strncpy(pathname, pathenv, sizeof(pathname));
#ifndef GMX_NATIVE_WINDOWS
    strcat(pathname, "/*.so");
    glob(pathname, 0, NULL, &globbuf);
    if (globbuf.gl_pathc == 0)
    {
        printf("\nNo VMD Plugins found\n"
               "Set the environment variable VMD_PLUGIN_PATH to the molfile folder within the\n"
               "VMD installation.\n"
               "The architecture (e.g. 32bit versus 64bit) of GROMACS and VMD has to match.\n");
        return 0;
    }
    for (size_t i = 0; i < globbuf.gl_pathc && vmdplugin->api == NULL; i++)
    {
        /* FIXME: Undefined which plugin is chosen if more than one plugin
           can read a certain file ending. Requires some additional command
           line option or enviroment variable to specify which plugin should
           be picked.
         */
        ret |= load_sharedlibrary_plugins(globbuf.gl_pathv[i], vmdplugin);
    }
    globfree(&globbuf);
#else
    strcat(pathname, "\\*.so");
    hFind = FindFirstFile(pathname, &ffd);
    if (INVALID_HANDLE_VALUE == hFind)
    {
        printf("\nNo VMD Plugins found\n");
        return 0;
    }
    do
    {
        char filename[GMX_PATH_MAX];
        sprintf(filename, "%s\\%s", pathenv, ffd.cFileName);
        ret |= load_sharedlibrary_plugins(filename, vmdplugin);
    }
    while (FindNextFile(hFind, &ffd )  != 0 && vmdplugin->api == NULL);
    FindClose(hFind);
#endif

    if (!ret)
    {
        printf("\nCould not open any VMD library.\n");
        err = vmddlerror();
        if (!err)
        {
            printf("Compiled with dlopen?\n");
        }
        else
        {
            printf("Last error:\n%s\n", err);
        }
        return 0;
    }

    if (vmdplugin->api == NULL)
    {
        printf("\nNo plugin for %s found\n", vmdplugin->filetype);
        return 0;
    }

    if (vmdplugin->api->abiversion < 10)
    {
        printf("\nPlugin and/or VMD is too old. At least VMD 1.8.6 is required.\n");
        return 0;
    }

    printf("\nUsing VMD plugin: %s (%s)\n", vmdplugin->api->name, vmdplugin->api->prettyname);

    return 1;

}
示例#11
0
bool GetSaveDumpName(DWORD dwProcessId, bool bFull, wchar_t* dmpfile, DWORD cchMaxDmpFile)
{
	bool bRc = false;

	HMODULE hCOMDLG32 = NULL;
	typedef BOOL (WINAPI* GetSaveFileName_t)(LPOPENFILENAMEW lpofn);
	GetSaveFileName_t _GetSaveFileName = NULL;

	if (!gpSrv->DbgInfo.bDebugProcessTree)
	{
		
		if (!hCOMDLG32)
			hCOMDLG32 = LoadLibraryW(L"COMDLG32.dll");
		if (hCOMDLG32 && !_GetSaveFileName)
			_GetSaveFileName = (GetSaveFileName_t)GetProcAddress(hCOMDLG32, "GetSaveFileNameW");

		if (_GetSaveFileName)
		{
			OPENFILENAMEW ofn; memset(&ofn,0,sizeof(ofn));
			ofn.lStructSize=sizeof(ofn);
			ofn.hwndOwner = NULL;
			ofn.lpstrFilter = L"Debug dumps (*.mdmp)\0*.mdmp;*.dmp\0Debug dumps (*.dmp)\0*.dmp;*.mdmp\0\0";
			ofn.nFilterIndex = bFull ? 2 : 1;
			ofn.lpstrFile = dmpfile;
			ofn.nMaxFile = cchMaxDmpFile;
			ofn.lpstrTitle = bFull ? L"Save debug full-dump" : L"Save debug mini-dump";
			ofn.lpstrDefExt = bFull ? L"dmp" : L"mdmp";
			ofn.Flags = OFN_ENABLESIZING|OFN_NOCHANGEDIR
			            | OFN_PATHMUSTEXIST|OFN_EXPLORER|OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT;

			if (_GetSaveFileName(&ofn))
			{
				bRc = true;
			}
		}

		if (hCOMDLG32)
		{
			FreeLibrary(hCOMDLG32);
		}
	}

	if (gpSrv->DbgInfo.bDebugProcessTree || !_GetSaveFileName)
	{
		HRESULT dwErr = SHGetFolderPath(NULL, CSIDL_DESKTOPDIRECTORY, NULL, 0/*SHGFP_TYPE_CURRENT*/, dmpfile);
		if (FAILED(dwErr))
		{
			memset(dmpfile, 0, cchMaxDmpFile*sizeof(*dmpfile));
			if (GetTempPath(cchMaxDmpFile-32, dmpfile) && *dmpfile)
				dwErr = S_OK;
		}

		if (FAILED(dwErr))
		{
			_printf("\nGetSaveDumpName called, get desktop folder failed, code=%u\n", (DWORD)dwErr);
		}
		else
		{
			if (*dmpfile && dmpfile[lstrlen(dmpfile)-1] != L'\\')
				_wcscat_c(dmpfile, cchMaxDmpFile, L"\\");
			
			_wcscat_c(dmpfile, cchMaxDmpFile, L"ConEmuTrap");
			CreateDirectory(dmpfile, NULL);

			INT_PTR nLen = lstrlen(dmpfile);
			_wsprintf(dmpfile+nLen, SKIPLEN(cchMaxDmpFile-nLen) L"\\Trap-%02u%02u%02u%s-%u.%s",
				MVV_1, MVV_2, MVV_3,_T(MVV_4a), dwProcessId,
				bFull ? L"dmp" : L"mdmp");

			bRc = true;
		}
	}

	return bRc;
}
bool MachineInstaller::ShouldSilentInstall()
{
	// Figure out the package name from our own EXE name 
	wchar_t ourFile[MAX_PATH];
	HMODULE hMod = GetModuleHandle(NULL);
	GetModuleFileName(hMod, ourFile, _countof(ourFile));

	CString fullPath = CString(ourFile);
	CString pkgName = CString(ourFile + fullPath.ReverseFind(L'\\'));
	pkgName.Replace(L".exe", L"");
	
	wchar_t installFolder[MAX_PATH];

	// C:\Users\Username\AppData\Local\$pkgName\packages
	SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, installFolder);
	wcscat(installFolder, L"\\");
	wcscat(installFolder, pkgName);
	wcscat(installFolder, L"\\");
	wcscat(installFolder, L"packages");

	if (GetFileAttributes(installFolder) != INVALID_FILE_ATTRIBUTES) {
		return false;
	}

	// C:\Users\Username\AppData\Local\$pkgName\.dead (was machine-installed but user uninstalled)
	SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, installFolder);
	wcscat(installFolder, L"\\");
	wcscat(installFolder, pkgName);
	wcscat(installFolder, L"\\");
	wcscat(installFolder, L".dead");

	if (GetFileAttributes(installFolder) != INVALID_FILE_ATTRIBUTES) {
		return false;
	}

	// C:\ProgramData\$pkgName\$username\packages
	wchar_t username[512];
	DWORD unamesize = _countof(username);
	SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, SHGFP_TYPE_CURRENT, installFolder);
	GetUserName(username, &unamesize);
	wcscat(installFolder, L"\\");
	wcscat(installFolder, pkgName);
	wcscat(installFolder, L"\\");
	wcscat(installFolder, username);
	wcscat(installFolder, L"\\");
	wcscat(installFolder, L"packages");

	if (GetFileAttributes(installFolder) != INVALID_FILE_ATTRIBUTES) {
		return false;
	}

	// C:\ProgramData\$pkgName\$username\.dead
	SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, SHGFP_TYPE_CURRENT, installFolder);
	wcscat(installFolder, L"\\");
	wcscat(installFolder, pkgName);
	wcscat(installFolder, L"\\");
	wcscat(installFolder, username);
	wcscat(installFolder, L"\\");
	wcscat(installFolder, L".dead");

	if (GetFileAttributes(installFolder) != INVALID_FILE_ATTRIBUTES) {
		return false;
	}

	// None of these exist, we should install
	return true;
}
示例#13
0
///
/// Determines where the BOINC data directory is.
///
void CBOINCGUIApp::DetectDataDirectory() {
#ifdef __WXMSW__
    //
    // Determine BOINCMgr Data Directory
    //
	LONG    lReturnValue;
	HKEY    hkSetupHive;
    LPTSTR  lpszRegistryValue = NULL;
    TCHAR   szPath[MAX_PATH];
	DWORD   dwSize = 0;

    // change the current directory to the boinc data directory if it exists
	lReturnValue = RegOpenKeyEx(
        HKEY_LOCAL_MACHINE, 
        _T("SOFTWARE\\Space Sciences Laboratory, U.C. Berkeley\\BOINC Setup"),
		0, 
        KEY_READ,
        &hkSetupHive
    );
    if (lReturnValue == ERROR_SUCCESS) {
        // How large does our buffer need to be?
        lReturnValue = RegQueryValueEx(
            hkSetupHive,
            _T("DATADIR"),
            NULL,
            NULL,
            NULL,
            &dwSize
        );
        if (lReturnValue != ERROR_FILE_NOT_FOUND) {
            // Allocate the buffer space.
            lpszRegistryValue = (LPTSTR) malloc(dwSize);
            (*lpszRegistryValue) = NULL;

            // Now get the data
            lReturnValue = RegQueryValueEx( 
                hkSetupHive,
                _T("DATADIR"),
                NULL,
                NULL,
                (LPBYTE)lpszRegistryValue,
                &dwSize
            );

            // Store the root directory for later use.
            m_strBOINCMGRDataDirectory = lpszRegistryValue;
        }
    } else {
        if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA|CSIDL_FLAG_CREATE, NULL, SHGFP_TYPE_CURRENT, szPath))) {
            _tcsncat(szPath, _T("\\boinc"), ((sizeof(szPath)/sizeof(TCHAR)) - _tcslen(szPath)));
            if (wxDir::Exists(szPath)) {
                // Store the root directory for later use.
                m_strBOINCMGRDataDirectory = szPath;
            }
        }
    }

    // Cleanup
	if (hkSetupHive) RegCloseKey(hkSetupHive);
    if (lpszRegistryValue) free(lpszRegistryValue);
#endif
#ifdef __WXMAC__
    m_strBOINCMGRDataDirectory = wxT("/Library/Application Support/BOINC Data");
#endif
}
示例#14
0
DWORD WINAPI CaptureThread(HANDLE hDllMainThread)
{
    bool bSuccess = false;

    //wait for dll initialization to finish before executing any initialization code
    if(hDllMainThread)
    {
        WaitForSingleObject(hDllMainThread, INFINITE);
        CloseHandle(hDllMainThread);
    }

    TCHAR lpLogPath[MAX_PATH];
    SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, SHGFP_TYPE_CURRENT, lpLogPath);
    wcscat_s(lpLogPath, MAX_PATH, TEXT("\\OBS\\pluginData\\captureHookLog.txt"));

    dummyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);

    if(!logOutput.is_open())
        logOutput.open(lpLogPath, ios_base::in | ios_base::out | ios_base::trunc, _SH_DENYNO);

    wstringstream str;
    str << OBS_KEEPALIVE_EVENT << UINT(GetCurrentProcessId());
    strKeepAlive = str.str();

    logOutput << CurrentDateTimeString() << "we're booting up: " << endl;

    InitializeCriticalSection(&d3d9EndMutex);
    InitializeCriticalSection(&glMutex);

    DWORD procID = GetCurrentProcessId();

    wstringstream strRestartEvent, strEndEvent, strReadyEvent, strExitEvent, strInfoMemory;
    strRestartEvent << RESTART_CAPTURE_EVENT << procID;
    strEndEvent     << END_CAPTURE_EVENT     << procID;
    strReadyEvent   << CAPTURE_READY_EVENT   << procID;
    strExitEvent    << APP_EXIT_EVENT        << procID;
    strInfoMemory   << INFO_MEMORY           << procID;

    hSignalRestart  = GetEvent(strRestartEvent.str().c_str());
    hSignalEnd      = GetEvent(strEndEvent.str().c_str());
    hSignalReady    = GetEvent(strReadyEvent.str().c_str());
    hSignalExit     = GetEvent(strExitEvent.str().c_str());

    DWORD bla;
    HANDLE hWindowThread = CreateThread(NULL, 0, DummyWindowThread, NULL, 0, &bla);
    if (!hWindowThread) {
        logOutput << CurrentTimeString() << "CaptureThread: could not create window thread for some reason" << endl;
        return 0;
    }

    CloseHandle(hWindowThread);

    hInfoFileMap = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(CaptureInfo), strInfoMemory.str().c_str());
    if(!hInfoFileMap)
    {
        logOutput << CurrentTimeString() << "CaptureThread: could not info file mapping" << endl;
        return 0;
    }

    infoMem = (CaptureInfo*)MapViewOfFile(hInfoFileMap, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(CaptureInfo));
    if(!infoMem)
    {
        logOutput << CurrentTimeString() << "CaptureThread: could not map view of info shared memory" << endl;
        CloseHandle(hInfoFileMap);
        hInfoFileMap = NULL;
        return 0;
    }

    hwndOBS = FindWindow(OBS_WINDOW_CLASS, NULL);
    if(!hwndOBS)
    {
        logOutput << CurrentTimeString() << "CaptureThread: could not find main application window?  wtf?  seriously?" << endl;
        return 0;
    }

    textureMutexes[0] = OpenMutex(MUTEX_ALL_ACCESS, FALSE, TEXTURE_MUTEX1);
    if (textureMutexes[0]) {
        textureMutexes[1] = OpenMutex(MUTEX_ALL_ACCESS, FALSE, TEXTURE_MUTEX2);
        if (textureMutexes[1]) {
            while(!AttemptToHookSomething())
                Sleep(50);

            logOutput << CurrentTimeString() << "(half life scientist) everything..  seems to be in order" << endl;

            while (1) {
                AttemptToHookSomething();
                Sleep(4000);
            }

            CloseHandle(textureMutexes[1]);
            textureMutexes[1] = NULL;
        } else {
            logOutput << CurrentTimeString() << "could not open texture mutex 2" << endl;
        }

        CloseHandle(textureMutexes[0]);
        textureMutexes[0] = NULL;
    } else {
        logOutput << CurrentTimeString() << "could not open texture mutex 1" << endl;
    }

    logOutput << CurrentTimeString() << "WARNING: exit out of the main thread loop somehow" << endl;

    return 0;
}
示例#15
0
CL_String CL_Directory::get_appdata(const CL_StringRef &company_name, const CL_StringRef &application_name, const CL_StringRef &version, bool create_dirs_if_missing)
{
#if defined(WIN32)
	TCHAR app_data[MAX_PATH];
	if (FAILED(SHGetFolderPath(0, CSIDL_APPDATA, 0, SHGFP_TYPE_DEFAULT, app_data)))
		throw CL_Exception("SHGetFolderPath failed!");
	CL_String configuration_path = cl_format("%1\\%2\\%3\\%4\\", app_data, company_name, application_name, version);
	if (create_dirs_if_missing)
	{
		CL_String::size_type prevPos = 0;
		while (true)
		{
			CL_String::size_type pos = configuration_path.find_first_of("\\/", prevPos);
			if (pos == CL_String::npos)
				break;

			CL_StringRef folder = configuration_path.substr(0, pos);
			CreateDirectory(CL_StringHelp::utf8_to_ucs2(folder).c_str(), 0);

			prevPos = pos + 1;
		}
	}
	return configuration_path;
#elif defined(__APPLE__)
	throw CL_Exception("Congratulations, you got the task to implement CL_Directory::get_appdata on this platform.");
#else
	const char *home_dir = getenv("HOME");
	if (home_dir == NULL)
		throw CL_Exception("Cannot object $HOME environment variable");

	if (!create_dirs_if_missing)
	{
		return cl_format("%1/.%2/%3/%4/", home_dir, company_name, application_name, version);
	}

	struct stat stFileInfo;
	CL_String name( cl_format("%1/.%2", home_dir, company_name) );

	if (stat(name.c_str(), &stFileInfo))
	{
		if (::mkdir(name.c_str(), 0755))
			throw CL_Exception(cl_format("Cannot create %1 directory", name));	
	}

	name = cl_format("%1/%2", name, application_name);
	if (stat(name.c_str(), &stFileInfo))
	{
		if (::mkdir(name.c_str(), 0755))
			throw CL_Exception(cl_format("Cannot create %1 directory", name));	
	}

	name = cl_format("%1/%2", name, version);
	if (stat(name.c_str(), &stFileInfo))
	{
		if (::mkdir(name.c_str(), 0755))
			throw CL_Exception(cl_format("Cannot create %1 directory", name));	
	}

	name = cl_format("%1/", name);
	return name;
#endif
}
示例#16
0
void initializeIt()
{
		char filename[512],*p;
		char	directory[1024] = "";
		char currentDir[MAX_PATH] = "";


		memset(filename, '\000', sizeof(filename));
		GetModuleFileName(NULL,filename,sizeof(filename));
		strcpy(currentDir, filename);
		char *pend;
		pend = strrchr(currentDir, '\\');
		if (pend) {
			*pend = '\000';
		}
		p = filename+lstrlen(filename);
		while (p >= filename && *p != '\\') p--;
		p++;

		char	logFile[1024] = "";
		memset(logFile, '\000', sizeof(logFile));
		strcpy(logFile, "edcast_foo");

		char tmpfile[MAX_PATH] = "";
		sprintf(tmpfile, "%s\\.tmp", currentDir);

		FILE *filep = fopen(tmpfile, "w");
		if (filep == 0) {
			char path[MAX_PATH] = "";

			SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, path);
			strcpy(currentDir, path);
		}
		else {
			fclose(filep);
		}
        LoadConfigs(currentDir, logFile);

		/************ Bad string!!!!!*************/
        //AfxWinInit(core_api::get_my_instance(), NULL, "", SW_HIDE);
		::AfxSetResourceHandle(core_api::get_my_instance());

        mainWindow = new CMainWindow();

        mainWindow->InitializeWindow();

        strcpy(mainWindow->m_currentDir, currentDir);

        //mainWindow->Create((UINT)IDD_EDCAST, mainApp.GetMainWnd());    
        //mainWindow->Create((UINT)IDD_EDCAST, CWnd::FromHandle(core_api::get_main_window()));    
		//::AfxGetMainWnd();
        mainWindow->Create((UINT)IDD_EDCAST, AfxGetMainWnd());
        int x = getLastX();
        int y = getLastY();
        if (x < 0) {
            x = 0;
        }
        if (y < 0) {
            y = 0;
        }

        mainWindow->SetWindowPos(NULL, x, y, -1, -1, SWP_NOSIZE | SWP_SHOWWINDOW);

        modeless_dialog_manager::g_add(mainWindow->m_hWnd);
        modeless_dialog_manager::g_add(mainWindow->configDialog->m_hWnd);   
        modeless_dialog_manager::g_add(mainWindow->editMetadata->m_hWnd);

        mainWindow->SetIcon(mainApp.LoadIcon(IDR_MAINFRAME), TRUE);
        mainWindow->ShowWindow(SW_HIDE);
        

        initializeedcast();
}
示例#17
0
VOID GetIniFilePath(TCHAR *inPath, const TCHAR *inINIFileName, const TCHAR *inAppName)
{
	TCHAR szFilePath[MAX_PATH_SIZE + 100];
	UINT nRet = 0;

	*szFilePath = '\0';

#if _MSC_VER < 1500
	if(GetVerifyVersionInfo(5, 0, 0))
	{
		HMODULE hDll;
		UINT  nLen;
		TCHAR *szPath;
		const TCHAR *szFile = _T("SHELL32.DLL");
#ifdef _UNICODE
		const char  *szFunc = "SHGetFolderPathW";
#else
		const char  *szFunc = "SHGetFolderPathA";
#endif

		nLen = GetSystemDirectory(0, 0);

		if(nLen < 1)
			goto FOUL;

		nLen  += (UINT)_tcslen(szFile) + 1;
		szPath = (TCHAR*)malloc(nLen * sizeof(TCHAR));

		if(szPath == NULL)
			goto FOUL;

		nRet = GetSystemDirectory(szPath, nLen);

		if(nRet < 0)
			goto FOUL;

		TCHAR *p = szPath + nRet;
		*(p++) = _T('\\');
		_tcscpy(p, szFile);

		hDll = LoadLibrary(szPath);
		if(hDll != NULL)
		{
			HRESULT (WINAPI *SHGetFolderPath)(HWND, int, HANDLE, DWORD, LPTSTR);
			SHGetFolderPath = reinterpret_cast<HRESULT(WINAPI*)(HWND, int, HANDLE, DWORD, LPTSTR)>(GetProcAddress(hDll, szFunc));

			if(SHGetFolderPath != NULL)
			{
#endif /* _MSC_VER < 1500 */
				HRESULT hRet;

				if(GetModuleFileName(NULL, inPath, MAX_PATH_SIZE + 100) != NULL)
				{
					hRet = SHGetFolderPath(NULL, CSIDL_PROGRAM_FILES, NULL, 0, szFilePath);

					if (SUCCEEDED(hRet))
					{
						TCHAR *p;

						//  Program File から実行されているか確認。
						p = _tcsstr(inPath, szFilePath);

						//  実行されていたら Appdata のパスにする。
						if(p != NULL)
						{
							hRet = SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, szFilePath);

							if(SUCCEEDED(hRet))
							{
								// inPath に Appdata のパスをコピーする。
								p = _qtcscpy(inPath, szFilePath);
								*(p++) = _T('\\');

								// inPath に inAppName のパスを追記する。
								p = _qtcscpy(p, inAppName);
								*(p++) = _T('\\');
								*p = _T('\0');

								// inAppName のフォルダーがない場合は作成する。
								if(!PathIsDirectory(inPath))
								{
									CreateDirectory(inPath, NULL);
								}

								// 最後に inINIFileName を追記してINIファイルのパスが完成。
								_tcscpy(p, inINIFileName);

								nRet = 1;
							}
						}
#if _MSC_VER < 1500
						else
						{
							nRet = 0;
						}
#endif /* _MSC_VER < 1500 */
					}
				}

#if _MSC_VER < 1500
			}
			FreeLibrary(hDll);
		}
FOUL:
		if(szPath)
			free(szPath);

	}
#endif /* _MSC_VER < 1500 */

	if(!nRet)
	{
		TCHAR *p;

		if(GetModuleFileName(NULL, szFilePath, MAX_PATH_SIZE + 100) != NULL)
		{
			PathRemoveFileSpec(szFilePath);
			p = _qtcscpy(inPath, szFilePath);
			*(p++) = _T('\\');
			_tcscpy(p, inINIFileName);
		}
	}

	return;
}
示例#18
0
/*
** Entry point
**
*/
int SkinInstallerMain(LPWSTR lpCmdLine)
{
	// Avoid loading a dll from current directory
	SetDllDirectory(L"");

	CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
	InitCommonControls();

	if (lpCmdLine[0] == L'"')
	{
		// Strip quotes
		++lpCmdLine;
		WCHAR* pos = wcsrchr(lpCmdLine, L'"');
		if (pos)
		{
			*pos = L'\0';
		}
	}

	WCHAR buffer[MAX_PATH];
	GetModuleFileName(GetInstanceHandle(), buffer, MAX_PATH);

	// Remove the module's name from the path
	WCHAR* pos = wcsrchr(buffer, L'\\');
	if (pos)
	{
		*(pos + 1) = L'\0';
	}

	g_Data.programPath = g_Data.settingsPath = buffer;
	wcscat(buffer, L"Rainmeter.ini");

	// Find the settings file and read skins path off it
	if (_waccess(buffer, 0) == 0)
	{
		g_Data.iniFile = buffer;
		if (GetPrivateProfileString(L"Rainmeter", L"SkinPath", L"", buffer, MAX_LINE_LENGTH, buffer) > 0)
		{
			g_Data.skinsPath = buffer;
			if (g_Data.skinsPath.back() != L'\\' && g_Data.skinsPath.back() != L'/')
			{
				g_Data.skinsPath += L'\\';
			}
		}
		else
		{
			g_Data.skinsPath = g_Data.programPath;
			g_Data.skinsPath += L"Skins\\";
		}
	}
	else
	{
		HRESULT hr = SHGetFolderPath(nullptr, CSIDL_APPDATA, nullptr, SHGFP_TYPE_CURRENT, buffer);
		wcscat(buffer, L"\\Rainmeter\\");
		g_Data.settingsPath = buffer;
		wcscat(buffer, L"Rainmeter.ini");
		g_Data.iniFile = buffer;
		if (SUCCEEDED(hr) && _waccess(buffer, 0) == 0)
		{
			if (GetPrivateProfileString(L"Rainmeter", L"SkinPath", L"", buffer, MAX_LINE_LENGTH, buffer) > 0)
			{
				g_Data.skinsPath = buffer;
				if (g_Data.skinsPath.back() != L'\\' && g_Data.skinsPath.back() != L'/')
				{
					g_Data.skinsPath += L'\\';
				}
			}
			else
			{
				std::wstring error = L"SkinPath not found.\nMake sure that Rainmeter has been run at least once.";
				MessageBox(nullptr, error.c_str(), L"Rainmeter Skin Installer", MB_ERROR);
				return 1;
			}
		}
		else
		{
			std::wstring error = L"Rainmeter.ini not found.\nMake sure that Rainmeter has been run at least once.";
			MessageBox(nullptr, error.c_str(), L"Rainmeter Skin Installer", MB_ERROR);
			return 1;
		}
	}

	std::wstring layoutsPath = g_Data.settingsPath + L"Layouts\\";
	if (_waccess(layoutsPath.c_str(), 0) == -1)
	{
		// Migrate Themes into Layouts for backwards compatibility and rename
		// Rainmeter.thm to Rainmeter.ini and RainThemes.bmp to Wallpaper.bmp.
		std::wstring themesPath = g_Data.settingsPath + L"Themes";
		if (_waccess(themesPath.c_str(), 0) != -1)
		{
			// Migrate Themes into Layouts for backwards compatibility and rename
			// Rainmeter.thm to Rainmeter.ini and RainThemes.bmp to Wallpaper.bmp.
			MoveFile(themesPath.c_str(), layoutsPath.c_str());

			layoutsPath += L'*';  // For FindFirstFile.
			WIN32_FIND_DATA fd;
			HANDLE hFind = FindFirstFile(layoutsPath.c_str(), &fd);
			layoutsPath.pop_back();  // Remove '*'.

			if (hFind != INVALID_HANDLE_VALUE)
			{
				do
				{
					if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY &&
						wcscmp(L".", fd.cFileName) != 0 &&
						wcscmp(L"..", fd.cFileName) != 0)
					{
						std::wstring layoutFolder = layoutsPath + fd.cFileName;
						layoutFolder += L'\\';

						std::wstring file = layoutFolder + L"Rainmeter.thm";
						if (_waccess(file.c_str(), 0) != -1)
						{
							std::wstring newFile = layoutFolder + L"Rainmeter.ini";
							MoveFile(file.c_str(), newFile.c_str());
						}

						file = layoutFolder + L"RainThemes.bmp";
						if (_waccess(file.c_str(), 0) != -1)
						{
							std::wstring newFile = layoutFolder + L"Wallpaper.bmp";
							MoveFile(file.c_str(), newFile.c_str());
						}
					}
				}
				while (FindNextFile(hFind, &fd));

				FindClose(hFind);
			}
		}
	}

	if (_wcsnicmp(lpCmdLine, L"/LoadTheme ", 11) == 0)
	{
		// For backwards compatibility.
		std::wstring args = L"!LoadLayout \"";
		args += &lpCmdLine[11];  // Skip "/LoadTheme ".
		args += L'"';

		std::wstring file = g_Data.programPath + L"Rainmeter.exe";
		SHELLEXECUTEINFO sei = {0};
		sei.cbSize = sizeof(SHELLEXECUTEINFO);
		sei.fMask = SEE_MASK_UNICODE;
		sei.lpFile = file.c_str();
		sei.lpParameters = args.c_str();
		sei.lpDirectory = g_Data.programPath.c_str();
		sei.nShow = SW_SHOWNORMAL;
		ShellExecuteEx(&sei);

		return 0;
	}
	else if (wcscmp(lpCmdLine, L"/Packager") == 0)
	{
		DialogPackage::Create(GetInstanceHandle(), lpCmdLine);
	}
	else
	{
		DialogInstall::Create(GetInstanceHandle(), lpCmdLine);
	}

	return 0;
}
static FT_Error GetFontByFaceName(const char *font_name, FT_Face *face)
{
	FT_Error err = FT_Err_Cannot_Open_Resource;
	HKEY hKey;
	LONG ret;
	TCHAR vbuffer[MAX_PATH], dbuffer[256];
	TCHAR *font_namep;
	char *font_path;
	uint index;

	/* On windows NT (2000, NT3.5, XP, etc.) the fonts are stored in the
	 * "Windows NT" key, on Windows 9x in the Windows key. To save us having
	 * to retrieve the windows version, we'll just query both */
	ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T(FONT_DIR_NT), 0, KEY_READ, &hKey);
	if (ret != ERROR_SUCCESS) ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T(FONT_DIR_9X), 0, KEY_READ, &hKey);

	if (ret != ERROR_SUCCESS) {
		DEBUG(freetype, 0, "Cannot open registry key HKLM\\SOFTWARE\\Microsoft\\Windows (NT)\\CurrentVersion\\Fonts");
		return err;
	}

	/* For Unicode we need some conversion between widechar and
	 * normal char to match the data returned by RegEnumValue,
	 * otherwise just use parameter */
#if defined(UNICODE)
	font_namep = MallocT<TCHAR>(MAX_PATH);
	MB_TO_WIDE_BUFFER(font_name, font_namep, MAX_PATH * sizeof(TCHAR));
#else
	font_namep = const_cast<char *>(font_name); // only cast because in unicode pointer is not const
#endif

	for (index = 0;; index++) {
		TCHAR *s;
		DWORD vbuflen = lengthof(vbuffer);
		DWORD dbuflen = lengthof(dbuffer);

		ret = RegEnumValue(hKey, index, vbuffer, &vbuflen, NULL, NULL, (byte*)dbuffer, &dbuflen);
		if (ret != ERROR_SUCCESS) goto registry_no_font_found;

		/* The font names in the registry are of the following 3 forms:
		 * - ADMUI3.fon
		 * - Book Antiqua Bold (TrueType)
		 * - Batang & BatangChe & Gungsuh & GungsuhChe (TrueType)
		 * We will strip the font-type '()' if any and work with the font name
		 * itself, which must match exactly; if...
		 * TTC files, font files which contain more than one font are seperated
		 * byt '&'. Our best bet will be to do substr match for the fontname
		 * and then let FreeType figure out which index to load */
		s = _tcschr(vbuffer, _T('('));
		if (s != NULL) s[-1] = '\0';

		if (_tcschr(vbuffer, _T('&')) == NULL) {
			if (_tcsicmp(vbuffer, font_namep) == 0) break;
		} else {
			if (_tcsstr(vbuffer, font_namep) != NULL) break;
		}
	}

	if (!SUCCEEDED(SHGetFolderPath(NULL, CSIDL_FONTS, NULL, SHGFP_TYPE_CURRENT, vbuffer))) {
		DEBUG(freetype, 0, "SHGetFolderPath cannot return fonts directory");
		goto folder_error;
	}

	/* Some fonts are contained in .ttc files, TrueType Collection fonts. These
	 * contain multiple fonts inside this single file. GetFontData however
	 * returns the whole file, so we need to check each font inside to get the
	 * proper font.
	 * Also note that FreeType does not support UNICODE filesnames! */
#if defined(UNICODE)
	/* We need a cast here back from wide because FreeType doesn't support
	 * widechar filenames. Just use the buffer we allocated before for the
	 * font_name search */
	font_path = (char*)font_namep;
	WIDE_TO_MB_BUFFER(vbuffer, font_path, MAX_PATH * sizeof(TCHAR));
#else
	font_path = vbuffer;
#endif

	ttd_strlcat(font_path, "\\", MAX_PATH * sizeof(TCHAR));
	ttd_strlcat(font_path, WIDE_TO_MB(dbuffer), MAX_PATH * sizeof(TCHAR));

	/* Convert the path into something that FreeType understands */
	font_path = GetShortPath(font_path);

	index = 0;
	do {
		err = FT_New_Face(_library, font_path, index, face);
		if (err != FT_Err_Ok) break;

		if (strncasecmp(font_name, (*face)->family_name, strlen((*face)->family_name)) == 0) break;
		/* Try english name if font name failed */
		if (strncasecmp(font_name + strlen(font_name) + 1, (*face)->family_name, strlen((*face)->family_name)) == 0) break;
		err = FT_Err_Cannot_Open_Resource;

	} while ((FT_Long)++index != (*face)->num_faces);


folder_error:
registry_no_font_found:
#if defined(UNICODE)
	free(font_namep);
#endif
	RegCloseKey(hKey);
	return err;
}
示例#20
0
// Run this at startup time. Please use GetSysDirectory if you need to query where folders are.
void InitSysDirectories() {
	if (!g_Config.memCardDirectory.empty() && !g_Config.flash0Directory.empty())
		return;

	const std::string path = ConvertWStringToUTF8(File::GetExeDirectory());

	// Mount a filesystem
	g_Config.flash0Directory = path + "/flash0/";

	// Detect the "My Documents"(XP) or "Documents"(on Vista/7/8) folder.
	wchar_t myDocumentsPath[MAX_PATH];
	const HRESULT result = SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, SHGFP_TYPE_CURRENT, myDocumentsPath);
	const std::string myDocsPath = ConvertWStringToUTF8(myDocumentsPath) + "/PPSSPP/";

	const std::string installedFile = path + "/installed.txt";
	const bool installed = File::Exists(installedFile);

	// If installed.txt exists(and we can determine the Documents directory)
	if (installed && (result == S_OK))	{
		std::ifstream inputFile(ConvertUTF8ToWString(installedFile));

		if (!inputFile.fail() && inputFile.is_open()) {
			std::string tempString;

			std::getline(inputFile, tempString);

			// Skip UTF-8 encoding bytes if there are any. There are 3 of them.
			if (tempString.substr(0, 3) == "\xEF\xBB\xBF")
				tempString = tempString.substr(3);

			g_Config.memCardDirectory = tempString;
		}
		inputFile.close();

		// Check if the file is empty first, before appending the slash.
		if (g_Config.memCardDirectory.empty())
			g_Config.memCardDirectory = myDocsPath;

		size_t lastSlash = g_Config.memCardDirectory.find_last_of("/");
		if (lastSlash != (g_Config.memCardDirectory.length() - 1))
			g_Config.memCardDirectory.append("/");
	} else {
		g_Config.memCardDirectory = path + "/memstick/";
	}

	// Create the memstickpath before trying to write to it, and fall back on Documents yet again
	// if we can't make it.
	if (!File::Exists(g_Config.memCardDirectory)) {
		if (!File::CreateDir(g_Config.memCardDirectory))
			g_Config.memCardDirectory = myDocsPath;
	}

	const std::string testFile = "/_writable_test.$$$";

	// If any directory is read-only, fall back to the Documents directory.
	// We're screwed anyway if we can't write to Documents, or can't detect it.
	if (!File::CreateEmptyFile(g_Config.memCardDirectory + testFile))
		g_Config.memCardDirectory = myDocsPath;

	// Clean up our mess.
	if (File::Exists(g_Config.memCardDirectory + testFile))
		File::Delete(g_Config.memCardDirectory + testFile);

	if (g_Config.currentDirectory.empty()) {
		g_Config.currentDirectory = GetSysDirectory(DIRECTORY_GAME);
	}
}
示例#21
0
void
strb_InitializeSdlFont(void)
{
  if (TTF_Init()) {
    rb_raise_sdl_ttf_error();
  }
  fontFileInfos = ALLOC(FontFileInfo);
  fontFileInfos->rbFontNameSymbol = Qundef;
  fontFileInfos->rbFileNameSymbol = Qundef;
  fontFileInfos->ttcIndex         = -1;
  fontFileInfos->next             = NULL;
  FontFileInfo* currentInfo = fontFileInfos;
  (void)currentInfo;

#ifdef WIN32
  HKEY hKey;
  TCHAR* regPath =
    _T("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts");
  if (SUCCEEDED(RegOpenKeyEx(HKEY_LOCAL_MACHINE, regPath, 0,
                             KEY_READ, &hKey))) {
    DWORD fontNameBuffMaxLength;
    DWORD fileNameBuffMaxByteLength;
    RegQueryInfoKey(hKey, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
                    &fontNameBuffMaxLength, &fileNameBuffMaxByteLength,
                    NULL, NULL);
    TCHAR fontNameBuff[fontNameBuffMaxLength + 1];
    BYTE fileNameByteBuff[fileNameBuffMaxByteLength];
    for (DWORD dwIndex = 0; ;dwIndex++) {
      ZeroMemory(fontNameBuff, sizeof(fontNameBuff));
      ZeroMemory(fileNameByteBuff, sizeof(fileNameByteBuff));
      DWORD fontNameBuffLength = sizeof(fontNameBuff) / sizeof(TCHAR);
      DWORD fileNameBuffByteLength = fileNameBuffMaxByteLength;
      LONG result = RegEnumValue(hKey, dwIndex,
                                 fontNameBuff, &fontNameBuffLength,
                                 NULL, NULL,
                                 fileNameByteBuff, &fileNameBuffByteLength);
      TCHAR* fileNameBuff = (TCHAR*)fileNameByteBuff;
      DWORD fileNameBuffLength = _tcslen(fileNameBuff);
      if (result == ERROR_SUCCESS) {
        const TCHAR* ext = &(fileNameBuff[fileNameBuffLength - 3]);
        if (tolower(ext[0]) == _T('t') &&
            tolower(ext[1]) == _T('t') &&
            (tolower(ext[2]) == _T('f') ||
             tolower(ext[2]) == _T('c'))) {
          TCHAR* fontName = fontNameBuff;
          const TCHAR* fileName = fileNameBuff;
          // A TTF font name must end with ' (TrueType)'.
          fontName[fontNameBuffLength - 11] = _T('\0');
          for (int i = fileNameBuffLength - 1; 0 <= i; i--) {
            if (fileName[i] == _T('\\')) {
              fileName += i + 1;
              break;
            }
          }
          int length =
            WideCharToMultiByte(CP_UTF8, 0,
                                fontName, -1,
                                NULL, 0,
                                NULL, NULL);
          char fontNameUTF8[length];
          WideCharToMultiByte(CP_UTF8, 0,
                              fontName, -1,
                              fontNameUTF8, length,
                              NULL, NULL);
          volatile VALUE rbFontName = rb_str_new2(fontNameUTF8);
          length =
            WideCharToMultiByte(CP_ACP, 0,
                                fileName, -1,
                                NULL, 0,
                                NULL, NULL);
          char fileNameANSI[length];
          WideCharToMultiByte(CP_ACP, 0,
                              fileName, -1,
                              fileNameANSI, length,
                              NULL, NULL);
          volatile VALUE rbFileName = rb_str_new2(fileNameANSI);
          if (strchr(StringValueCStr(rbFontName), '&')) {
            volatile VALUE rbArr = rb_str_split(rbFontName, "&");
            const int arrLength = RARRAY_LEN(rbArr);
            int ttcIndex = 0;
            for (int i = 0; i < arrLength; i++) {
              volatile VALUE rbFontName = rb_ary_entry(rbArr, i);
              rb_funcall(rbFontName, rb_intern("strip!"), 0);
              if (0 < RSTRING_LEN(rbFontName)) {
                volatile VALUE rbFontNameSymbol = rb_str_intern(rbFontName);
                volatile VALUE rbFileNameSymbol = rb_str_intern(rbFileName);
                ADD_INFO(currentInfo, rbFontNameSymbol, rbFileNameSymbol,
                         ttcIndex);
                ttcIndex++;
              }
            }
          } else {
            volatile VALUE rbFontNameSymbol = rb_str_intern(rbFontName);
            volatile VALUE rbFileNameSymbol = rb_str_intern(rbFileName);
            ADD_INFO(currentInfo, rbFontNameSymbol, rbFileNameSymbol, -1);
          }
        }
      } else {
        break;
      }
    }
    RegCloseKey(hKey);
  } else {
    rb_raise(strb_GetStarRubyErrorClass(),
             "Win32API error: %d", (int)GetLastError());
  }
  TCHAR szWindowsFontDirPath[MAX_PATH + 1];
  if (FAILED(SHGetFolderPath(NULL, CSIDL_FONTS, NULL,
                             SHGFP_TYPE_CURRENT,
                             szWindowsFontDirPath))) {
    rb_raise(strb_GetStarRubyErrorClass(),
             "Win32API error: %d", (int)GetLastError());
  }
  int length =
    WideCharToMultiByte(CP_UTF8, 0,
                        szWindowsFontDirPath, -1,
                        NULL, 0,
                        NULL, NULL);
  char szWindowsFontDirPathUTF8[length];
  WideCharToMultiByte(CP_UTF8, 0,
                      szWindowsFontDirPath, -1,
                      szWindowsFontDirPathUTF8, length,
                      NULL, NULL);
  volatile VALUE rbWindowsFontDirPath = rb_str_new2(szWindowsFontDirPathUTF8);
  rbWindowsFontDirPathSymbol = rb_str_intern(rbWindowsFontDirPath);
#endif
}
示例#22
0
文件: IoUser.c 项目: Akiyah/io
IoObject *IoUser_homeDirectory(IoUser *self, IoObject *locals, IoMessage *m)
{
	TCHAR homePath[MAX_PATH];
	SHGetFolderPath( NULL, CSIDL_APPDATA, NULL, 0, homePath );
	return IoDirectory_newWithPath_(IOSTATE, IOSYMBOL(homePath));
}
示例#23
0
/** Gets current user's application save directory (without trailing separator)
 * @param[in] _zSubPath                     Sub-path to append to the application save directory, orxNULL for none
 * @return Current user's application save directory, use it immediately or copy it as it will be modified by the next call to orxFile_GetHomeDirectory() or orxFile_GetApplicationSaveDirectory()
 */
const orxSTRING orxFASTCALL orxFile_GetApplicationSaveDirectory(const orxSTRING _zSubPath)
{
  orxS32 s32Index = -1;
  const orxSTRING zResult = orxSTRING_EMPTY;

  /* Checks */
  orxASSERT((sstFile.u32Flags & orxFILE_KU32_STATIC_FLAG_READY) == orxFILE_KU32_STATIC_FLAG_READY);

#if defined(__orxWINDOWS__)

  {
    char acPath[MAX_PATH];

    /* Gets application folder */
    if(SUCCEEDED(SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, acPath)))
    {
      /* For all characters */
      for(s32Index = 0; s32Index < MAX_PATH; s32Index++)
      {
        /* Copies it + replace windows separators by linux ones */
        sstFile.acWorkDirectory[s32Index] = (acPath[s32Index] != orxCHAR_DIRECTORY_SEPARATOR_WINDOWS) ? acPath[s32Index] : orxCHAR_DIRECTORY_SEPARATOR_LINUX;

        /* End of string? */
        if(acPath[s32Index] == orxCHAR_NULL)
        {
          /* Stops */
          break;
        }
      }
    }
  }

#elif defined(__orxLINUX__) || defined(__orxMAC__) || defined(__orxRASPBERRY_PI__)

  {
    const orxCHAR *zHome;

    /* Gets environment HOME variable */
    zHome = (orxCHAR *)getenv("HOME");

    /* Valid? */
    if(zHome != orxNULL)
    {
      /* Prints home directory */
      s32Index = orxString_NPrint(sstFile.acWorkDirectory, sizeof(sstFile.acWorkDirectory) - 1, "%s%c%s", zHome, orxCHAR_DIRECTORY_SEPARATOR_LINUX, orxFILE_KZ_APPLICATION_FOLDER);
    }
    else
    {
      struct passwd *pstPasswd;

      /* Gets current user's passwd */
      pstPasswd = getpwuid(getuid());

      /* Valid? */
      if(pstPasswd != orxNULL)
      {
        /* Prints home directory */
        s32Index = orxString_NPrint(sstFile.acWorkDirectory, sizeof(sstFile.acWorkDirectory) - 1, "%s%c%s", pstPasswd->pw_dir, orxCHAR_DIRECTORY_SEPARATOR_LINUX, orxFILE_KZ_APPLICATION_FOLDER);
      }
    }
  }

#elif defined(__orxIOS__)

  /* Prints documents directory */
  s32Index = orxString_NPrint(sstFile.acWorkDirectory, sizeof(sstFile.acWorkDirectory) - 1, "%s", orxiOS_GetDocumentsPath());

#elif defined(__orxANDROID__) || defined(__orxANDROID_NATIVE__)

  /* Prints internal storage directory */
  s32Index = orxString_NPrint(sstFile.acWorkDirectory, sizeof(sstFile.acWorkDirectory) - 1, "%s", orxAndroid_GetInternalStoragePath());

#endif

  /* Success? */
  if(s32Index >= 0)
  {
    /* Should add sub-path? */
    if(_zSubPath != orxNULL)
    {
      /* Appends folder name */
      s32Index += orxString_NPrint(sstFile.acWorkDirectory + s32Index, sizeof(sstFile.acWorkDirectory) - s32Index - 1, "%c%s", orxCHAR_DIRECTORY_SEPARATOR_LINUX, _zSubPath);
    }

    /* Updates result */
    zResult = sstFile.acWorkDirectory;
  }

  /* Done! */
  return zResult;
}
///////////
// Collect
void FontsCollectorThread::Collect() {
    // Make sure there is a separator at the end
    destination += _T("\\");

    // Reset log box
    wxTextCtrl *LogBox = collector->LogBox;
    wxMutexGuiEnter();
    LogBox->SetValue(_T(""));
    LogBox->SetDefaultStyle(wxTextAttr(wxColour(0,0,180)));
    LogBox->AppendText(_("Searching for fonts in file...\n"));
    LogBox->SetDefaultStyle(wxTextAttr(wxColour(0,0,0)));
    LogBox->Refresh();
    LogBox->Update();
    wxSafeYield();
    wxMutexGuiLeave();

    // Scans file
    AssStyle *curStyle;
    AssDialogue *curDiag;
    curLine = 0;
    for (std::list<AssEntry*>::iterator cur=subs->Line.begin(); cur!=subs->Line.end(); cur++) {
        // Collect from style
        curStyle = AssEntry::GetAsStyle(*cur);
        if (curStyle) {
            AddFont(curStyle->font,true);
            wxMutexGuiEnter();
            LogBox->AppendText(wxString(_T("\"")) + curStyle->font + _("\" found on style \"") + curStyle->name + _T("\".\n"));
            LogBox->Refresh();
            LogBox->Update();
            wxSafeYield();
            wxMutexGuiLeave();
        }

        // Collect from dialogue
        else {
            curDiag = AssEntry::GetAsDialogue(*cur);
            if (curDiag) {
                curLine++;
                curDiag->ParseASSTags();
                curDiag->ProcessParameters(GetFonts);
                curDiag->ClearBlocks();
            }
        }
    }

#ifdef __WIN32__
    // Collect font data
    wxMutexGuiEnter();
    LogBox->SetDefaultStyle(wxTextAttr(wxColour(0,0,180)));
    LogBox->AppendText(_("\nReading fonts from registry...\n"));
    LogBox->SetDefaultStyle(wxTextAttr(wxColour(0,0,0)));
    wxSafeYield();
    wxMutexGuiLeave();
    CollectFontData();

    // Get fonts folder
    wxString source;
    TCHAR szPath[MAX_PATH];
    if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_FONTS,NULL,0,szPath))) {
        source = wxString(szPath);
    }
    else source = wxGetOSDirectory() + _T("\\fonts");
    source += _T("\\");

    // Get font file names
    wxArrayString work;
    wxArrayString copied;
    for (size_t i=0; i<fonts.GetCount(); i++) {
        try {
            work = GetFontFiles(fonts[i]);
            for (size_t j=0; j<work.GetCount(); j++) {
                // Get path to font file
                wxString srcFile,dstFile;
                wxFileName srcFileName(work[j]);
                if (srcFileName.FileExists() && srcFileName.IsAbsolute()) {
                    srcFile = work[j];
                    dstFile = destination + srcFileName.GetFullName();
                }
                else {
                    srcFile = source + work[j];
                    dstFile = destination + work[j];
                }

                if (copied.Index(work[j]) == wxNOT_FOUND) {
                    copied.Add(work[j]);

                    // Check if it exists
                    if (wxFileName::FileExists(dstFile)) {
                        wxMutexGuiEnter();
                        LogBox->SetDefaultStyle(wxTextAttr(wxColour(255,128,0)));
                        LogBox->AppendText(wxString(_T("\"")) + work[j] + _("\" already exists on destination.\n"));
                        LogBox->Refresh();
                        LogBox->Update();
                        wxSafeYield();
                        wxMutexGuiLeave();
                    }

                    // Copy
                    else {
                        // Copy font
                        bool success = Copy(srcFile,dstFile);

                        // Report
                        wxMutexGuiEnter();
                        if (success) {
                            LogBox->SetDefaultStyle(wxTextAttr(wxColour(0,180,0)));
                            LogBox->AppendText(wxString(_T("\"")) + work[j] + _("\" copied.\n"));

                        }
                        else {
                            LogBox->SetDefaultStyle(wxTextAttr(wxColour(220,0,0)));
                            LogBox->AppendText(wxString(_("Failed copying \"")) + srcFile + _T("\".\n"));
                        }
                        LogBox->Refresh();
                        LogBox->Update();
                        wxSafeYield();
                        wxMutexGuiLeave();
                    }
                }
            }
        }

        catch (...) {
            wxMutexGuiEnter();
            LogBox->SetDefaultStyle(wxTextAttr(wxColour(220,0,0)));
            LogBox->AppendText(wxString(_("Could not find font ")) + fonts[i] + _T("\n"));
            wxMutexGuiLeave();
        }
    }
#endif
}
/**
 * @brief Adds the directories in the colon separated string to the datadir handler.
 */
void DataDirLocater::AddDirs(const std::string& in)
{
	size_t prev_colon = 0, colon;
#ifndef _WIN32
	while ((colon = in.find(':', prev_colon)) != std::string::npos) {
#else
	while ((colon = in.find(';', prev_colon)) != std::string::npos) {
#endif
		datadirs.push_back(in.substr(prev_colon, colon - prev_colon));
#ifdef DEBUG
		logOutput.Print("Adding %s to directories" , in.substr(prev_colon, colon - prev_colon).c_str());
#endif
		prev_colon = colon + 1;
	}
#ifdef DEBUG
	logOutput.Print("Adding %s to directories" , in.substr(prev_colon).c_str());
#endif
	datadirs.push_back(in.substr(prev_colon));
}

/**
 * @brief Figure out permissions we have for a single data directory d.
 * @returns whether we have permissions to read the data directory.
 */
bool DataDirLocater::DeterminePermissions(DataDir* d)
{
#ifndef _WIN32
	if (d->path.c_str()[0] != '/' || d->path.find("..") != std::string::npos)
#else
	if (d->path.find("..") != std::string::npos)
#endif
		throw content_error("specify data directories using absolute paths please");
	// Figure out whether we have read/write permissions
	// First check read access, if we got that check write access too
	// (no support for write-only directories)
	// Note: we check for executable bit otherwise we can't browse the directory
	// Note: we fail to test whether the path actually is a directory
	// Note: modifying permissions while or after this function runs has undefined behaviour
#ifndef _WIN32
	if (access(d->path.c_str(), R_OK | X_OK | F_OK) == 0) {
		// Note: disallow multiple write directories.
		// There isn't really a use for it as every thing is written to the first one anyway,
		// and it may give funny effects on errors, e.g. it probably only gives funny things
		// like network mounted datadir lost connection and suddenly files end up in some
		// other random writedir you didn't even remember you had added it.
		if (!writedir && access(d->path.c_str(), W_OK) == 0) {
#else
	if (_access(d->path.c_str(), 4) == 0) {
		if (!writedir && _access(d->path.c_str(), 2) == 0) {
#endif
			d->writable = true;
			writedir = &*d;
		}
		return true;
	} else {
		if (filesystem.CreateDirectory(d->path)) {
			// it didn't exist before, now it does and we just created it with rw access,
			// so we just assume we still have read-write acces...
			if (!writedir) {
				d->writable = true;
				writedir = d;
			}
			return true;
		}
	}
	return false;
}

/**
 * @brief Figure out permissions we have for the data directories.
 */
void DataDirLocater::DeterminePermissions()
{
	std::vector<DataDir> newDatadirs;
	std::string previous; // used to filter out consecutive duplicates
	// (I didn't bother filtering out non-consecutive duplicates because then
	//  there is the question which of the multiple instances to purge.)

	writedir = NULL;

	for (std::vector<DataDir>::iterator d = datadirs.begin(); d != datadirs.end(); ++d) {
		if (d->path != previous && DeterminePermissions(&*d)) {
			newDatadirs.push_back(*d);
			previous = d->path;
		}
	}

	datadirs = newDatadirs;
}

/**
 * @brief locate spring data directory
 *
 * On *nix platforms, attempts to locate
 * and change to the spring data directory
 *
 * In Unixes, the data directory to chdir to is determined by the following, in this
 * order (first items override lower items):
 *
 * - 'SPRING_DATADIR' environment variable. (colon separated list, like PATH)
 * - 'SpringData=/path/to/data' declaration in '~/.springrc'. (colon separated list)
 * - "$HOME/.spring"
 * - In the same order any line in '/etc/spring/datadir', if that file exists.
 * - 'datadir=/path/to/data' option passed to 'scons configure'.
 * - 'prefix=/install/path' option passed to scons configure. The datadir is
 *   assumed to be at '$prefix/games/spring' in this case.
 * - the default datadirs in the default prefix, ie. '/usr/local/games/spring'
 *   (This is set by the build system, ie. SPRING_DATADIR and SPRING_DATADIR_2
 *   preprocessor definitions.)
 *
 * In Windows, its:
 * - SPRING_DATADIR env-variable
 * - user configurable (SpringData in registry)
 * - location of the binary dir (like it has been until 0.76b1)
 * - the Users 'Documents'-directory (in subdirectory Spring), unless spring is configured to use another
 * - all users app-data (in subdirectory Spring)
 * - compiler flags SPRING_DATADIR and SPRING_DATADIR_2
 *
 * All of the above methods support environment variable substitution, eg.
 * '$HOME/myspringdatadir' will be converted by spring to something like
 * '/home/username/myspringdatadir'.
 *
 * If it fails to chdir to the above specified directory spring will asume the
 * current working directory is the data directory.
 */
void DataDirLocater::LocateDataDirs()
{
	// Construct the list of datadirs from various sources.
	datadirs.clear();

	// environment variable
	char* env = getenv("SPRING_DATADIR");
	if (env && *env)
		AddDirs(SubstEnvVars(env));

	// user defined (in spring config handler (Linux: ~/.springrc, Windows: registry))
	std::string userDef = configHandler.GetString("SpringData", "");
	if (!userDef.empty()) {
		AddDirs(SubstEnvVars(userDef));
	}

#ifdef WIN32
	TCHAR currentDir[MAX_PATH];
	::GetCurrentDirectory(sizeof(currentDir) - 1, currentDir);
	std::string curPath = currentDir;
	AddDirs(std::string(currentDir));

	// my documents
	TCHAR strPath[MAX_PATH];
	SHGetFolderPath( NULL, CSIDL_PERSONAL, NULL, SHGFP_TYPE_CURRENT, strPath);
	std::string cfg = strPath;
	cfg += "\\Spring"; // e.g. F:\Dokumente und Einstellungen\Karl-Robert\Eigene Dateien\Spring
	AddDirs(cfg);
	cfg.clear();

	// appdata
	SHGetFolderPath( NULL, CSIDL_COMMON_APPDATA, NULL, SHGFP_TYPE_CURRENT, strPath);
	cfg = strPath;
	cfg += "\\Spring"; // e.g. F:\Dokumente und Einstellungen\All Users\Anwendungsdaten\Spring
	AddDirs(cfg);
#elif defined(__APPLE__)
	// copied from old MacFileSystemHandler, won't compile here, but would not compile in its old location either
	// needs fixing for new DataDirLocater-structure
	// Get the path to the application bundle we are running:
	char cPath[1024];
	CFBundleRef mainBundle = CFBundleGetMainBundle();
	if(!mainBundle)
		throw content_error("Could not determine bundle path");

	CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle);
	if(!mainBundleURL)
		throw content_error("Could not determine bundle path");

	CFStringRef cfStringRef = CFURLCopyFileSystemPath(mainBundleURL, kCFURLPOSIXPathStyle);
	if(!cfStringRef)
		throw content_error("Could not determine bundle path");

	CFStringGetCString(cfStringRef, cPath, 1024, kCFStringEncodingASCII);

	CFRelease(mainBundleURL);
	CFRelease(cfStringRef);
	std::string path(cPath);
	
	datadirs.clear();
	writedir = NULL;
	
	// Add bundle resources:
	datadirs.push_back(path + "/Contents/Resources/");
	datadirs.rbegin()->readable = true;
	// Add the directory surrounding the bundle, for users to add mods and maps in:
	datadirs.push_back(filesystem.GetDirectory(path));
	// Use surrounding directory as writedir for now, should propably
	// change this to something inside the home directory:
	datadirs.rbegin()->writable = true;
	datadirs.rbegin()->readable = true;
	writedir = &*datadirs.rbegin();
#else
	// home
	AddDirs(SubstEnvVars("$HOME/.spring"));

	// settings in /etc
	FILE* f = ::fopen("/etc/spring/datadir", "r");
	if (f) {
		char buf[1024];
		while (fgets(buf, sizeof(buf), f)) {
			char* newl = strchr(buf, '\n');
			if (newl)
				*newl = 0;
			char white[3] = {'\t', ' ', 0};
			if (strlen(buf) > 0 && strspn(buf, white) != strlen(buf)) // don't count lines of whitespaces / tabulators
				AddDirs(SubstEnvVars(buf));
		}
		fclose(f);
	}
#endif

	// compiler flags
#ifdef SPRING_DATADIR
	datadirs.push_back(SubstEnvVars(SPRING_DATADIR));
#endif
	// should not be needed because you can seperate directories with a ':' in SPRING_DATADIR(1)
#ifdef SPRING_DATADIR_2
	datadirs.push_back(SubstEnvVars(SPRING_DATADIR_2));
#endif

	// Figure out permissions of all datadirs
	DeterminePermissions();

	if (!writedir) {
		// bail out
#ifdef WIN32
		const std::string errstr = "Not a single writable data directory found!\n\n"
				"Configure a writable data directory using either:\n"
				"- the SPRING_DATADIR environment variable,\n"
				"- a SpringData=C:/path/to/data declaration in spring's registry entry or\n"
				"- by giving you write access to the installation directory";
#else
		const std::string errstr = "Not a single writable data directory found!\n\n"
				"Configure a writable data directory using either:\n"
				"- the SPRING_DATADIR environment variable,\n"
				"- a SpringData=/path/to/data declaration in ~/.springrc or\n"
				"- the configuration file /etc/spring/datadir";
#endif
		throw content_error(errstr);
	}

	// for now, chdir to the datadirectory as a safety measure:
	// all AIs still just assume it's ok to put their stuff in the current directory after all
	// Not only safety anymore, it's just easier if other code can safely assume that
	// writedir == current working directory
#ifndef _WIN32
	chdir(GetWriteDir()->path.c_str());
#else
	_chdir(GetWriteDir()->path.c_str());
#endif
	// Initialize the log. Only after this moment log will be written to file.
	logOutput.Initialize();
	// Logging MAY NOT start before the chdir, otherwise the logfile ends up
	// in the wrong directory.
	// Update: now it actually may start before, log has preInitLog.
	for (std::vector<DataDir>::const_iterator d = datadirs.begin(); d != datadirs.end(); ++d) {
		if (d->writable)
			logOutput.Print("Using read-write data directory: %s", d->path.c_str());
		else
			logOutput.Print("Using read-only  data directory: %s", d->path.c_str());
	}
}
示例#26
0
String Get(Key key) {
    switch(key) {

      case FILE_EXE:
          {
#if SIRIKATA_PLATFORM == SIRIKATA_PLATFORM_MAC
              // Executable path can have relative references ("..") depending on
              // how the app was launched.
              uint32_t executable_length = 0;
              _NSGetExecutablePath(NULL, &executable_length);
              std::string executable_path(executable_length, '\0');
              char* executable_path_c = (char*)executable_path.c_str();
              int rv = _NSGetExecutablePath(executable_path_c, &executable_length);
              assert(rv == 0);
              if ((rv != 0) || (executable_path.empty()))
                  return "";
              // _NSGetExecutablePath will return whatever gets execed, so if
              // the command line is ./foo, you'll get the '.'. We use the
              // aggressive mode here to handle '..' parts that could interfere
              // with finding other paths that start from FILE_EXE.
              return canonicalize(executable_path, true);
#elif SIRIKATA_PLATFORM == SIRIKATA_PLATFORM_LINUX
              // boost::filesystem can't chase symlinks, do it manually
              const char* selfExe = "/proc/self/exe";

              char bin_dir[MAX_PATH + 1];
              int bin_dir_size = readlink(selfExe, bin_dir, MAX_PATH);
              if (bin_dir_size < 0 || bin_dir_size > MAX_PATH) {
                  SILOG(core,fatal,"Couldn't read self symlink to setup dynamic loading paths.");
                  return "";
              }
              bin_dir[bin_dir_size] = 0;
              return String(bin_dir, bin_dir_size);
#elif SIRIKATA_PLATFORM == SIRIKATA_PLATFORM_WINDOWS
              char system_buffer[MAX_PATH];
              system_buffer[0] = 0;
              GetModuleFileName(NULL, system_buffer, MAX_PATH);
              // Go through boost::filesystem to canonicalize our formatting.
              // If we don't, we can get \ or / in filenames depending on where
              // they came from/whether we went through boost::filesystem
              String exe_file(system_buffer);
              if (exe_file.empty()) return "";
              boost::filesystem::path exe_file_path(exe_file);
              return exe_file_path.string();
#else
              return "";
#endif
          }
          break;

      case DIR_EXE:
          {
              String exe_file = Get(FILE_EXE);
              if (exe_file.empty()) return "";
              boost::filesystem::path exe_file_path(exe_file);
              return exe_file_path.parent_path().string();
          }
          break;

      case DIR_EXE_BUNDLE:
          {
#if SIRIKATA_PLATFORM == SIRIKATA_PLATFORM_WINDOWS || SIRIKATA_PLATFORM == SIRIKATA_PLATFORM_LINUX
              // Windows and Linux don't have bundles
              return Get(DIR_EXE);
#elif SIRIKATA_PLATFORM == SIRIKATA_PLATFORM_MAC
              // On mac we need to detect that we're in a .app. We assume this
              // only applies if the binaries are in the standard location,
              // i.e. foo.app/Contents/MacOS/bar_binary
              String exe_dir = Get(DIR_EXE);
              boost::filesystem::path exe_dir_path(exe_dir);
              // Work our way back up verifying the path names, finally
              // returning if we actually find the .app.
              if (exe_dir_path.has_filename() && exe_dir_path.filename() == "MacOS") {
                  exe_dir_path = exe_dir_path.parent_path();
                  if (exe_dir_path.has_filename() && exe_dir_path.filename() == "Contents") {
                      exe_dir_path = exe_dir_path.parent_path();
                      if (exe_dir_path.has_filename()) {
                          String app_dir_name = exe_dir_path.filename();
                          if (app_dir_name.substr(app_dir_name.size()-4, 4) == ".app")
                              return exe_dir_path.parent_path().string();
                      }
                  }
              }
              // Otherwise dump the original
              return exe_dir;
#endif
          }
          break;

      case DIR_CURRENT:
          {
#if SIRIKATA_PLATFORM == SIRIKATA_PLATFORM_MAC || SIRIKATA_PLATFORM == SIRIKATA_PLATFORM_LINUX
              char system_buffer[MAX_PATH] = "";
              if (!getcwd(system_buffer, sizeof(system_buffer))) {
                  return "";
              }

              return String(system_buffer);
#elif SIRIKATA_PLATFORM == SIRIKATA_PLATFORM_WINDOWS
              char system_buffer[MAX_PATH];
              system_buffer[0] = 0;
              DWORD len = ::GetCurrentDirectory(MAX_PATH, system_buffer);
              if (len == 0 || len > MAX_PATH)
                  return "";
              return String(system_buffer);
#else
              return ".";
#endif
          }
          break;

      case DIR_USER:
          {
#if SIRIKATA_PLATFORM == SIRIKATA_PLATFORM_LINUX || SIRIKATA_PLATFORM == SIRIKATA_PLATFORM_MAC
              uid_t uid = getuid();
              passwd* pw = getpwuid(uid);
              if (pw != NULL && pw->pw_dir != NULL) {
                  boost::filesystem::path homedir(pw->pw_dir);
                  if (boost::filesystem::exists(homedir) && boost::filesystem::is_directory(homedir))
                      return homedir.string();
              }
#elif SIRIKATA_PLATFORM == SIRIKATA_PLATFORM_WINDOWS
              char system_buffer[MAX_PATH];
              system_buffer[0] = 0;
              if (FAILED(SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, 0, system_buffer)))
                  return "";
              std::string appdata_str(system_buffer);
              boost::filesystem::path user_appdata(appdata_str);
              user_appdata /= "Sirikata";
              if (!boost::filesystem::exists(user_appdata))
                  boost::filesystem::create_directory(user_appdata);
              if (boost::filesystem::exists(user_appdata) && boost::filesystem::is_directory(user_appdata))
                  return user_appdata.string();
#endif
              // Last resort (and default for unknown platform) is to try to use
              // the current directory
              return ".";
          }
          break;

      case DIR_USER_HIDDEN:
          {
#if SIRIKATA_PLATFORM == SIRIKATA_PLATFORM_WINDOWS
              // On windows there's no difference from the user-specific data directory since that's already hidden.
              return Get(DIR_USER);
#else
              // We just compute this as an offset from the user directory
              boost::filesystem::path user_dir(Get(DIR_USER));
              user_dir /= ".sirikata";
              if (!boost::filesystem::exists(user_dir))
                  boost::filesystem::create_directory(user_dir);
              if (boost::filesystem::exists(user_dir) && boost::filesystem::is_directory(user_dir))
                  return user_dir.string();
#endif
              return ".";
          }

      case DIR_TEMP:
          {
#if SIRIKATA_PLATFORM == SIRIKATA_PLATFORM_LINUX || SIRIKATA_PLATFORM == SIRIKATA_PLATFORM_MAC
              // On Mac and Linux we try to work under tmp using our own directory
              boost::filesystem::path tmp_path("/tmp");
              if (boost::filesystem::exists(tmp_path) && boost::filesystem::is_directory(tmp_path)) {
                  tmp_path /= "sirikata";
                  // If it doesn't exist, try creating it
                  if (!boost::filesystem::exists(tmp_path))
                      boost::filesystem::create_directory(tmp_path);
                  if (boost::filesystem::exists(tmp_path) && boost::filesystem::is_directory(tmp_path))
                      return tmp_path.string();
              }
#elif SIRIKATA_PLATFORM == SIRIKATA_PLATFORM_WINDOWS
              // Windows doesn't seem to suggest a good location for this, so we
              // put it under the app data directory in its own temp directory
              boost::filesystem::path sirikata_temp_dir =
                  boost::filesystem::path(Get(DIR_USER_HIDDEN)) / "temp";
              if (!boost::filesystem::exists(sirikata_temp_dir))
                  boost::filesystem::create_directory(sirikata_temp_dir);
              if (boost::filesystem::exists(sirikata_temp_dir) && boost::filesystem::is_directory(sirikata_temp_dir))
                  return sirikata_temp_dir.string();
#endif
              // Last resort (and default for unknown platform) is to try to use
              // the current directory
              return ".";
          }
          break;

      case DIR_SYSTEM_CONFIG:
          {
#if SIRIKATA_PLATFORM == SIRIKATA_PLATFORM_LINUX || SIRIKATA_PLATFORM == SIRIKATA_PLATFORM_MAC
              // This is sirikata specific, so we're looking for more
              // than just /etc.
              if (boost::filesystem::exists("/etc") && boost::filesystem::is_directory("/etc") &&
                  boost::filesystem::exists("/etc/sirikata") && boost::filesystem::is_directory("/etc/sirikata"))
                  return "/etc/sirikata";
              return "";
#else
              // Other platforms don't have an equivalent?
              return "";
#endif
          }
          break;

      case RESOURCE:
          {
              SILOG(core,fatal,"Can't request RESOURCE without specifiying an in-tree path and path to resource.");
              assert(key != RESOURCE);
              return "";
          }
          break;

      default:
        return "";
    }
}
示例#27
0
void DataDirLocater::LocateDataDirs()
{
    // Prepare the data-dirs defined in different places

    // environment variable
    std::string dd_env = "";
    {
        char* env = getenv("SPRING_DATADIR");
        if (env && *env) {
            dd_env = SubstEnvVars(env);
        }
    }

#if       defined(UNITSYNC)
    const std::string dd_curWorkDir = Platform::GetModulePath();
#else  // defined(UNITSYNC)
    const std::string dd_curWorkDir = Platform::GetProcessExecutablePath();
#endif // defined(UNITSYNC)

    // This is useful in case of multiple engine/unitsync versions installed
    // together in a sub-dir of the data-dir
    // The data-dir structure then might look similar to this:
    // maps/
    // games/
    // engines/engine-0.83.0.0.exe
    // engines/engine-0.83.1.0.exe
    // unitsyncs/unitsync-0.83.0.0.exe
    // unitsyncs/unitsync-0.83.1.0.exe
    const std::string dd_curWorkDirParent = FileSystemHandler::GetParent(dd_curWorkDir);

#if    defined(WIN32)
    // fetch my documents path
    TCHAR pathMyDocs[MAX_PATH];
    SHGetFolderPath( NULL, CSIDL_PERSONAL, NULL, SHGFP_TYPE_CURRENT, pathMyDocs);

    // fetch app-data path
    TCHAR pathAppData[MAX_PATH];
    SHGetFolderPath( NULL, CSIDL_COMMON_APPDATA, NULL, SHGFP_TYPE_CURRENT, pathAppData);

    std::string dd_myDocs = pathMyDocs;
    // e.g. F:\Dokumente und Einstellungen\Karl-Robert\Eigene Dateien\Spring
    dd_myDocs += "\\Spring";

    std::string dd_myDocsMyGames = pathMyDocs;
    // My Documents\My Games seems to be the MS standard even if no official guidelines exist
    // most if not all new Games For Windows(TM) games use this dir
    dd_myDocsMyGames += "\\My Games\\Spring";

    std::string dd_appData = pathAppData;
    // e.g. F:\Dokumente und Einstellungen\All Users\Anwendungsdaten\Spring
    dd_appData += "\\Spring";
#elif     defined(MACOSX_BUNDLE)
    const std::string dd_curWorkDirData = dd_curWorkDir + "/" + SubstEnvVars(DATADIR);
    const std::string dd_curWorkDirLib  = dd_curWorkDir + "/" + SubstEnvVars(LIBDIR);
#else // *nix (-OSX)
    // settings in /etc
    std::string dd_etc = "";
    {
        FILE* fileH = ::fopen("/etc/spring/datadir", "r");
        if (fileH) {
            const char whiteSpaces[3] = {'\t', ' ', '\0'};
            char lineBuf[1024];
            while (fgets(lineBuf, sizeof(lineBuf), fileH)) {
                char* newLineCharPos = strchr(lineBuf, '\n');
                if (newLineCharPos) {
                    // remove the new line char
                    *newLineCharPos = '\0';
                }
                // ignore lines consisting of only whitespaces
                if ((strlen(lineBuf) > 0) && strspn(lineBuf, whiteSpaces) != strlen(lineBuf)) {
                    // append, separated by sPD (depending on OS): ';' or ':'
                    dd_etc = dd_etc + (dd_etc.empty() ? "" : sPD) + SubstEnvVars(lineBuf);
                }
            }
            fclose(fileH);
        }
    }
#endif // defined(WIN32), defined(MACOSX_BUNDLE), else

    // Construct the list of datadirs from various sources.
    datadirs.clear();
    // The first dir added will be the writeable data dir.

    // same on all platforms
    AddDirs(dd_env);    // ENV{SPRING_DATADIR}
    // user defined in spring config handler
    // (Linux: ~/.springrc, Windows: .\springsettings.cfg)
    AddDirs(SubstEnvVars(configHandler->GetString("SpringData", "")));

#ifdef WIN32
    // All MS Windows variants

    if ((dd_curWorkDirParent != "") && LooksLikeMultiVersionDataDir(dd_curWorkDirParent)) {
        AddDirs(dd_curWorkDirParent); // "../"
    } else if (IsPortableMode()) { // we can not add both ./ and ../ as data-dir
        AddDirs(dd_curWorkDir); // "./"
    }
    AddDirs(dd_myDocsMyGames);  // "C:/.../My Documents/My Games/Spring/"
    AddDirs(dd_myDocs);         // "C:/.../My Documents/Spring/"
    AddDirs(dd_appData);        // "C:/.../All Users/Applications/Spring/"

#elif defined(MACOSX_BUNDLE)
    // Mac OS X

    // Maps and mods are supposed to be located in spring's executable location on Mac, but unitsync
    // cannot find them since it does not know spring binary path. I have no idea but to force users
    // to locate lobby executables in the same as spring's dir and add its location to search dirs.
#ifdef UNITSYNC
    AddDirs(dd_curWorkDir);     // "./"
#endif

    // libs and data are supposed to be located in subdirectories of spring executable, so they
    // sould be added instead of SPRING_DATADIR definition.
    AddDirs(dd_curWorkDirData); // "./data/"
    AddDirs(dd_curWorkDirLib);  // "./lib/"

#else
    // Linux, FreeBSD, Solaris, Apple non-bundle

    if ((dd_curWorkDirParent != "") && LooksLikeMultiVersionDataDir(dd_curWorkDirParent)) {
        AddDirs(dd_curWorkDirParent); // "../"
    } else if (IsPortableMode()) { // we can not add both ./ and ../ as data-dir
        // always using this would be unclean, because spring and unitsync
        // would end up with different sets of data-dirs
        AddDirs(dd_curWorkDir); // "./"
    }
    AddDirs(SubstEnvVars("$HOME/.spring")); // "~/.spring/"
    AddDirs(dd_etc);            // from /etc/spring/datadir
#endif

#ifdef SPRING_DATADIR
    AddDirs(SubstEnvVars(SPRING_DATADIR)); // from -DSPRING_DATADIR
#endif

    // Figure out permissions of all datadirs
    DeterminePermissions();

    if (!writedir) {
        // bail out
        const std::string errstr = "Not a single writable data directory found!\n\n"
                                   "Configure a writable data directory using either:\n"
                                   "- the SPRING_DATADIR environment variable,\n"
#ifdef WIN32
                                   "- a SpringData=C:/path/to/data declaration in spring's config file ./springsettings.cfg\n"
                                   "- by giving you write access to the installation directory";
#else
                                   "- a SpringData=/path/to/data declaration in ~/.springrc or\n"
                                   "- the configuration file /etc/spring/datadir";
#endif
        throw content_error(errstr);
    }

    // for now, chdir to the data directory as a safety measure:
    // Not only safety anymore, it's just easier if other code can safely assume that
    // writedir == current working directory
    FileSystemHandler::GetInstance().Chdir(GetWriteDir()->path.c_str());

    // Initialize the log. Only after this moment log will be written to file.
    logOutput.Initialize();
    // Logging MAY NOT start before the chdir, otherwise the logfile ends up
    // in the wrong directory.
    // Update: now it actually may start before, log has preInitLog.
    for (std::vector<DataDir>::const_iterator d = datadirs.begin(); d != datadirs.end(); ++d) {
        if (d->writable) {
            logOutput.Print("Using read-write data directory: %s", d->path.c_str());

            // tag the cache dir
            const std::string cacheDir = d->path + "cache";
            if (filesystem.CreateDirectory(cacheDir)) {
                CacheDir::SetCacheDir(cacheDir, true);
            }
        } else {
            logOutput.Print("Using read-only data directory: %s",  d->path.c_str());
        }
    }
}
BOOL CSetSavedDataPage::OnInitDialog()
{
	ISettingsPropPage::OnInitDialog();

	// find out how many log messages and URLs we've stored
	int nLogHistWC = 0;
	INT_PTR nLogHistMsg = 0;
	int nUrlHistWC = 0;
	INT_PTR nUrlHistItems = 0;
	int nLogHistRepo = 0;
	CRegistryKey regloghist(_T("Software\\TortoiseGit\\History"));
	CStringList loghistlist;
	regloghist.getSubKeys(loghistlist);
	for (POSITION pos = loghistlist.GetHeadPosition(); pos != NULL; )
	{
		CString sHistName = loghistlist.GetNext(pos);
		if (sHistName.Left(6).CompareNoCase(_T("commit")) == 0 || sHistName.Left(5).CompareNoCase(_T("merge")) == 0)
		{
			nLogHistWC++;
			CRegistryKey regloghistwc(_T("Software\\TortoiseGit\\History\\")+sHistName);
			CStringList loghistlistwc;
			regloghistwc.getValues(loghistlistwc);
			nLogHistMsg += loghistlistwc.GetCount();
		}
		else
		{
			// repoURLs
			CStringList urlhistlistmain;
			CStringList urlhistlistmainvalues;
			CRegistryKey regurlhistlist(_T("Software\\TortoiseGit\\History\\repoURLS"));
			regurlhistlist.getSubKeys(urlhistlistmain);
			regurlhistlist.getValues(urlhistlistmainvalues);
			nUrlHistItems += urlhistlistmainvalues.GetCount();
			for (POSITION urlpos = urlhistlistmain.GetHeadPosition(); urlpos != NULL; )
			{
				CString sWCUID = urlhistlistmain.GetNext(urlpos);
				nUrlHistWC++;
				CStringList urlhistlistwc;
				CRegistryKey regurlhistlistwc(_T("Software\\TortoiseGit\\History\\repoURLS\\")+sWCUID);
				regurlhistlistwc.getValues(urlhistlistwc);
				nUrlHistItems += urlhistlistwc.GetCount();
			}
		}
	}

	// find out how many dialog sizes / positions we've stored
	INT_PTR nResizableDialogs = 0;
	CRegistryKey regResizable(_T("Software\\TortoiseGit\\TortoiseProc\\ResizableState"));
	CStringList resizablelist;
	regResizable.getValues(resizablelist);
	nResizableDialogs += resizablelist.GetCount();

	// find out how many auth data we've stored
	int nSimple = 0;
	int nSSL = 0;
	int nUsername = 0;

	CString sFile;
	bool bIsDir = false;

	TCHAR pathbuf[MAX_PATH] = {0};
	if (SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, SHGFP_TYPE_CURRENT, pathbuf)==S_OK)
	{
		_tcscat_s(pathbuf, MAX_PATH, _T("\\Subversion\\auth\\"));
		CString sSimple = CString(pathbuf) + _T("svn.simple");
		CString sSSL = CString(pathbuf) + _T("svn.ssl.server");
		CString sUsername = CString(pathbuf) + _T("svn.username");
		CDirFileEnum simpleenum(sSimple);
		while (simpleenum.NextFile(sFile, &bIsDir))
			nSimple++;
		CDirFileEnum sslenum(sSSL);
		while (sslenum.NextFile(sFile, &bIsDir))
			nSSL++;
		CDirFileEnum userenum(sUsername);
		while (userenum.NextFile(sFile, &bIsDir))
			nUsername++;
	}

	CDirFileEnum logenum(CPathUtils::GetAppDataDirectory()+_T("logcache"));
	while (logenum.NextFile(sFile, &bIsDir))
		nLogHistRepo++;
	// the "Repositories.dat" is not a cache file
	nLogHistRepo--;

	BOOL bActionLog = PathFileExists(CPathUtils::GetAppDataDirectory() + _T("logfile.txt"));

	m_btnLogHistClear.EnableWindow(nLogHistMsg || nLogHistWC);
	m_btnUrlHistClear.EnableWindow(nUrlHistItems || nUrlHistWC);
	m_btnResizableHistClear.EnableWindow(nResizableDialogs > 0);
	m_btnAuthHistClear.EnableWindow(nSimple || nSSL || nUsername);
	m_btnRepoLogClear.EnableWindow(nLogHistRepo >= 0);
	m_btnActionLogClear.EnableWindow(bActionLog);
	m_btnActionLogShow.EnableWindow(bActionLog);

	EnableToolTips();

	m_tooltips.Create(this);
	CString sTT;
	sTT.Format(IDS_SETTINGS_SAVEDDATA_LOGHIST_TT, nLogHistMsg, nLogHistWC);
	m_tooltips.AddTool(IDC_LOGHISTORY, sTT);
	m_tooltips.AddTool(IDC_LOGHISTCLEAR, sTT);
	sTT.Format(IDS_SETTINGS_SAVEDDATA_URLHIST_TT, nUrlHistItems, nUrlHistWC);
	m_tooltips.AddTool(IDC_URLHISTORY, sTT);
	m_tooltips.AddTool(IDC_URLHISTCLEAR, sTT);
	sTT.Format(IDS_SETTINGS_SAVEDDATA_RESIZABLE_TT, nResizableDialogs);
	m_tooltips.AddTool(IDC_RESIZABLEHISTORY, sTT);
	m_tooltips.AddTool(IDC_RESIZABLEHISTCLEAR, sTT);
	sTT.Format(IDS_SETTINGS_SAVEDDATA_AUTH_TT, nSimple, nSSL, nUsername);
	m_tooltips.AddTool(IDC_AUTHHISTORY, sTT);
	m_tooltips.AddTool(IDC_AUTHHISTCLEAR, sTT);
	sTT.Format(IDS_SETTINGS_SAVEDDATA_REPOLOGHIST_TT, nLogHistRepo);
	m_tooltips.AddTool(IDC_REPOLOG, sTT);
	m_tooltips.AddTool(IDC_REPOLOGCLEAR, sTT);
	sTT.LoadString(IDS_SETTINGS_SHOWACTIONLOG_TT);
	m_tooltips.AddTool(IDC_ACTIONLOGSHOW, sTT);
	sTT.LoadString(IDS_SETTINGS_MAXACTIONLOGLINES_TT);
	m_tooltips.AddTool(IDC_MAXLINES, sTT);
	sTT.LoadString(IDS_SETTINGS_CLEARACTIONLOG_TT);
	m_tooltips.AddTool(IDC_ACTIONLOGCLEAR, sTT);

	return TRUE;
}
示例#29
0
// Returns a string with a Dolphin data dir or file in the user's home
// directory. To be used in "multi-user" mode (that is, installed).
const std::string& GetUserPath(const unsigned int DirIDX, const std::string &newPath)
{
	static std::string paths[NUM_PATH_INDICES];

	// Set up all paths and files on the first run
	if (paths[D_USER_IDX].empty())
	{
#ifdef _WIN32
		// Detect where the User directory is. There are five different cases (on top of the
		// command line flag, which overrides all this):
		// 1. GetExeDirectory()\portable.txt exists
		//    -> Use GetExeDirectory()\User
		// 2. HKCU\Software\Dolphin Emulator\LocalUserConfig exists and is true
		//    -> Use GetExeDirectory()\User
		// 3. HKCU\Software\Dolphin Emulator\UserConfigPath exists
		//    -> Use this as the user directory path
		// 4. My Documents exists
		//    -> Use My Documents\Dolphin Emulator as the User directory path
		// 5. Default
		//    -> Use GetExeDirectory()\User

		// Check our registry keys
		HKEY hkey;
		DWORD local = 0;
		TCHAR configPath[MAX_PATH] = {0};
		if (RegOpenKeyEx(HKEY_CURRENT_USER, TEXT("Software\\Dolphin Emulator"), NULL, KEY_QUERY_VALUE, &hkey) == ERROR_SUCCESS)
		{
			DWORD size = 4;
			if (RegQueryValueEx(hkey, TEXT("LocalUserConfig"), NULL, NULL, reinterpret_cast<LPBYTE>(&local), &size) != ERROR_SUCCESS)
				local = 0;

			size = MAX_PATH;
			if (RegQueryValueEx(hkey, TEXT("UserConfigPath"), NULL, NULL, (LPBYTE)configPath, &size) != ERROR_SUCCESS)
				configPath[0] = 0;
			RegCloseKey(hkey);
		}

		local = local || File::Exists(GetExeDirectory() + DIR_SEP "portable.txt");

		// Get Program Files path in case we need it.
		TCHAR my_documents[MAX_PATH];
		bool my_documents_found = SUCCEEDED(SHGetFolderPath(NULL, CSIDL_MYDOCUMENTS, NULL, SHGFP_TYPE_CURRENT, my_documents));

		if (local) // Case 1-2
			paths[D_USER_IDX] = GetExeDirectory() + DIR_SEP USERDATA_DIR DIR_SEP;
		else if (configPath[0]) // Case 3
			paths[D_USER_IDX] = TStrToUTF8(configPath);
		else if (my_documents_found) // Case 4
			paths[D_USER_IDX] = TStrToUTF8(my_documents) + DIR_SEP "Dolphin Emulator" DIR_SEP;
		else // Case 5
			paths[D_USER_IDX] = GetExeDirectory() + DIR_SEP USERDATA_DIR DIR_SEP;

		// Prettify the path: it will be displayed in some places, we don't want a mix of \ and /.
		paths[D_USER_IDX] = ReplaceAll(paths[D_USER_IDX], "\\", DIR_SEP);

		// Make sure it ends in DIR_SEP.
		if (*paths[D_USER_IDX].rbegin() != DIR_SEP_CHR)
			paths[D_USER_IDX] += DIR_SEP;
#else
		if (File::Exists(ROOT_DIR DIR_SEP USERDATA_DIR))
			paths[D_USER_IDX] = ROOT_DIR DIR_SEP USERDATA_DIR DIR_SEP;
		else
			paths[D_USER_IDX] = std::string(getenv("HOME") ?
				getenv("HOME") : getenv("PWD") ?
				getenv("PWD") : "") + DIR_SEP DOLPHIN_DATA_DIR DIR_SEP;
#endif

		paths[D_GCUSER_IDX]			= paths[D_USER_IDX] + GC_USER_DIR DIR_SEP;
		paths[D_WIIROOT_IDX]		= paths[D_USER_IDX] + WII_USER_DIR;
		paths[D_WIIUSER_IDX]		= paths[D_WIIROOT_IDX] + DIR_SEP;
		paths[D_CONFIG_IDX]			= paths[D_USER_IDX] + CONFIG_DIR DIR_SEP;
		paths[D_GAMESETTINGS_IDX]	= paths[D_USER_IDX] + GAMESETTINGS_DIR DIR_SEP;
		paths[D_MAPS_IDX]			= paths[D_USER_IDX] + MAPS_DIR DIR_SEP;
		paths[D_CACHE_IDX]			= paths[D_USER_IDX] + CACHE_DIR DIR_SEP;
		paths[D_SHADERCACHE_IDX]	= paths[D_USER_IDX] + SHADERCACHE_DIR DIR_SEP;
		paths[D_SHADERS_IDX]		= paths[D_USER_IDX] + SHADERS_DIR DIR_SEP;
		paths[D_STATESAVES_IDX]		= paths[D_USER_IDX] + STATESAVES_DIR DIR_SEP;
		paths[D_SCREENSHOTS_IDX]	= paths[D_USER_IDX] + SCREENSHOTS_DIR DIR_SEP;
		paths[D_HIRESTEXTURES_IDX]	= paths[D_USER_IDX] + HIRES_TEXTURES_DIR DIR_SEP;
		paths[D_DUMP_IDX]			= paths[D_USER_IDX] + DUMP_DIR DIR_SEP;
		paths[D_DUMPFRAMES_IDX]		= paths[D_DUMP_IDX] + DUMP_FRAMES_DIR DIR_SEP;
		paths[D_DUMPAUDIO_IDX]		= paths[D_DUMP_IDX] + DUMP_AUDIO_DIR DIR_SEP;
		paths[D_DUMPTEXTURES_IDX]	= paths[D_DUMP_IDX] + DUMP_TEXTURES_DIR DIR_SEP;
		paths[D_DUMPDSP_IDX]		= paths[D_DUMP_IDX] + DUMP_DSP_DIR DIR_SEP;
		paths[D_LOGS_IDX]			= paths[D_USER_IDX] + LOGS_DIR DIR_SEP;
		paths[D_MAILLOGS_IDX]		= paths[D_LOGS_IDX] + MAIL_LOGS_DIR DIR_SEP;
		paths[D_WIISYSCONF_IDX]		= paths[D_WIIUSER_IDX] + WII_SYSCONF_DIR DIR_SEP;
		paths[D_WIIWC24_IDX]		= paths[D_WIIUSER_IDX] + WII_WC24CONF_DIR DIR_SEP;
		paths[D_THEMES_IDX]			= paths[D_USER_IDX] + THEMES_DIR DIR_SEP;
		paths[F_DOLPHINCONFIG_IDX]	= paths[D_CONFIG_IDX] + DOLPHIN_CONFIG;
		paths[F_DEBUGGERCONFIG_IDX]	= paths[D_CONFIG_IDX] + DEBUGGER_CONFIG;
		paths[F_LOGGERCONFIG_IDX]	= paths[D_CONFIG_IDX] + LOGGER_CONFIG;
		paths[F_MAINLOG_IDX]		= paths[D_LOGS_IDX] + MAIN_LOG;
		paths[F_WIISYSCONF_IDX]		= paths[D_WIISYSCONF_IDX] + WII_SYSCONF;
		paths[F_RAMDUMP_IDX]		= paths[D_DUMP_IDX] + RAM_DUMP;
		paths[F_ARAMDUMP_IDX]		= paths[D_DUMP_IDX] + ARAM_DUMP;
		paths[F_FAKEVMEMDUMP_IDX]	= paths[D_DUMP_IDX] + FAKEVMEM_DUMP;
		paths[F_GCSRAM_IDX]			= paths[D_GCUSER_IDX] + GC_SRAM;
	}

	if (!newPath.empty())
	{
		if (!File::IsDirectory(newPath))
		{
			WARN_LOG(COMMON, "Invalid path specified %s", newPath.c_str());
			return paths[DirIDX];
		}
		else
		{
			paths[DirIDX] = newPath;
		}

		switch (DirIDX)
		{
		case D_WIIROOT_IDX:
			paths[D_WIIUSER_IDX] = paths[D_WIIROOT_IDX] + DIR_SEP;
			paths[D_WIISYSCONF_IDX]	= paths[D_WIIUSER_IDX] + WII_SYSCONF_DIR + DIR_SEP;
			paths[F_WIISYSCONF_IDX]	= paths[D_WIISYSCONF_IDX] + WII_SYSCONF;
			break;

		case D_USER_IDX:
			paths[D_GCUSER_IDX]				= paths[D_USER_IDX] + GC_USER_DIR DIR_SEP;
			paths[D_WIIROOT_IDX]			= paths[D_USER_IDX] + WII_USER_DIR;
			paths[D_WIIUSER_IDX]			= paths[D_WIIROOT_IDX] + DIR_SEP;
			paths[D_CONFIG_IDX]				= paths[D_USER_IDX] + CONFIG_DIR DIR_SEP;
			paths[D_GAMESETTINGS_IDX]		= paths[D_USER_IDX] + GAMESETTINGS_DIR DIR_SEP;
			paths[D_MAPS_IDX]				= paths[D_USER_IDX] + MAPS_DIR DIR_SEP;
			paths[D_CACHE_IDX]				= paths[D_USER_IDX] + CACHE_DIR DIR_SEP;
			paths[D_SHADERCACHE_IDX]		= paths[D_USER_IDX] + SHADERCACHE_DIR DIR_SEP;
			paths[D_SHADERS_IDX]			= paths[D_USER_IDX] + SHADERS_DIR DIR_SEP;
			paths[D_STATESAVES_IDX]			= paths[D_USER_IDX] + STATESAVES_DIR DIR_SEP;
			paths[D_SCREENSHOTS_IDX]		= paths[D_USER_IDX] + SCREENSHOTS_DIR DIR_SEP;
			paths[D_HIRESTEXTURES_IDX]		= paths[D_USER_IDX] + HIRES_TEXTURES_DIR DIR_SEP;
			paths[D_DUMP_IDX]				= paths[D_USER_IDX] + DUMP_DIR DIR_SEP;
			paths[D_DUMPFRAMES_IDX]			= paths[D_DUMP_IDX] + DUMP_FRAMES_DIR DIR_SEP;
			paths[D_DUMPAUDIO_IDX]			= paths[D_DUMP_IDX] + DUMP_AUDIO_DIR DIR_SEP;
			paths[D_DUMPTEXTURES_IDX]		= paths[D_DUMP_IDX] + DUMP_TEXTURES_DIR DIR_SEP;
			paths[D_DUMPDSP_IDX]			= paths[D_DUMP_IDX] + DUMP_DSP_DIR DIR_SEP;
			paths[D_LOGS_IDX]				= paths[D_USER_IDX] + LOGS_DIR DIR_SEP;
			paths[D_MAILLOGS_IDX]			= paths[D_LOGS_IDX] + MAIL_LOGS_DIR DIR_SEP;
			paths[D_WIISYSCONF_IDX]			= paths[D_WIIUSER_IDX] + WII_SYSCONF_DIR DIR_SEP;
			paths[D_THEMES_IDX]				= paths[D_USER_IDX] + THEMES_DIR DIR_SEP;
			paths[F_DOLPHINCONFIG_IDX]		= paths[D_CONFIG_IDX] + DOLPHIN_CONFIG;
			paths[F_DEBUGGERCONFIG_IDX]		= paths[D_CONFIG_IDX] + DEBUGGER_CONFIG;
			paths[F_LOGGERCONFIG_IDX]		= paths[D_CONFIG_IDX] + LOGGER_CONFIG;
			paths[F_MAINLOG_IDX]			= paths[D_LOGS_IDX] + MAIN_LOG;
			paths[F_WIISYSCONF_IDX]			= paths[D_WIISYSCONF_IDX] + WII_SYSCONF;
			paths[F_RAMDUMP_IDX]			= paths[D_DUMP_IDX] + RAM_DUMP;
			paths[F_ARAMDUMP_IDX]			= paths[D_DUMP_IDX] + ARAM_DUMP;
			paths[F_FAKEVMEMDUMP_IDX]		= paths[D_DUMP_IDX] + FAKEVMEM_DUMP;
			paths[F_GCSRAM_IDX]				= paths[D_GCUSER_IDX] + GC_SRAM;
			break;

		case D_CONFIG_IDX:
			paths[F_DOLPHINCONFIG_IDX]	= paths[D_CONFIG_IDX] + DOLPHIN_CONFIG;
			paths[F_DEBUGGERCONFIG_IDX]	= paths[D_CONFIG_IDX] + DEBUGGER_CONFIG;
			paths[F_LOGGERCONFIG_IDX]	= paths[D_CONFIG_IDX] + LOGGER_CONFIG;
			break;

		case D_GCUSER_IDX:
			paths[F_GCSRAM_IDX]			= paths[D_GCUSER_IDX] + GC_SRAM;
			break;

		case D_DUMP_IDX:
			paths[D_DUMPFRAMES_IDX]		= paths[D_DUMP_IDX] + DUMP_FRAMES_DIR DIR_SEP;
			paths[D_DUMPAUDIO_IDX]		= paths[D_DUMP_IDX] + DUMP_AUDIO_DIR DIR_SEP;
			paths[D_DUMPTEXTURES_IDX]	= paths[D_DUMP_IDX] + DUMP_TEXTURES_DIR DIR_SEP;
			paths[D_DUMPDSP_IDX]		= paths[D_DUMP_IDX] + DUMP_DSP_DIR DIR_SEP;
			paths[F_RAMDUMP_IDX]		= paths[D_DUMP_IDX] + RAM_DUMP;
			paths[F_ARAMDUMP_IDX]		= paths[D_DUMP_IDX] + ARAM_DUMP;
			paths[F_FAKEVMEMDUMP_IDX]	= paths[D_DUMP_IDX] + FAKEVMEM_DUMP;
			break;
		case D_LOGS_IDX:
			paths[D_MAILLOGS_IDX]		= paths[D_LOGS_IDX] + MAIL_LOGS_DIR DIR_SEP;
			paths[F_MAINLOG_IDX]		= paths[D_LOGS_IDX] + MAIN_LOG;
		}

		paths[D_WIIUSER_IDX] = paths[D_WIIROOT_IDX] + DIR_SEP;
		paths[D_WIIWC24_IDX] = paths[D_WIIUSER_IDX] + WII_WC24CONF_DIR DIR_SEP;
		paths[D_WIISYSCONF_IDX]	= paths[D_WIIUSER_IDX] + WII_SYSCONF_DIR + DIR_SEP;
		paths[F_WIISYSCONF_IDX]	= paths[D_WIISYSCONF_IDX] + WII_SYSCONF;
	}

	return paths[DirIDX];
}
示例#30
0
文件: Ntop.cpp 项目: bemehow/ntopng
Ntop::Ntop(char *appName) {
  globals = new NtopGlobals();
  pa = new PeriodicActivities();
  address = new AddressResolution();
  categorization = NULL;
  httpbl = NULL;
  custom_ndpi_protos = NULL;
  prefs = NULL, redis = NULL;
  num_defined_interfaces = 0;
  local_interface_addresses = New_Patricia(128);
  export_interface = NULL;
  historical_interface_id = -1;
  start_time = 0; /* It will be initialized by start() */
  memset(iface, 0, sizeof(iface));
  httpd = NULL, runtimeprefs = NULL, geo = NULL;
#ifdef WIN32
  if(SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL,
		     SHGFP_TYPE_CURRENT, working_dir) != S_OK) {
    strcpy(working_dir, "C:\\Windows\\Temp" /* "\\ntopng" */); // Fallback: it should never happen
  }

  // Get the full path and filename of this program
  if(GetModuleFileName(NULL, startup_dir, sizeof(startup_dir)) == 0) {
    startup_dir[0] = '\0';
  } else {
    for(int i=(int)strlen(startup_dir)-1; i>0; i--)
      if(startup_dir[i] == '\\') {
	startup_dir[i] = '\0';
	break;
      }
  }

  dirs[0] = startup_dir;
  strcpy(install_dir, startup_dir);
#else
  snprintf(working_dir, sizeof(working_dir), "%s/ntopng", CONST_DEFAULT_WRITABLE_DIR);

  umask (0);
  mkdir(working_dir, 0777);

  if(getcwd(startup_dir, sizeof(startup_dir)) == NULL)
    ntop->getTrace()->traceEvent(TRACE_ERROR, "Occurred while checking the current directory (errno=%d)", errno);

  dirs[0] = startup_dir;

  install_dir[0] = '\0';

  for(int i=0; dirs[i] != NULL; i++) {
    char path[MAX_PATH];
    struct stat statbuf;

    snprintf(path, sizeof(path), "%s/scripts/lua/index.lua", dirs[i]);
    fixPath(path);

    if(stat(path, &statbuf) == 0) {
      strcpy(install_dir, dirs[i]);
      break;
    }
  }
#endif

  // printf("--> %s [%s]\n", startup_dir, appName);

  initTimezone();
}