示例#1
0
void __cdecl IssueTransferThread(void *param)
{
	THeaderIPC *pipch = (THeaderIPC *)param;
	HANDLE hMainThread = HANDLE(pipch->Param);

	char szBuf[MAX_PATH];
	GetCurrentDirectoryA(sizeof(szBuf), szBuf);

	TAddArgList args;
	args.count = 0;
	args.files = NULL;
	TSlotIPC *pct = pipch->DataPtr;
	BOOL bQuit = false;
	while (pct != NULL) {
		if (pct->cbSize != sizeof(TSlotIPC)) 
			break;
		args.szFile = LPSTR(UINT_PTR(pct) + sizeof(TSlotIPC));
		args.hContact = pct->hContact;
		args.cch = pct->cbStrSection + 1;
		bQuit = AddToList(args);
		if (bQuit)
			break;
		pct = pct->Next;
	} // while

	if (args.files != NULL) {
		args.files = (LPSTR*)mir_realloc(args.files, (args.count + 1) * sizeof(LPSTR));
		args.files[args.count] = NULL;
		args.count++;
		if (!bQuit) {
			args.hEvent = CreateEvent(NULL, true, false, NULL);
			QueueUserAPC(MainThreadIssueTransfer, hMainThread, UINT_PTR(&args));
			while (true) {
				if (WaitForSingleObjectEx(args.hEvent, INFINITE, true) != WAIT_IO_COMPLETION)
					break;
			}
			CloseHandle(args.hEvent);
		}
		for (int j = 0; j < args.count; j++)
			mir_free(args.files[j]);
		mir_free(args.files);
	}
	SetCurrentDirectoryA(szBuf);
	mir_free(pipch);
	CloseHandle(hMainThread);
}
示例#2
0
/**
	@brief	単体テストを実行する。
	@note
	現在、単体テスト内でEngineを使用した場合の動作は保証していない。
	テスト内でCoreを直接生成する。
*/
int main(int argc, char **argv)
{
#if _WIN32
	char current_path[MAX_PATH + 1];
	GetDirectoryName(current_path, argv[0]);
	SetCurrentDirectoryA(current_path);
#endif

	//Graphics_Empty(false);
	//return 0;

	//Profiler_Profiling();
	//return 0;

	::testing::InitGoogleTest(&argc, argv);

	auto result = RUN_ALL_TESTS();
	getchar();
	return result;
}
示例#3
0
/*
* Set local current directory. Returns NULL on success, or else an
* error message which must be freed after printing.
*/
char *psftp_lcd(char *dir)
{
   char *ret = NULL;

   if (!SetCurrentDirectoryA(dir)) {
      LPVOID message;
      int i;
      FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
         FORMAT_MESSAGE_FROM_SYSTEM |
         FORMAT_MESSAGE_IGNORE_INSERTS,
         NULL, GetLastError(),
         MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
         (LPTSTR)&message, 0, NULL);
      i = strcspn((char *)message, "\n");
      ret = dupprintf("%.*s", i, (LPCTSTR)message);
      LocalFree(message);
   }

   return ret;
}
示例#4
0
static BOOL fix_current_directory(void)
{
    char *p;

    if (!GetModuleFileNameA(NULL, currentDirectory, sizeof(currentDirectory) - 1)) {
        return FALSE;
    }

    if ((p = strrchr(currentDirectory, '\\')) != NULL) {
        *p = 0;
    }

#ifndef UNDER_CE
    if (!SetCurrentDirectoryA(currentDirectory)) {
        return FALSE;
    }
#endif

    return TRUE;
}
示例#5
0
void CEditorRoot::SetMasterFolder()
{
	CHAR sFolder[_MAX_PATH];

	GetModuleFileNameA( GetModuleHandle(NULL), sFolder, sizeof(sFolder));
	PathRemoveFileSpecA(sFolder);

	CHAR *lpPath = StrStrIA(sFolder,"\\Bin32");
	if (lpPath)
		*lpPath = 0;
	lpPath = StrStrIA(sFolder,"\\Bin64");
	if (lpPath)
		*lpPath = 0;

	m_masterFolder = sFolder;
	if (!m_masterFolder.IsEmpty())
	{
		if (m_masterFolder[m_masterFolder.GetLength()-1] != '\\')
			m_masterFolder += '\\';
	}

	SetCurrentDirectoryA( sFolder );
}
示例#6
0
文件: main.cpp 项目: Pctg-x8/Altseed
/**
	@brief	単体テストを実行する。
	@note
	現在、単体テスト内でEngineを使用した場合の動作は保証していない。
	テスト内でCoreを直接生成する。
*/
int main(int argc, char **argv)
{
#if _WIN32
	char current_path[MAX_PATH + 1];
	GetDirectoryName(current_path, argv[0]);
	SetCurrentDirectoryA(current_path);
#endif
	//Graphics_CubemapTexture(true);
	//Graphics_CubemapTexture(false);
	//return 0;

	//Font_AffLoader();
	//getchar();
	//return 0;

	//Graphics_TextureFormat(false);
	//return 0;

	::testing::InitGoogleTest(&argc, argv);

	auto result = RUN_ALL_TESTS();
	getchar();
	return result;
}
示例#7
0
bool z3ResEx::setFlags( const targs &args )
{
	if( args.Count() > 1 )
	{
		if( args.HasItem("--usage") )
		{
			PrintUsage();

			// Also stop execution here (but successfully)
			return false;
		}

		if( SetCurrentDirectoryA( args.GetItemValue(1) ) == 0 )
		{
			setMessage( "ERROR: Cannot set current path to \"%s\"", args.GetItemValue(1) );
			return false;
		}

		// Allow verbose toggle when not true by default
		if( !( m_verboseMessages ) )
			m_verboseMessages = ( args.HasItem("-v") || args.HasItem("--verbose") );

		// Disable file extraction
		if( args.HasItem("-x") || args.HasItem("--no-extraction") )
			m_doExtraction = false;

		// List the filesystem contents (no extraction)
		if( args.HasItem("-l") || args.HasItem("--list-filesystem") )
		{
			m_listContents = true;
			m_doExtraction = false;
		}

		// Specify which folder to extract
		if( args.HasItem("-c") || args.HasItem("--criteria") )
		{
			bool bHasValue = false;

			const char *strVal1 = args.GetItemValue("-c");
			if( strVal1 )
			{
				m_folderCriteria = strVal1;
				bHasValue = true;
			}
			else
			{
				const char *strVal2 = args.GetItemValue("--criteria");

				if( strVal2 )
				{
					m_folderCriteria = strVal2;
					bHasValue = true;
				}
			}

			if( !bHasValue )
			{
				setMessage( "ERROR: No criteria was specified" );
				return false;
			}
		}
	}
	else
	{
		// No arguments, but inform user of them!
		puts("To see all options, use the --usage flag\n");
	}

	if( m_verboseMessages )
	{
		// Print current flags

		if( m_doExtraction )	puts("LOG: Extracting files");
		if( m_listContents )	puts("LOG: Listing filesystem");
		if( !m_folderCriteria.empty( ) )
		{
			string tmp;
			tmp = "LOG: Search criteria set to '";
			tmp += m_folderCriteria.c_str();
			tmp += "'";
			puts( tmp.c_str() );
		}
	}

	std::transform(m_folderCriteria.begin(), m_folderCriteria.end(), m_folderCriteria.begin(), ::toupper);

	return true;
}
示例#8
0
static void test_inffilelist(void)
{
    static const char inffile2[] = "test2.inf";
    static const WCHAR inffile2W[] = {'t','e','s','t','2','.','i','n','f',0};
    static const char invalid_inf[] = "invalid.inf";
    static const WCHAR invalid_infW[] = {'i','n','v','a','l','i','d','.','i','n','f',0};
    static const char *inf =
        "[Version]\n"
        "Signature=\"$Chicago$\"";
    static const char *inf2 =
        "[Version]\n"
        "Signature=\"$CHICAGO$\"";
    static const char *infNT =
        "[Version]\n"
        "Signature=\"$WINDOWS NT$\"";

    WCHAR *p, *ptr;
    char dirA[MAX_PATH];
    WCHAR dir[MAX_PATH] = { 0 };
    WCHAR buffer[MAX_PATH] = { 0 };
    DWORD expected, outsize;
    BOOL ret;

    if(!pSetupGetInfFileListW)
    {
        win_skip("SetupGetInfFileListW not present\n");
        return;
    }

    /* NULL means %windir%\\inf
     * get the value as reference
     */
    expected = 0;
    SetLastError(0xdeadbeef);
    ret = pSetupGetInfFileListW(NULL, INF_STYLE_WIN4, NULL, 0, &expected);
    if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
    {
        win_skip("SetupGetInfFileListW not implemented\n");
        return;
    }
    ok(ret, "expected SetupGetInfFileListW to succeed! Error: %d\n", GetLastError());
    ok(expected > 0, "expected required buffersize to be at least 1\n");

    /* check if an empty string doesn't behaves like NULL */
    outsize = 0;
    SetLastError(0xdeadbeef);
    ret = pSetupGetInfFileListW(dir, INF_STYLE_WIN4, NULL, 0, &outsize);
    ok(!ret, "expected SetupGetInfFileListW to fail!\n");

    /* create a private directory, the temp directory may contain some
     * inf files left over from old installations
     */
    if (!GetTempFileNameA(CURR_DIR, "inftest", 1, dirA))
    {
        win_skip("GetTempFileNameA failed with error %d\n", GetLastError());
        return;
    }
    if (!CreateDirectoryA(dirA, NULL ))
    {
        win_skip("CreateDirectoryA(%s) failed with error %d\n", dirA, GetLastError());
        return;
    }
    if (!SetCurrentDirectoryA(dirA))
    {
        win_skip("SetCurrentDirectoryA failed with error %d\n", GetLastError());
        RemoveDirectoryA(dirA);
        return;
    }

    MultiByteToWideChar(CP_ACP, 0, dirA, -1, dir, MAX_PATH);
    /* check a not existing directory
     */
    ptr = dir + lstrlenW(dir);
    MultiByteToWideChar(CP_ACP, 0, "\\not_existent", -1, ptr, MAX_PATH - lstrlenW(dir));
    outsize = 0xffffffff;
    SetLastError(0xdeadbeef);
    ret = pSetupGetInfFileListW(dir, INF_STYLE_WIN4, NULL, 0, &outsize);
    ok(ret, "expected SetupGetInfFileListW to succeed!\n");
    ok(outsize == 1, "expected required buffersize to be 1, got %d\n", outsize);
    ok(ERROR_PATH_NOT_FOUND == GetLastError(),
       "expected error ERROR_PATH_NOT_FOUND, got %d\n", GetLastError());
    
    create_inf_file(inffile, inf);
    create_inf_file(inffile2, inf);
    create_inf_file(invalid_inf, "This content does not match the inf file format");

    /* pass a filename instead of a directory
     */
    *ptr = '\\';
    MultiByteToWideChar(CP_ACP, 0, invalid_inf, -1, ptr+1, MAX_PATH - lstrlenW(dir));
    outsize = 0xffffffff;
    SetLastError(0xdeadbeef);
    ret = pSetupGetInfFileListW(dir, INF_STYLE_WIN4, NULL, 0, &outsize);
    ok(!ret, "expected SetupGetInfFileListW to fail!\n");
    ok(ERROR_DIRECTORY == GetLastError(),
       "expected error ERROR_DIRECTORY, got %d\n", GetLastError());

    /* make the filename look like directory
     */
    dir[1 + lstrlenW(dir)] = 0;
    dir[lstrlenW(dir)] = '\\';
    SetLastError(0xdeadbeef);
    ret = pSetupGetInfFileListW(dir, INF_STYLE_WIN4, NULL, 0, &outsize);
    ok(!ret, "expected SetupGetInfFileListW to fail!\n");
    ok(ERROR_DIRECTORY == GetLastError(),
       "expected error ERROR_DIRECTORY, got %d\n", GetLastError());

    /* now check the buffer content of a vaild call
     */
    *ptr = 0;
    expected = 3 + strlen(inffile) + strlen(inffile2);
    ret = pSetupGetInfFileListW(dir, INF_STYLE_WIN4, buffer, MAX_PATH, &outsize);
    ok(ret, "expected SetupGetInfFileListW to succeed!\n");
    ok(expected == outsize, "expected required buffersize to be %d, got %d\n",
         expected, outsize);
    for(p = buffer; lstrlenW(p) && (outsize > (p - buffer)); p+=lstrlenW(p) + 1)
        ok(!lstrcmpW(p,inffile2W) || !lstrcmpW(p,inffileW),
            "unexpected filename %s\n",wine_dbgstr_w(p));

    /* upper case value
     */
    create_inf_file(inffile2, inf2);
    ret = pSetupGetInfFileListW(dir, INF_STYLE_WIN4, buffer, MAX_PATH, &outsize);
    ok(ret, "expected SetupGetInfFileListW to succeed!\n");
    ok(expected == outsize, "expected required buffersize to be %d, got %d\n",
         expected, outsize);
    for(p = buffer; lstrlenW(p) && (outsize > (p - buffer)); p+=lstrlenW(p) + 1)
        ok(!lstrcmpW(p,inffile2W) || !lstrcmpW(p,inffileW),
            "unexpected filename %s\n",wine_dbgstr_w(p));

    /* signature Windows NT is also inf style win4
     */
    create_inf_file(inffile2, infNT);
    expected = 3 + strlen(inffile) + strlen(inffile2);
    ret = pSetupGetInfFileListW(dir, INF_STYLE_WIN4, buffer, MAX_PATH, &outsize);
    ok(ret, "expected SetupGetInfFileListW to succeed!\n");
    ok(expected == outsize, "expected required buffersize to be %d, got %d\n",
         expected, outsize);
    for(p = buffer; lstrlenW(p) && (outsize > (p - buffer)); p+=lstrlenW(p) + 1)
        ok(!lstrcmpW(p,inffile2W) || !lstrcmpW(p,inffileW),
            "unexpected filename %s\n",wine_dbgstr_w(p));

    /* old style
     */
    expected = 2 + strlen(invalid_inf);
    ret = pSetupGetInfFileListW(dir, INF_STYLE_OLDNT, buffer, MAX_PATH, &outsize);
    ok(ret, "expected SetupGetInfFileListW to succeed!\n");
    ok(expected == outsize, "expected required buffersize to be %d, got %d\n",
         expected, outsize);
    for(p = buffer; lstrlenW(p) && (outsize > (p - buffer)); p+=lstrlenW(p) + 1)
        ok(!lstrcmpW(p,invalid_infW), "unexpected filename %s\n",wine_dbgstr_w(p));

    /* mixed style
     */
    expected = 4 + strlen(inffile) + strlen(inffile2) + strlen(invalid_inf);
    ret = pSetupGetInfFileListW(dir, INF_STYLE_OLDNT | INF_STYLE_WIN4, buffer,
                                MAX_PATH, &outsize);
    ok(ret, "expected SetupGetInfFileListW to succeed!\n");
    ok(expected == outsize, "expected required buffersize to be %d, got %d\n",
         expected, outsize);
    for(p = buffer; lstrlenW(p) && (outsize > (p - buffer)); p+=lstrlenW(p) + 1)
        ok(!lstrcmpW(p,inffile2W) || !lstrcmpW(p,inffileW) || !lstrcmpW(p,invalid_infW),
            "unexpected filename %s\n",wine_dbgstr_w(p));

    DeleteFileA(inffile);
    DeleteFileA(inffile2);
    DeleteFileA(invalid_inf);
    SetCurrentDirectoryA(CURR_DIR);
    RemoveDirectoryA(dirA);
}
int PlayerWin::run()
{
    FileUtils::getInstance()->setPopupNotify(false);

    INITCOMMONCONTROLSEX InitCtrls;
    InitCtrls.dwSize = sizeof(InitCtrls);
    InitCtrls.dwICC = ICC_WIN95_CLASSES;
    InitCommonControlsEx(&InitCtrls);

    // set QUICK_V3_ROOT
    const char *QUICK_V3_ROOT = getenv("QUICK_V3_ROOT");
    if (!QUICK_V3_ROOT || strlen(QUICK_V3_ROOT) == 0)
    {
        MessageBox("Please run \"setup_win.bat\", set Quick-Cocos2dx-Community root path.", "Quick-Cocos2dx-Community player error");
        return 1;
    }
	_project.setQuickCocos2dxRootPath(QUICK_V3_ROOT);

    // load project config from command line args
    vector<string> args;
    for (int i = 0; i < __argc; ++i)
    {
        wstring ws(__wargv[i]);
        string s;
        s.assign(ws.begin(), ws.end());
        args.push_back(s);
    }
    _project.parseCommandLine(args);

    if (_project.getProjectDir().empty())
    {
        if (args.size() >= 2)
        {
            // for Code IDE before RC2
            _project.setProjectDir(args.at(1));
        }
        else
        {
            _project.resetToWelcome();
        }
    }

    // set framework path
    if (!_project.isLoadPrecompiledFramework())
    {
		FileUtils::getInstance()->addSearchPath(_project.getQuickCocos2dxRootPath() + "quick/");
    }

    // create the application instance
    _app = new AppDelegate();
    _app->setProjectConfig(_project);

    // set window icon
    HICON icon = LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_PLAYER));

    // create console window
    if (_project.isShowConsole())
    {
        AllocConsole();
        _hwndConsole = GetConsoleWindow();
        if (_hwndConsole != NULL)
        {
            SendMessage(_hwndConsole, WM_SETICON, ICON_BIG, (LPARAM)icon);
            SendMessage(_hwndConsole, WM_SETICON, ICON_SMALL, (LPARAM)icon);

            ShowWindow(_hwndConsole, SW_SHOW);
            BringWindowToTop(_hwndConsole);
            freopen("CONOUT$", "wt", stdout);
            freopen("CONOUT$", "wt", stderr);

            HMENU hmenu = GetSystemMenu(_hwndConsole, FALSE);
            if (hmenu != NULL)
            {
                DeleteMenu(hmenu, SC_CLOSE, MF_BYCOMMAND);
            }
        }
    }

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

    // set environments
    SetCurrentDirectoryA(_project.getProjectDir().c_str());
    FileUtils::getInstance()->setSearchRootPath(_project.getProjectDir().c_str());
    FileUtils::getInstance()->setWritablePath(_project.getWritableRealPath().c_str());

    // check screen DPI
    HDC screen = GetDC(0);
    int dpi = GetDeviceCaps(screen, LOGPIXELSX);
    ReleaseDC(0, screen);

    // set scale with DPI
    //  96 DPI = 100 % scaling
    // 120 DPI = 125 % scaling
    // 144 DPI = 150 % scaling
    // 192 DPI = 200 % scaling
    // http://msdn.microsoft.com/en-us/library/windows/desktop/dn469266%28v=vs.85%29.aspx#dpi_and_the_desktop_scaling_factor
    //
    // enable DPI-Aware with DeclareDPIAware.manifest
    // http://msdn.microsoft.com/en-us/library/windows/desktop/dn469266%28v=vs.85%29.aspx#declaring_dpi_awareness
    float screenScale = 1.0f;
    //if (dpi >= 120 && dpi < 144)
    //{
    //    screenScale = 1.25f;
    //}
    //else if (dpi >= 144 && dpi < 192)
    //{
    //    screenScale = 1.5f;
    //}
    //else if (dpi >= 192)
    //{
    //    screenScale = 2.0f;
    //}
    CCLOG("SCREEN DPI = %d, SCREEN SCALE = %0.2f", dpi, screenScale);

    // create opengl view
    Size frameSize = _project.getFrameSize();
    float frameScale = 1.0f;
    if (_project.isRetinaDisplay())
    {
        frameSize.width *= screenScale;
        frameSize.height *= screenScale;
    }
    else
    {
        frameScale = screenScale;
    }

    const Rect frameRect = Rect(0, 0, frameSize.width, frameSize.height);
    const bool isResize = _project.isResizeWindow();
    GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8};
	GLView::setGLContextAttrs(glContextAttrs);
    //auto glview = GLView::createWithRect("Quick-Cocos2dx-Community", frameRect, frameScale, isResize, false, true);
    auto glview = GLViewImpl::createWithRect("Quick-Cocos2dx-Community", frameRect, frameScale);
    _hwnd = glview->getWin32Window();
    SendMessage(_hwnd, WM_SETICON, ICON_BIG, (LPARAM)icon);
    SendMessage(_hwnd, WM_SETICON, ICON_SMALL, (LPARAM)icon);
    FreeResource(icon);

    auto director = Director::getInstance();
    director->setOpenGLView(glview);

    // set window position
    if (_project.getProjectDir().length())
    {
        setZoom(_project.getFrameScale()); 
    }
    Vec2 pos = _project.getWindowOffset();
    if (pos.x != 0 && pos.y != 0)
    {
        RECT rect;
        GetWindowRect(_hwnd, &rect);
        MoveWindow(_hwnd, pos.x, pos.y, rect.right - rect.left, rect.bottom - rect.top, FALSE);
    }

    // init player services
    initServices();

    loadLuaConfig();
    registerKeyboardEvent();

    // register event handlers
    auto eventDispatcher = director->getEventDispatcher();
    eventDispatcher->addCustomEventListener("APP.WINDOW_CLOSE_EVENT", CC_CALLBACK_1(PlayerWin::onWindowClose, this));
    eventDispatcher->addCustomEventListener("APP.WINDOW_RESIZE_EVENT", CC_CALLBACK_1(PlayerWin::onWindowResize, this));
    eventDispatcher->addCustomEventListener("APP.VIEW_SCALE", CC_CALLBACK_1(PlayerWin::onWindowScale, this));

    // prepare
    _project.dump();
    auto app = Application::getInstance();
    g_oldWindowProc = (WNDPROC)SetWindowLong(_hwnd, GWL_WNDPROC, (LONG)PlayerWin::windowProc);

    HWND hwnd = _hwnd;
    HWND hwndConsole = _hwndConsole;
    const ProjectConfig &project = _project;
    director->getScheduler()->schedule([hwnd, hwndConsole, project](float dt) {
        CC_UNUSED_PARAM(dt);
        ShowWindow(hwnd, SW_RESTORE);
        auto glview = dynamic_cast<GLViewImpl*>(Director::getInstance()->getOpenGLView());
        GLFWwindow *window = glview->getWindow();
        glfwShowWindow(window);
    }, this, 0.0f, 0, 0.001f, false, "SHOW_WINDOW_CALLBACK");

    if (project.isAppMenu() && GetMenu(hwnd))
    {
        // update window size
        RECT rect;
        GetWindowRect(_hwnd, &rect);
        MoveWindow(_hwnd, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top + GetSystemMetrics(SM_CYMENU), FALSE);
    }
    ShowWindow(_hwnd, SW_MINIMIZE);

    // startup message loop
    return app->run();
}
示例#10
0
int __cdecl main(int argc, char *argv[])
{
    BOOL bRc = FALSE;
    char szDirName[252];
    DWORD curDirLen;
    char *szTemp = NULL;
    char *szTemp2 = NULL;
    char szwCurrentDir[MAX_PATH];
    char szwSubDir[MAX_PATH];

    if (0 != PAL_Initialize(argc,argv))
    {
        return FAIL;
    }

    /*
     * remove a NULL directory 
     */
    bRc = RemoveDirectoryA(NULL);
    if (bRc != FALSE)
    {
        Fail("Error[%ul]:RemoveDirectoryA: Failed since it was able to remove a"
            " NULL directory name\n", GetLastError());
    }

    /* 
     * remove a directory that does not exist 
     */
    szTemp = (char *) malloc (sizeof("test_directory"));
    sprintf(szTemp, "test_directory");
    bRc = RemoveDirectoryA(szTemp);
    if (bRc != FALSE)
    {
        free(szTemp);
        Fail("Error[%ul]:RemoveDirectoryA: Failed since it was able to remove"
            " the non-existant directory \"test_directory\"\n", GetLastError());
    }

    /* 
     * remove a symlink to a directory
     */
    bRc = CreateDirectoryA(szTemp, NULL);
    if (bRc != TRUE)
    {
        free(szTemp);
        Fail("Error[%ul]:RemoveDirectoryA: Failed to create the directory "
            "\"test_directory\".\n", GetLastError());
    }

    char *szSymlinkName = (char *) malloc (sizeof("test_directory_symlink"));
    sprintf(szSymlinkName, "test_directory_symlink");
    if (symlink(szTemp, szSymlinkName) != 0)
    {
        Fail("Error:RemoveDirectoryA: Failed to create a symlink to the directory \"test_directory\".\n");
    }

    bRc = RemoveDirectoryA(szSymlinkName);
    if (bRc != FALSE)
    {
        Fail("Error:RemoveDirectoryA: RemoveDirectoryA should return FALSE when passed a symlink.\n");
    }

    unlink(szSymlinkName);

    /* 
     * remove a directory that exists 
     */
    bRc = RemoveDirectoryA(szTemp);
    if (bRc == FALSE)
    {
        free(szTemp);
        Fail("Error[%ul]:RemoveDirectoryW: Failed to remove the directory "
            "\"test_directory\"\n",
            GetLastError());
    }
    /* Make sure the directory was removed */
    if( -1 != GetFileAttributesA(szTemp) )
    {
        free(szTemp);
        Fail("Error[%ul]:RemoveDirectoryA: Able to get the attributes of "
             "the removed directory\n" , GetLastError());
    }
    free(szTemp);

    /* 
     * remove long directory names (245 characters) 
     */
    curDirLen = GetCurrentDirectoryA(0, NULL) + 1;
    memset(szDirName, 0, 252);
    memset(szDirName, 'a', 245 - curDirLen);
    szTemp = (char *) malloc (sizeof(szDirName));
    szTemp = strncpy(szTemp, szDirName, strlen(szDirName) + 1);

    bRc = CreateDirectoryA(szTemp, NULL);
    if (bRc == FALSE)
    {
        free(szTemp);
        Fail("Error[%ul]:RemoveDirectoryA: Failed to create a directory name "
            "245 chars long\n" , GetLastError());
    }
    bRc = RemoveDirectoryA(szTemp);
    if (bRc == FALSE)
    {
        free(szTemp);
        Fail("Error[%ul]:RemoveDirectoryA: Failed to remove a 245 char "
            "long directory\n", GetLastError());
    }

    /* Make sure the directory was removed */
    if( -1 != GetFileAttributesA(szTemp) )
    {
        free(szTemp);
        Fail("Error[%ul]:RemoveDirectoryA: Able to get the attributes of "
             "the removed directory\n", GetLastError());
    }
    free(szTemp);

    /* 
     * directories with dots 
     */
    memset(szDirName, 0, 252);
    sprintf(szDirName, ".dotDirectory");
    szTemp = (char *) malloc (sizeof(szDirName));
    szTemp = strncpy(szTemp, szDirName, strlen(szDirName) + 1);

    bRc = CreateDirectoryA(szTemp, NULL);
    if (bRc == FALSE)
    {
        free(szTemp);
        Fail("Error[%ul]:RemoveDirectoryA: Failed to create \"%s\"\n", GetLastError(), szDirName);
    }
    bRc = RemoveDirectoryA(szTemp);
    if (bRc == FALSE)
    {
        free(szTemp);
        Fail("Error[%ul]:RemoveDirectoryA: Failed to remove \"%s\"\n", GetLastError(), szDirName);
    }

    /* Make sure the directory was removed */
    if( -1 != GetFileAttributesA(szTemp) )
    {
        free(szTemp);
        Fail("Error[%ul]:RemoveDirectoryA: Able to get the attributes of "
             "the removed directory\n", GetLastError());
    }
    free(szTemp);

    /* 
     * Try calling RemoveDirectory with a file name
     */
    memset(szDirName, 0, 252);
    sprintf(szDirName, "removedirectoryw.c");
    szTemp = (char *) malloc (sizeof(szDirName));
    szTemp = strncpy(szTemp, szDirName, strlen(szDirName) + 1);

    bRc = RemoveDirectoryA(szTemp);
    free(szTemp);
    if (bRc != FALSE)
    {
        Fail("Error[%ul]:RemoveDirectoryA: should have failed when "
             "called with a valid file name", GetLastError() );
    }

    /* 
     * remove a non empty directory 
     *
     * To test that, we'll first create non_empty_dir, we'll
     * set the current dir to non_empty_dir in which we'll
     * create sub_dir. We'll go back to the root of non_empty_dir
     * and we'll try to delete it (it shouldn't work).
     * After that we'll cleanup sub_dir and non_empty_dir 
     */

    /* Get the current directory so it is easy to get back
       to it later */
    if( 0 == GetCurrentDirectoryA(MAX_PATH, szwCurrentDir) )
    {
        Fail("RemoveDirectoryA: Failed to get current directory "
            "with GetCurrentDirectoryA.\n");
    }

    /* Create non_empty_dir */
    sprintf( szDirName, "non_empty_dir");
    szTemp = (char *) malloc (sizeof(szDirName));
    szTemp = strncpy(szTemp, szDirName, strlen(szDirName) + 1);
    bRc = CreateDirectoryA(szTemp, NULL);
    if (bRc != TRUE)
    {
        free(szTemp);
        Fail("Error[%ul]:RemoveDirectoryA: Failed to create the directory "
             "\"non_empty_dir\" when it exists already.\n", GetLastError());
    }

    if( 0 == SetCurrentDirectoryA(szTemp) )
    {
        free(szTemp);
        Fail("Error[%ul]:RemoveDirectoryA: Failed to set current directory to "
            "\"non_empty_dir\" with SetCurrentDirectoryA.\n", GetLastError());
    }

    /* Get the directory full path so it is easy to get back
       to it later */
    if( 0 == GetCurrentDirectoryA(MAX_PATH, szwSubDir) )
    {
        free(szTemp);
        Fail("Error[%ul]:RemoveDirectoryA: Failed to get current directory "
            "with GetCurrentDirectoryA.\n", GetLastError());
    }

    /* Create sub_dir */
    sprintf (szDirName, "sub_dir");
    szTemp2 = (char *) malloc (sizeof(szDirName));
    szTemp2 = strncpy(szTemp2, szDirName, strlen(szDirName) + 1);
    bRc = CreateDirectoryA(szTemp2, NULL);
    if (bRc != TRUE)
    {
        free(szTemp);
        free(szTemp2);
        Fail("Error[%ul]:RemoveDirectoryA: Failed to create the directory "
            "\"sub_dir\" when it exists already.\n", GetLastError());
    }

    /* Set the current dir to the parent of non_empty_dir/sub_dir */
    if( 0 == SetCurrentDirectoryA(szwCurrentDir) )
    {
        free(szTemp);
        free(szTemp2);
        Fail("Error[%ul]:RemoveDirectoryA: Failed to set current directory to "
            "\"non_empty_dir\" with SetCurrentDirectoryA.\n", GetLastError());
    }

    /* Try to remove non_empty_dir (shouldn't work) */
    bRc = RemoveDirectoryA(szTemp);
    if (bRc == TRUE)
    {
        free(szTemp);
        free(szTemp2);
        Fail("Error[%ul]:RemoveDirectoryA: shouldn't have been able to remove "
             "the non empty directory \"non_empty_dir\"\n", GetLastError());
    }

    /* Go back to non_empty_dir and remove sub_dir */
    if( 0 == SetCurrentDirectoryA(szwSubDir) )
    {
        free(szTemp);
        free(szTemp2);
        Fail("Error[%ul]:RemoveDirectoryA: Failed to set current directory to "
            "\"non_empty_dir\" with SetCurrentDirectoryA.\n", GetLastError());
    }

    bRc = RemoveDirectoryA(szTemp2);
    if (bRc == FALSE)
    {
        free(szTemp);
        free(szTemp2);
        Fail("Error[%ul]:RemoveDirectoryA: unable to remove "
             "directory \"sub_dir\" \n",
             GetLastError());
    }
    /* Make sure the directory was removed */
    if( -1 != GetFileAttributesA(szTemp2) )
    {
        Fail("Error[%ul]RemoveDirectoryA: Able to get the attributes of "
             "the removed directory\n", GetLastError());
    }
    free(szTemp2);

    /* Go back to parent of non_empty_dir and remove non_empty_dir */
    if( 0 == SetCurrentDirectoryA(szwCurrentDir) )
    {
        free(szTemp);
        Fail("Error[%ul]:RemoveDirectoryA: Failed to set current directory to "
            "\"..\non_empty_dir\" with SetCurrentDirectoryA.\n", GetLastError());
    }
    bRc = RemoveDirectoryA(szTemp);
    if (bRc == FALSE)
    {
        free(szTemp);    
        Fail("Error[%ul]RemoveDirectoryA: unable to remove "
             "the directory \"non_empty_dir\"\n",
             GetLastError());
    }
    /* Make sure the directory was removed */
    if( -1 != GetFileAttributesA(szTemp) )
    {
        Fail("Error[%ul]:RemoveDirectoryA: Able to get the attributes of "
             "the removed directory\n", GetLastError());
    }
    free(szTemp); 


    PAL_Terminate();  
    return PASS;
}
示例#11
0
int CALLBACK WinMain(HINSTANCE Instance, HINSTANCE PrevInstance, LPSTR CommandLine, int ShowCode)
{
    // Tick frequency
    {
        int64 TicksPerSecond;
        QueryPerformanceFrequency((LARGE_INTEGER *)&TicksPerSecond);
        Timer::Init(1000.0 / TicksPerSecond);
    }

    QueryPerformanceCounter((LARGE_INTEGER *)&Mem.Debug.Time);
    Timer::StartTime(&Mem.Debug.Timers[Timer_Startup]);

    Mem.IsRunning = true;

    // Set current path to this executable's path
    {
        HMODULE Module = GetModuleHandleA(NULL);
        char PathString[MAX_PATH];
        uint32 PathLength = GetModuleFileNameA(Module, PathString, MAX_PATH);
        if (PathLength != -1)
        {
            char *LastSlash = strrchr(PathString, '\\');
            if (LastSlash) { *LastSlash = '\0'; }
            SetCurrentDirectoryA(PathString);
        }
    }

    HWND Window;
    // Create Window
    {
        WNDCLASSA WindowClass = {};
        WindowClass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
        WindowClass.lpfnWndProc = Win32MainWindowCallback;
        WindowClass.hInstance = Instance;
        const char* IcoPath = "papaya.ico";
        WindowClass.hIcon = (HICON)LoadImage(0, IcoPath, IMAGE_ICON, 0, 0, LR_LOADFROMFILE | LR_DEFAULTSIZE | LR_SHARED);
        WindowClass.lpszClassName = "PapayaWindowClass";

        if (!RegisterClassA(&WindowClass))
        {
            // TODO: Log: Register window class failed
            return 0;
        }

        Window =
            CreateWindowExA(
            0,                                                          // Extended window style
            WindowClass.lpszClassName,                                  // Class name,
            "Papaya",                                                   // Name,
            WS_POPUP | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_VISIBLE,    // Window style
            CW_USEDEFAULT,                                              // X,
            CW_USEDEFAULT,                                              // Y,
            CW_USEDEFAULT,                                              // Width,
            CW_USEDEFAULT,                                              // Height,
            0,                                                          // Window Parent,
            0,                                                          // Menu,
            Instance,                                                   // Handle to the instance,
            0);                                                         // lpParam

        if (!Window)
        {
            // TODO: Log: Create window failed
            return 0;
        }

        SystemParametersInfo(SPI_GETWORKAREA, 0, &WindowsWorkArea, 0);

#ifdef PAPAYARELEASE

        SetWindowPos(Window, HWND_TOP, 0, 0, 600, 600, NULL);
        ShowWindow(Window, SW_MAXIMIZE);
#else
        uint32 ScreenWidth = GetSystemMetrics(SM_CXSCREEN);
        uint32 ScreenHeight = GetSystemMetrics(SM_CYSCREEN);

        Mem.Window.Width = (uint32)((float)ScreenWidth * 0.5);
        Mem.Window.Height = (uint32)((float)ScreenHeight * 0.8);

        uint32 WindowX = (ScreenWidth - Mem.Window.Width) / 2;
        uint32 WindowY = (ScreenHeight - Mem.Window.Height) / 2;

        SetWindowPos(Window, HWND_TOP, WindowX, WindowY, Mem.Window.Width, Mem.Window.Height, NULL);
#endif // PAPAYARELEASE

        // Get window size
        {
            RECT WindowRect = { 0 };
            BOOL foo = GetClientRect(Window, &WindowRect);
            Mem.Window.Width  = WindowRect.right - WindowRect.left;
            Mem.Window.Height = WindowRect.bottom - WindowRect.top;
        }
    }

    // Initialize OpenGL
    {
        DeviceContext = GetDC(Window);

        // Setup pixel format
        {
            PIXELFORMATDESCRIPTOR PixelFormatDesc = { 0 };
            // TODO: Program seems to work perfectly fine without all other params except dwFlags.
            //       Can we skip other params for the sake of brevity?
            PixelFormatDesc.nSize = sizeof(PIXELFORMATDESCRIPTOR);
            PixelFormatDesc.nVersion = 1;
            PixelFormatDesc.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
            PixelFormatDesc.iPixelType = PFD_TYPE_RGBA;
            PixelFormatDesc.cColorBits = 32;
            PixelFormatDesc.cDepthBits = 32;
            PixelFormatDesc.dwLayerMask = PFD_MAIN_PLANE;
            //

            int32 PixelFormat = ChoosePixelFormat(DeviceContext, &PixelFormatDesc);
            if (!PixelFormat) { exit(1); } // TODO: Log: Choose pixel format failed
            if (!SetPixelFormat(DeviceContext, PixelFormat, &PixelFormatDesc)) { exit(1); } // TODO: Log: Set pixel format failed
        }

        // Create rendering context
        {
            // TODO: Create "proper" context?
            //       https://www.opengl.org/wiki/Creating_an_OpenGL_Context_(WGL)#Proper_Context_Creation

            HGLRC RenderingContext = wglCreateContext(DeviceContext);
            wglMakeCurrent(DeviceContext, RenderingContext);

            if (!GL::InitAndValidate()) { exit(1); }

            glGetIntegerv(GL_MAJOR_VERSION, &Mem.System.OpenGLVersion[0]);
            glGetIntegerv(GL_MINOR_VERSION, &Mem.System.OpenGLVersion[1]);
        }

        // Disable vsync
        if (wglewIsSupported("WGL_EXT_swap_control")) { wglSwapIntervalEXT(0); }
    }

    // Initialize tablet
    EasyTab_Load(Window);

    Core::Initialize(&Mem);

    // Initialize ImGui
    {
        ImGuiIO& io = ImGui::GetIO();
        io.KeyMap[ImGuiKey_Tab] = VK_TAB;          // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array that we will update during the application lifetime.
        io.KeyMap[ImGuiKey_LeftArrow] = VK_LEFT;
        io.KeyMap[ImGuiKey_RightArrow] = VK_RIGHT;
        io.KeyMap[ImGuiKey_UpArrow] = VK_UP;
        io.KeyMap[ImGuiKey_DownArrow] = VK_DOWN;
        io.KeyMap[ImGuiKey_Home] = VK_HOME;
        io.KeyMap[ImGuiKey_End] = VK_END;
        io.KeyMap[ImGuiKey_Delete] = VK_DELETE;
        io.KeyMap[ImGuiKey_Backspace] = VK_BACK;
        io.KeyMap[ImGuiKey_Enter] = VK_RETURN;
        io.KeyMap[ImGuiKey_Escape] = VK_ESCAPE;
        io.KeyMap[ImGuiKey_A] = 'A';
        io.KeyMap[ImGuiKey_C] = 'C';
        io.KeyMap[ImGuiKey_V] = 'V';
        io.KeyMap[ImGuiKey_X] = 'X';
        io.KeyMap[ImGuiKey_Y] = 'Y';
        io.KeyMap[ImGuiKey_Z] = 'Z';

        io.RenderDrawListsFn = Core::RenderImGui;
        io.ImeWindowHandle = Window;
    }


    Mem.Window.MenuHorizontalOffset = 32;
    Mem.Window.TitleBarButtonsWidth = 109;
    Mem.Window.TitleBarHeight = 30;

    Timer::StopTime(&Mem.Debug.Timers[Timer_Startup]);

    // Handle command line arguments (if present)
    if (strlen(CommandLine)) 
    {
        // Remove double quotes from string if present
        {
            char* PtrRead  = CommandLine;
            char* PtrWrite = CommandLine;
            while (*PtrRead) 
            {
                *PtrWrite = *PtrRead++;
                if (*PtrWrite != '\"') { PtrWrite++; }
            }
            *PtrWrite = '\0';
        }
        Core::OpenDocument(CommandLine, &Mem); 
    }

#ifdef PAPAYA_DEFAULT_IMAGE
    Core::OpenDocument(PAPAYA_DEFAULT_IMAGE, &Mem);
#endif // PAPAYA_DEFAULT_IMAGE

    while (Mem.IsRunning)
    {
        Timer::StartTime(&Mem.Debug.Timers[Timer_Frame]);

        // Windows message handling
        {
            MSG Message;
            while (PeekMessage(&Message, 0, 0, 0, PM_REMOVE))
            {
                if (Message.message == WM_QUIT)
                {
                    Mem.IsRunning = false;
                }

                TranslateMessage(&Message);
                DispatchMessageA(&Message);
            }
        }

        // Tablet input // TODO: Put this in papaya.cpp
        {
            Mem.Tablet.Pressure = EasyTab->Pressure;
            Mem.Tablet.PosX = EasyTab->PosX;
            Mem.Tablet.PosY = EasyTab->PosY;
            Mem.Tablet.Buttons = EasyTab->Buttons;
        }

        BOOL IsMaximized = IsMaximized(Window);
        if (IsIconic(Window)) { goto EndOfFrame; }

        // Start new ImGui frame
        {
            ImGuiIO& io = ImGui::GetIO();

            // Setup display size (every frame to accommodate for window resizing)
            RECT rect;
            GetClientRect(Window, &rect);
            io.DisplaySize = ImVec2((float)(rect.right - rect.left), (float)(rect.bottom - rect.top));

            // Read keyboard modifiers inputs
            io.KeyCtrl = (GetKeyState(VK_CONTROL) & 0x8000) != 0;
            io.KeyShift = (GetKeyState(VK_SHIFT) & 0x8000) != 0;
            io.KeyAlt = (GetKeyState(VK_MENU) & 0x8000) != 0;

            // Setup time step
            INT64 current_time;
            QueryPerformanceCounter((LARGE_INTEGER *)&current_time);
            io.DeltaTime = (float)(current_time - Mem.Debug.Time) * 
                           (float)Timer::GetFrequency() / 1000.0f;
            Mem.Debug.Time = current_time; // TODO: Move Imgui timers from Debug to their own struct

            // Hide OS mouse cursor if ImGui is drawing it
            //SetCursor(io.MouseDrawCursor ? NULL : LoadCursor(NULL, IDC_ARROW));

            // Start the frame
            ImGui::NewFrame();
        }

        // Title Bar Icon
        {
            ImGui::SetNextWindowSize(ImVec2((float)Mem.Window.MenuHorizontalOffset,(float)Mem.Window.TitleBarHeight));
            ImGui::SetNextWindowPos(ImVec2(1.0f, 1.0f));

            ImGuiWindowFlags WindowFlags = 0; // TODO: Create a commonly-used set of Window flags, and use them across ImGui windows
            WindowFlags |= ImGuiWindowFlags_NoTitleBar;
            WindowFlags |= ImGuiWindowFlags_NoResize;
            WindowFlags |= ImGuiWindowFlags_NoMove;
            WindowFlags |= ImGuiWindowFlags_NoScrollbar;
            WindowFlags |= ImGuiWindowFlags_NoCollapse;
            WindowFlags |= ImGuiWindowFlags_NoScrollWithMouse;

            ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0);
            ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(2,2));
            ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0,0));
            ImGui::PushStyleVar(ImGuiStyleVar_ItemInnerSpacing, ImVec2(0,0));
            ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0,0));

            ImGui::PushStyleColor(ImGuiCol_WindowBg, Mem.Colors[PapayaCol_Transparent]);

            bool bTrue = true;
            ImGui::Begin("Title Bar Icon", &bTrue, WindowFlags);

            #define CALCUV(X, Y) ImVec2((float)X/256.0f, (float)Y/256.0f)
            ImGui::Image((void*)(intptr_t)Mem.Textures[PapayaTex_UI], ImVec2(28,28), CALCUV(0,200), CALCUV(28,228));
            #undef CALCUV

            ImGui::End();

            ImGui::PopStyleColor(1);
            ImGui::PopStyleVar(5);
        }

        // Title Bar Buttons
        {
            ImGui::SetNextWindowSize(ImVec2((float)Mem.Window.TitleBarButtonsWidth,24.0f));
            ImGui::SetNextWindowPos(ImVec2((float)Mem.Window.Width - Mem.Window.TitleBarButtonsWidth, 0.0f));

            ImGuiWindowFlags WindowFlags = 0;
            WindowFlags |= ImGuiWindowFlags_NoTitleBar;
            WindowFlags |= ImGuiWindowFlags_NoResize;
            WindowFlags |= ImGuiWindowFlags_NoMove;
            WindowFlags |= ImGuiWindowFlags_NoScrollbar;
            WindowFlags |= ImGuiWindowFlags_NoCollapse;
            WindowFlags |= ImGuiWindowFlags_NoScrollWithMouse;

            ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0);
            ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0,0));
            ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0,0));
            ImGui::PushStyleVar(ImGuiStyleVar_ItemInnerSpacing, ImVec2(0,0));
            ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0,0));

            ImGui::PushStyleColor(ImGuiCol_Button, Mem.Colors[PapayaCol_Transparent]);
            ImGui::PushStyleColor(ImGuiCol_ButtonHovered, Mem.Colors[PapayaCol_ButtonHover]);
            ImGui::PushStyleColor(ImGuiCol_ButtonActive, Mem.Colors[PapayaCol_ButtonActive]);
            ImGui::PushStyleColor(ImGuiCol_WindowBg, Mem.Colors[PapayaCol_Transparent]);

            bool bTrue = true;

            #define CALCUV(X, Y) ImVec2((float)X/256.0f, (float)Y/256.0f)
            ImGui::Begin("Title Bar Buttons", &bTrue, WindowFlags);

            ImGui::PushID(0);
            if(ImGui::ImageButton((void*)(size_t)Mem.Textures[PapayaTex_UI], ImVec2(34,26), CALCUV(62,200),CALCUV(96,226), 1, ImVec4(0,0,0,0)))
            {
                ShowWindow(Window, SW_MINIMIZE);
            }

            ImVec2 StartUV = IsMaximized ? CALCUV(28,226) : CALCUV(62,226);
            ImVec2 EndUV   = IsMaximized ? CALCUV(62,252) : CALCUV(96,252);

            ImGui::PopID();
            ImGui::SameLine();
            ImGui::PushID(1);

            if(ImGui::ImageButton((void*)(size_t)Mem.Textures[PapayaTex_UI], ImVec2(34,26), StartUV, EndUV, 1, ImVec4(0,0,0,0)))
            {
                if (IsMaximized)
                {
                    ShowWindow(Window, SW_RESTORE);
                }
                else
                {
                    ShowWindow(Window, SW_MAXIMIZE);
                }
            }

            ImGui::PopID();
            ImGui::SameLine();
            ImGui::PushID(2);

            if(ImGui::ImageButton((void*)(size_t)Mem.Textures[PapayaTex_UI], ImVec2(34,26), CALCUV(28,200),CALCUV(62,226), 1, ImVec4(0,0,0,0)))
            {
                SendMessage(Window, WM_CLOSE, 0, 0);
            }

            ImGui::PopID();

            ImGui::End();
            #undef CALCUV

            ImGui::PopStyleVar(5);
            ImGui::PopStyleColor(4);
        }

        // ImGui::ShowTestWindow();
        Core::UpdateAndRender(&Mem);
        SwapBuffers(DeviceContext);

    EndOfFrame:
        Timer::StopTime(&Mem.Debug.Timers[Timer_Frame]);
        double FrameRate = (Mem.CurrentTool == PapayaTool_Brush && Mem.Mouse.IsDown[0]) ?
                           500.0 : 60.0;
        double FrameTime = 1000.0 / FrameRate;
        double SleepTime = FrameTime - Mem.Debug.Timers[Timer_Frame].ElapsedMs;
        Mem.Debug.Timers[Timer_Sleep].ElapsedMs = SleepTime;
        if (SleepTime > 0) { Sleep((int32)SleepTime); }
    }

    Core::Shutdown(&Mem);

    EasyTab_Unload();

    return 0;
}
示例#12
0
FileList::FileList(const FilePath & filepath)
{
    DVASSERT(filepath.IsDirectoryPathname());
    
	path = filepath;

// Windows version
#if defined(__DAVAENGINE_WIN32__)

	//char tmp[_MAX_PATH];
	//_getcwd(tmp, _MAX_PATH);
	//Path = tmp;
	FilePath prevDir = FileSystem::Instance()->GetCurrentWorkingDirectory();
	BOOL res = SetCurrentDirectoryA(path.GetAbsolutePathname().c_str());

	if (res)
	{
		struct _finddata_t c_file;
		intptr_t hFile;
		FileEntry entry;

		if( (hFile = _findfirst( "*", &c_file )) != -1L )
		{
			do
			{
                //TODO: need to check for Win32
				entry.path = filepath + c_file.name;
				entry.name = c_file.name;
				entry.size = c_file.size;
				entry.isDirectory = (_A_SUBDIR & c_file.attrib) != 0;
				if(entry.isDirectory)
				{
					entry.path.MakeDirectoryPathname();
				}

				fileList.push_back(entry);
				//Logger::FrameworkDebug("filelist: %s %s", filepath.c_str(), entry.name.c_str());
			}
			while( _findnext( hFile, &c_file ) == 0 );

			_findclose( hFile );
		}
	}
	FileSystem::Instance()->SetCurrentWorkingDirectory(prevDir);

	//TODO add drives
	//entry.Name = "E:\\";
	//entry.isDirectory = true;
	//Files.push_back(entry);
#elif defined(__DAVAENGINE_MACOS__) || defined(__DAVAENGINE_IPHONE__) || defined (__DAVAENGINE_ANDROID__)
	struct dirent **namelist;
	FileEntry entry;

#if defined (__DAVAENGINE_ANDROID__)
	int32 n = scandir(path.GetAbsolutePathname().c_str(), &namelist, 0, alphasortAndroid);
#else //#if defined (__DAVAENGINE_ANDROID__)
	int32 n = scandir(path.GetAbsolutePathname().c_str(), &namelist, 0, alphasort);
#endif //#if defined (__DAVAENGINE_ANDROID__)    
    
	if (n >= 0)
	{
		while(n--)
		{
			entry.path = path + namelist[n]->d_name;
			entry.name = namelist[n]->d_name;
			entry.size = 0;
			entry.isDirectory = namelist[n]->d_type == DT_DIR;
            if(entry.isDirectory)
            {
                entry.path.MakeDirectoryPathname();
            }
			fileList.push_back(entry);
			free(namelist[n]);
		}
		free(namelist);
	}
#endif //PLATFORMS

	directoryCount = 0;
	fileCount = 0;
	for (int fi = 0; fi < GetCount(); ++fi)
	{
		if (IsDirectory(fi))
		{
			if (!IsNavigationDirectory(fi))
				directoryCount++;
		}else
			fileCount++;
	}
}
示例#13
0
int WebEmberLinker::link(const char* prefix)
{
	assert(!mModuleHandle);
	std::string libdir(prefix);

#ifdef _WIN32
	if(!libdir.empty()) {
#if defined(_DEBUG) && defined(SEPARATE_BUILDS)
		//In msvc I prefer to separate release/debug builds to prevent mixing the runtime.
		//Set SEPARATE_BUILDS to enable this feature.
		libdir += "\\bin_d";
#else
		libdir += "\\bin";
#endif
		SetDllDirectoryA(libdir.c_str());
		SetCurrentDirectoryA(libdir.c_str());
		libdir += "\\";
	}

	//normally the browsers are disabling verbose popup messages from the OS on errors,
	//but to get more info on what is the missing DLL when linking recursively, we need to enable this.
	UINT browserErrorMode = GetErrorMode();
	SetErrorMode(0);
#else
	if (!libdir.empty()) {
		libdir += "/lib/";
	}
#endif

	std::string libfile(libdir + sLibName);
	FBLOG_INFO("WebEmberLinker::runEmber", "Loading library: " << libfile);
	//Loads the specified module into the address space of the calling process.
	mModuleHandle = LoadLib(libfile.c_str());
	if (mModuleHandle == NULL) {
#ifndef _WIN32
		FBLOG_ERROR("WebEmberLinker::runEmber", "dlerror: " << dlerror());
#endif
		FBLOG_ERROR("WebEmberLinker::runEmber", "Unable to load " << libfile);
		return 1;
	}
	
	//Retrieves the address of an exported function or variable from the specified DLL.
	pStartWebEmber = (funcTypeStart)GetFunction(mModuleHandle, sFuncNameStart);
	if (pStartWebEmber == NULL) {
#ifndef _WIN32
		FBLOG_ERROR("WebEmberLinker::runEmber", "dlerror: " << dlerror());
#endif
		FBLOG_ERROR("WebEmberLinker::runEmber", "Unable to load function " << sFuncNameStart << " in " << libfile);
		UnloadLib(mModuleHandle);
		return 2;
	}

	//same as above
	pQuitWebEmber = (funcTypeQuit)GetFunction(mModuleHandle, sFuncNameQuit);
	if (pQuitWebEmber == NULL) {
#ifndef _WIN32
		FBLOG_ERROR("WebEmberLinker::runEmber", "dlerror: " << dlerror());
#endif
		FBLOG_ERROR("WebEmberLinker::runEmber", "Unable to load function " << sFuncNameQuit << " in " << libfile);
		UnloadLib(mModuleHandle);
		return 3;
	}

#ifdef _WIN32
	//SetErrorMode of the process back to the original.
	SetErrorMode(browserErrorMode);
#endif
	return 0;
}
示例#14
0
static void test_find_file(void)
{
    DWORD ret;
    UINT dwCur, dwOut ;
    char appdir[MAX_PATH];
    char curdir[MAX_PATH];
    char filename[MAX_PATH];
    char outBuf[MAX_PATH];
    char windir[MAX_PATH];
    static CHAR empty[]    = "",
               regedit[] = "regedit",
               regedit_exe[] = "regedit.exe";

    memset(appdir, 0, MAX_PATH);
    memset(windir, 0, MAX_PATH);

    dwCur=MAX_PATH;
    dwOut=MAX_PATH;
    memset(curdir, 0, MAX_PATH);
    memset(outBuf, 0, MAX_PATH);
    ret = VerFindFileA(0, regedit, empty, empty, curdir, &dwCur, outBuf, &dwOut);
    switch(ret) {
    case 0L:
    ok(dwCur == 1, "Wrong length of buffer for current location: "
       "got %d(%s) expected 1\n", dwCur, curdir);
    ok(dwOut == 1, "Wrong length of buffer for the recommended installation location: "
       "got %d(%s) expected 1\n", dwOut, outBuf);
        break;
    case VFF_BUFFTOOSMALL:
        ok(dwCur == MAX_PATH, "Wrong length of buffer for current location: "
           "got %d(%s) expected MAX_PATH\n", dwCur, curdir);
        ok(dwOut == MAX_PATH, "Wrong length of buffer for the recommended installation location: "
           "got %d(%s) expected MAX_PATH\n", dwOut, outBuf);
        break;
    default:
        ok(0, "Got unexpected return value %x\n", ret);
    }

    if(!GetWindowsDirectoryA(windir, MAX_PATH))
        trace("GetWindowsDirectoryA failed\n");
    else {
        sprintf(appdir, "%s\\regedit.exe", windir);
        if(INVALID_FILE_ATTRIBUTES == GetFileAttributesA(appdir))
            trace("GetFileAttributesA(%s) failed\n", appdir);
        else {
            dwCur=MAX_PATH;
            dwOut=MAX_PATH;
            memset(curdir, 0, MAX_PATH);
            memset(outBuf, 0, MAX_PATH);
            ret = VerFindFileA(0, regedit_exe, empty, empty, curdir, &dwCur, outBuf, &dwOut);
            switch(ret) {
            case VFF_CURNEDEST:
                ok(dwCur == 1 + strlen(windir), "Wrong length of buffer for current location: "
               "got %d(%s) expected %d\n", dwCur, curdir, lstrlenA(windir)+1);
            ok(dwOut == 1, "Wrong length of buffer for the recommended installation location: "
               "got %d(%s) expected 1\n", dwOut, outBuf);
                break;
            case VFF_BUFFTOOSMALL:
                ok(dwCur == MAX_PATH, "Wrong length of buffer for current location: "
                   "got %d(%s) expected MAX_PATH\n", dwCur, curdir);
                ok(dwOut == MAX_PATH, "Wrong length of buffer for the recommended installation location: "
                   "got %d(%s) expected MAX_PATH\n", dwOut, outBuf);
                break;
            default:
                todo_wine ok(0, "Got unexpected return value %x\n", ret);
            }

            dwCur=MAX_PATH;
            dwOut=MAX_PATH;
            memset(curdir, 0, MAX_PATH);
            memset(outBuf, 0, MAX_PATH);
            ret = VerFindFileA(0, regedit_exe, NULL, NULL, curdir, &dwCur, outBuf, &dwOut);
            switch(ret) {
            case VFF_CURNEDEST:
                ok(dwCur == 1 + strlen(windir), "Wrong length of buffer for current location: "
               "got %d(%s) expected %d\n", dwCur, curdir, lstrlenA(windir)+1);
            ok(dwOut == 1, "Wrong length of buffer for the recommended installation location: "
               "got %d(%s) expected 1\n", dwOut, outBuf);
                break;
            case VFF_BUFFTOOSMALL:
                ok(dwCur == MAX_PATH, "Wrong length of buffer for current location: "
                   "got %d(%s) expected MAX_PATH\n", dwCur, curdir);
                ok(dwOut == MAX_PATH, "Wrong length of buffer for the recommended installation location: "
                   "got %d(%s) expected MAX_PATH\n", dwOut, outBuf);
                break;
            default:
                todo_wine ok(0, "Got unexpected return value %x\n", ret);
            }
        }
    }
    if(!GetModuleFileNameA(NULL, filename, MAX_PATH) ||
       !GetSystemDirectoryA(windir, MAX_PATH) ||
       !GetTempPathA(MAX_PATH, appdir))
        trace("GetModuleFileNameA, GetSystemDirectoryA or GetTempPathA failed\n");
    else {
        char *p = strrchr(filename, '\\');
        if(p) {
            *(p++) ='\0';
            SetCurrentDirectoryA(filename);
            memmove(filename, p, 1 + strlen(p));
        }

        dwCur=MAX_PATH;
        dwOut=MAX_PATH;
        memset(outBuf, 0, MAX_PATH);
        memset(curdir, 0, MAX_PATH);
        ret = VerFindFileA(0, filename, NULL, NULL, curdir, &dwCur, outBuf, &dwOut);
        switch(ret) {
        case VFF_CURNEDEST:
        ok(dwOut == 1, "Wrong length of buffer for the recommended installation location"
           "got %d(%s) expected 1\n", dwOut, outBuf);
            break;
        case VFF_BUFFTOOSMALL:
            ok(dwOut == MAX_PATH, "Wrong length of buffer for the recommended installation location"
               "got %d(%s) expected MAX_PATH\n", dwOut, outBuf);
            break;
        default:
            todo_wine ok(0, "Got unexpected return value %x\n", ret);
        }

        dwCur=MAX_PATH;
        dwOut=MAX_PATH;
        memset(outBuf, 0, MAX_PATH);
        memset(curdir, 0, MAX_PATH);
        ret = VerFindFileA(VFFF_ISSHAREDFILE, filename, NULL, appdir, curdir, &dwCur, outBuf, &dwOut);
        todo_wine ok(VFF_CURNEDEST == ret, "Wrong return value got %x expected VFF_CURNEDEST\n", ret);
        ok(dwOut == 1 + strlen(windir), "Wrong length of buffer for current location: "
           "got %d(%s) expected %d\n", dwOut, outBuf, lstrlenA(windir)+1);

        dwCur=MAX_PATH;
        dwOut=MAX_PATH;
        memset(outBuf, 0, MAX_PATH);
        memset(curdir, 0, MAX_PATH);
        ret = VerFindFileA(0, filename, NULL, appdir, curdir, &dwCur, outBuf, &dwOut);
        todo_wine ok(VFF_CURNEDEST == ret, "Wrong return value got %x expected VFF_CURNEDEST\n", ret);
        ok(dwOut == 1 + strlen(appdir), "Wrong length of buffer for current location: "
           "got %d(%s) expected %d\n", dwOut, outBuf, lstrlenA(appdir)+1);
    }
}
示例#15
0
int UiPlayer::run(void)
{
    const char *QUICK_COCOS2DX_ROOT = getenv("QUICK_COCOS2DX_ROOT");
    SimulatorConfig::sharedDefaults()->setQuickCocos2dxRootPath(QUICK_COCOS2DX_ROOT);

    loadProjectConfig();

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

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

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

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

    do
    {
        m_exit = TRUE;

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

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

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

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

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

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

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

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

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

        m_app->run();

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

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

    FreeConsole();
    if (m_writeDebugLogFile) fclose(m_writeDebugLogFile);
    return 0;
}
示例#16
0
int
visit_path_recursively(const char* pcszPath, operate_callback file_func,
		       operate_callback dir_func,
		       operate_callback dir_func2){
#ifndef WIN32
	struct stat		statbuf;
	struct dirent		*dirp;
	DIR			*dp;
	char			szPath[MAX_PATH];
	int			nRet = 1;
	
	lstat(pcszPath, &statbuf);

	/* if it is a file, use file operation
	   callback function to process it */
	if (S_ISDIR(statbuf.st_mode) == 0){
		if ( file_func != NULL ){
			nRet = file_func( pcszPath );
			return nRet;
		}
		else
			return 1;
	}

	/* here it is qure a path, then try to open the directory */
	if ( (dp = opendir(pcszPath)) == NULL){
		write_log(LT_BOTH, "Error: Can't open directory: %s!\n",
			  szPath );
		return 0;
	}

	/* use directory operation callback function to process it */
	if ( dir_func != NULL ){
		nRet = dir_func(pcszPath);
		if ( nRet == 0 || nRet == 2 ){
			if ( nRet == 0 )
				write_log(LT_BOTH, "Error: when process %s using dir_func!\n", pcszPath);
			goto exit;
		}
	}

	/* Read the directory and visit its all child recursively */

	while ( (dirp = readdir(dp)) != NULL) {
		/* ignore dot and dot-dot */
		if (strcmp(dirp->d_name, ".") == 0  ||
		    strcmp(dirp->d_name, "..") == 0)
			continue;

		/* append name after slash */
		sprintf(szPath, "%s/%s", pcszPath, dirp->d_name);

		nRet = visit_path_recursively(szPath, file_func, dir_func, dir_func2);
		if ( nRet == 0 ){
			write_log(LT_BOTH, "Error: when process %s!\n", szPath);
			goto exit;
		}
		if ( dir_func2 != NULL ){
			nRet = dir_func2(szPath);
			if ( nRet == 0 ){
				write_log(LT_BOTH, "Error: when process %s using dir_func2!\n", szPath);				
				goto exit;
			}
		}
	}

 exit:
	/* close the directory which is opened before */
	if (closedir(dp) < 0)
		write_log(LT_BOTH, "Error: Can't close directory %s!\n", pcszPath);
	
	return nRet;
#else		//WIN32
	intptr_t		hFind;
	_finddata_t		FindData;
	char			szPath[MAX_PATH];
	int			nRet = 1;

    if ( SetCurrentDirectoryA(pcszPath) == 0 ){
		write_log(LT_BOTH, "Error: Can't set the current directory: %s!\n",
			  pcszPath);
		return 0;
	}

	hFind = _findfirst("*.*", &FindData);
	if (hFind == -1)
		return 0;

	do{
		if ( strcmp(FindData.name, ".") == 0 ||
		     strcmp(FindData.name, "..") == 0)
			continue;

		sprintf(szPath, "%s\\%s", pcszPath, FindData.name);
		if ( FindData.attrib & _A_SUBDIR ){
			if ( dir_func != NULL ){
				nRet = dir_func(szPath);
				if ( nRet == 0 )
					goto exit;
				else if ( nRet == 2 ){
					continue;
				}
			}

			nRet = visit_path_recursively(szPath, file_func, 
						      dir_func, dir_func2);
			if ( nRet == 0 )
				goto exit;
			
			if ( dir_func2 != NULL ){
				nRet = dir_func2(szPath);
				if ( nRet == 0 )
					goto exit;
			}
		}
		else{
            SetFileAttributesA(FindData.name, FILE_ATTRIBUTE_NORMAL);
			if ( file_func != NULL ){
				nRet = file_func( szPath );
				if ( nRet == 0 )
					goto exit;
			}
		}
	}while ( _findnext(hFind, &FindData) == 0 );

 exit:
	if ( _findclose(hFind) )
		write_log(LT_BOTH, "Error: Can't close directory %s!\n", 
			  pcszPath);
	
	return nRet;
#endif //WIN32
}
示例#17
0
文件: test2.c 项目: ArildF/masters
int __cdecl main(int argc, char *argv[])
{
    DWORD dwRc = 0;
    char szReturnedPath[_MAX_DIR+1];
    char szFullFileName[_MAX_DIR+1];
    LPSTR pPathPtr;
    HANDLE hFile = NULL;

    /* Initialize the PAL.
     */
    if (0 != PAL_Initialize(argc,argv))
    {
        return (FAIL);
    }

    /* change the directory */
    if (!SetCurrentDirectoryA(szDotDot))
    {
        Fail("ERROR: SetCurrentDirectoryA failed with error code %u"
             " when passed \"%s\".\n",
             GetLastError(),
             szDotDot);
    }

    /* Initialize the receiving char buffers.
     */
    memset(szReturnedPath, 0, _MAX_DIR+1);
    memset(szFullFileName, 0, _MAX_DIR+1);

    /* Create Full filename to pass, will include '..\'
     * as a pre-fix. */
    strcat(szFullFileName, szDotDot);
    strcat(szFullFileName, szFileName);

    /* Get the full path to the filename.
     */
    dwRc = GetFullPathNameA(szFullFileName, 
                            _MAX_DIR,
                            szReturnedPath, 
                            &pPathPtr);
    if (dwRc == 0)
    {
        Fail("ERROR :%ld: GetFullPathName failed to "
             "retrieve the path of \"%s\".\n",
             GetLastError(),
             szFileName);
    }

    /* The returned value should be the parent directory with the 
     * file name appended. */
    hFile = CreateFileA(szReturnedPath,
                        GENERIC_READ,
                        FILE_SHARE_READ,
                        NULL,
                        CREATE_ALWAYS,
                        FILE_ATTRIBUTE_NORMAL,
                        NULL);

    if (hFile == INVALID_HANDLE_VALUE)
    {
        Fail("ERROR :%ld: CreateFileA failed to create \"%s\".\n", 
             GetLastError(),
             szReturnedPath);
    }

    /* Close the handle to the created file.
     */
    if (CloseHandle(hFile) != TRUE)
    {
        Trace("ERROR :%ld: CloseHandle failed close hFile=0x%lx.\n",
             GetLastError());
        goto terminate;
    }

    /* Verify that the file was created, attempt to create 
     * the file again. */
    hFile = CreateFileA(szReturnedPath,
                        GENERIC_READ,
                        FILE_SHARE_READ,
                        NULL,
                        CREATE_NEW,
                        FILE_ATTRIBUTE_NORMAL,
                        NULL);
    if ((hFile != INVALID_HANDLE_VALUE) && 
        (GetLastError() != ERROR_ALREADY_EXISTS))
    {
        Fail("ERROR :%ld: CreateFileA succeeded to create file "
             "\"%s\", that already existed.\n",
             GetLastError(),
             szFullFileName);
    }


    /* Verify that the returned filename is the same as the supplied.
     */
    if (strcmp(pPathPtr, szFileName) != 0)
    {
        Trace("ERROR : Returned filename \"%s\" is not equal to "
             "supplied filename \"%s\".\n",
             pPathPtr, 
             szFileName);
        goto terminate;
    }

terminate:
    /* Delete the create file. 
     */
    if (DeleteFileA(szReturnedPath) != TRUE)
    {
        Fail("ERROR :%ld: DeleteFileA failed to delete \"%s\".\n",
             GetLastError(),
             szFileName);
    }

    /* Terminate the PAL.*/
    PAL_Terminate();
    return PASS;
}
 ~scoped_chdir()
 {
     SetCurrentDirectoryA(buffer);
 }
 scoped_chdir(const char* newDir)
 {
     GetCurrentDirectoryA(sizeof(buffer), buffer);
     SetCurrentDirectoryA(newDir);
 }
示例#20
0
文件: Mesh.cpp 项目: deedum/GLGame
//---------------------------------------------------------------------------------------
// メッシュ読込
//---------------------------------------------------------------------------------------
int LoadMesh(MESH *mesh, const char *fname)
{
	FILE		*fp;					// ファイルポインタ
	char		line[256];				// 読み込みバッファ
	char		*token;					// 単語へのポインタ
	const char	sep[] = " ,;{}\t\n";	// 区切り文字
	int			phase;					// 処理中の状態
	int			i, j;					// カウンタ
	char		szDir[_MAX_PATH];		// ドライブ名
	char		szFolder[_MAX_DIR];		// フォルダ名
	char		szCurrentDir[_MAX_PATH];// 現在のフォルダ
	int			n, t;					// ワーク

	// フォルダ名を抽出
	_splitpath(fname, szDir, szFolder, NULL, NULL);
	strcat(szDir, szFolder);

	phase = 0;							// データ先頭の検出
	fp = fopen(fname, "r");				// Xファイルオープン
	if (fp == NULL) {
//		printf("Xファイル\"%s\"が見つかりません。\n", fname);
		return 0;						// エラー終了
	}
	while (fgets(line, 256, fp)) {
		token = strtok(line, sep);
		while (token) {
			switch (phase) {
			case 0:						// データ先頭の抽出
				if (strcmp(token, "template") == 0) {
					while (strtok(NULL, sep));
					break;
				}
				if (strcmp(token, "Mesh") == 0) {
					phase = 1;
					break;
				}
				if (strcmp(token, "MeshNormals") == 0) {
					phase = 5;
					break;
				}
				if (strcmp(token, "MeshTextureCoords") == 0) {
					phase = 9;
					break;
				}
				if (strcmp(token, "MeshMaterialList") == 0) {
					phase = 11;
					break;
				}
				break;
			case 1:						// 頂点数取得
				mesh->vnum = atoi(token);
				mesh->vertex = (VECTOR3*)malloc(mesh->vnum * sizeof(VECTOR3));
				phase = 2;
				i = j = 0;
				break;
			case 2:						// 頂点座標読み込み
				mesh->vertex[i].f[j] = (float)atof(token);
				if (j == 2) mesh->vertex[i].f[j] *= -1.0f;
				j++;
				if (j >= 3) {
					j = 0;
					i++;
					if (i >= mesh->vnum)
						phase = 3;
				}
				break;
			case 3:						// 面数取得
				mesh->fnum = atoi(token);
				mesh->face = (int *)malloc(mesh->fnum * 5 * sizeof(int));
				phase = 4;
				i = j = 0;
				break;
			case 4:						// 面情報読み込み
				mesh->face[i * 5 + j] = atoi(token);	// 頂点数/インデックスを数値化
				j++;									// 読込数加算
				if (j > mesh->face[i * 5]) {			// 読込数が頂点数を超えた?
					n = mesh->face[i * 5];
					t = mesh->face[i * 5 + 1];			// 頂点の並びを反転
					mesh->face[i * 5 + 1] = mesh->face[i * 5 + n - 1];
					mesh->face[i * 5 + n - 1] = t;
					j = 0;								// 読込数をクリア
					i++;								// 読込面数加算
					if (i >= mesh->fnum)				// 読込面数が面数を超えた?
						phase = 0;						// データ先頭の抽出へ
				}
				break;
			case 5:						// 法線ベクトル数取得
				mesh->nnum = atoi(token);
				mesh->normal = (VECTOR3*)malloc(mesh->nnum * sizeof(VECTOR3));
				phase = 6;
				i = j = 0;
				break;
			case 6:						// 法線ベクトル読み込み
				mesh->normal[i].f[j] = (float)atof(token);
				if (j == 2) mesh->normal[i].f[j] *= -1.0f;
				j++;
				if (j >= 3) {
					j = 0;
					i++;
					if (i >= mesh->nnum)
						phase = 7;
				}
				break;
			case 7:						// 法線インデックス数取得
				mesh->inum = atoi(token);
				mesh->index = (int *)malloc(mesh->inum * 5 * sizeof(int));
				phase = 8;
				i = j = 0;
				break;
			case 8:						// 法線インデックス読込
				mesh->index[i * 5 + j] = atoi(token);	// 頂点数/インデックスを数値化
				j++;									// 読込数加算
				if (j > mesh->index[i * 5]) {			// 読込数が頂点数を超えた?
					n = mesh->index[i * 5];
					t = mesh->index[i * 5 + 1];			// 法線の並びを反転
					mesh->index[i * 5 + 1] = mesh->index[i * 5 + n - 1];
					mesh->index[i * 5 + n - 1] = t;
					j = 0;								// 読込数をクリア
					i++;								// 読込インデックス数加算
					if (i >= mesh->inum)				// 読込インデックス数がインデックス数を超えた?
						phase = 0;						// データ先頭の抽出へ
				}
				break;
			case 9:						// UV座標数取得(頂点数と同じはず)
				i = atoi(token);
				mesh->uv = (VECTOR2*)malloc(mesh->vnum * sizeof(VECTOR2));
				phase = 10;
				i = j = 0;
				break;
			case 10:					// UV座標読み込み
				mesh->uv[i].f[j] = (float)atof(token);
				if (j == 1) mesh->uv[i].f[j] = 1.0f - mesh->uv[i].f[j];
				j++;
				if (j >= 2) {
					j = 0;
					i++;
					if (i >= mesh->vnum)
						phase = 0;
				}
				break;
			case 11:					// 材質数取得
				mesh->mnum = atoi(token);
				mesh->material = (MATERIAL*)malloc(mesh->mnum * sizeof(MATERIAL));
				memset(mesh->material, 0, mesh->mnum * sizeof(MATERIAL));
				phase = 12;
				break;
			case 12:					// 材質インデックス数取得(面数と同じはず)
				i = atoi(token);
				mesh->midx = (int *)malloc(mesh->fnum * sizeof(int));
				i = 0;
				phase = 13;
				break;
			case 13:					// 材質インデックス読み込み
				mesh->midx[i] = (int)atoi(token);
				i++;
				if (i >= mesh->fnum) {
					i = 0;
					phase = 14;
				}
				break;
			case 14:					// 材質情報読み込み
				if (strcmp(token, "Material") == 0) {
					j = 0;
					phase = 15;
				} else {
					phase = 0;
					continue;
				}
				break;
			case 15:					// 拡散光/環境光
				mesh->material[i].diffuse.f[j] = (float)atof(token);
				j++;
				if (j >= 4)
					phase = 16;
				break;
			case 16:					// 鏡面光の指数
				mesh->material[i].power = (float)atof(token);
				j = 0;
				phase = 17;
				break;
			case 17:					// 鏡面光
				mesh->material[i].specular.f[j] = (float)atof(token);
				j++;
				if (j >= 3) {
					mesh->material[i].specular.a = 1.0f;
					j = 0;
					phase = 18;
				}
				break;
			case 18:					// 放射輝度
				mesh->material[i].emissive.f[j] = (float)atof(token);
				j++;
				if (j >= 3) {
					mesh->material[i].emissive.a = 1.0f;
					j = 0;
					phase = 19;
				}
				break;
			case 19:					// テクスチャ
				if (strcmp(token, "TextureFilename") == 0) {
					phase = 20;
					break;
				}
				if (strcmp(token, "Material") == 0) {
					i++;
					j = 0;
					phase = 15;
					break;
				}
				if (*token) {
					phase = 0;
					continue;
				}
				break;
			case 20:					// テクスチャ
				if (szDir[0]) {		// カレントディレクトリを変更
					GetCurrentDirectoryA(_MAX_PATH, szCurrentDir);
					SetCurrentDirectoryA(szDir);
				}
				mesh->material[i].textureID = LoadTexture(trim(token));
				if (szDir[0])		// カレントディレクトリを元に戻す
					SetCurrentDirectoryA(szCurrentDir);
				i++;
				if (i < mesh->mnum)
					phase = 14;
				else
					phase = 0;
				break;
			}
			token = strtok(NULL, sep);
		}
	}
	fclose(fp);							// Xファイルクローズ

	return 1;							// 正常終了
}
示例#21
0
/** This callback is called by windows when the service is started */
VOID ServiceMain(DWORD argc, LPCSTR *argv)
{
	g_ServiceStatusHandle = RegisterServiceCtrlHandler(TEXT("InspIRCd"), (LPHANDLER_FUNCTION)ServiceCtrlHandler);
	if( !g_ServiceStatusHandle )
		return;

	g_ServiceStatus.dwCheckPoint = 1;
	g_ServiceStatus.dwControlsAccepted = 0;
	g_ServiceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
	g_ServiceStatus.dwWaitHint = 5000;
	g_ServiceStatus.dwWin32ExitCode = NO_ERROR;
	g_ServiceStatus.dwCurrentState = SERVICE_START_PENDING;

	if( !SetServiceStatus( g_ServiceStatusHandle, &g_ServiceStatus ) )
		return;

	char szModuleName[MAX_PATH];
	if(GetModuleFileNameA(NULL, szModuleName, MAX_PATH))
	{
		if(!argc)
			argc = 1;

		g_ServiceData.argc = argc;

		// Note: since this memory is going to stay allocated for the rest of the execution,
		//		 it doesn't make sense to free it, as it's going to be "freed" on process termination
		try {
			g_ServiceData.argv = new char*[argc];

			uint32_t allocsize = strnlen_s(szModuleName, MAX_PATH) + 1;
			g_ServiceData.argv[0] = new char[allocsize];
			strcpy_s(g_ServiceData.argv[0], allocsize, szModuleName);

			for(uint32_t i = 1; i < argc; i++)
			{
				allocsize = strnlen_s(argv[i], MAX_PATH) + 1;
				g_ServiceData.argv[i] = new char[allocsize];
				strcpy_s(g_ServiceData.argv[i], allocsize, argv[i]);
			}

			*(strrchr(szModuleName, '\\') + 1) = NULL;
			SetCurrentDirectoryA(szModuleName);

			HANDLE hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)WorkerThread, NULL, 0, NULL);
			if (hThread != NULL)
			{
				WaitForSingleObject(hThread, INFINITE);
				CloseHandle(hThread);
			}
		}
		catch(...)
		{
			g_ServiceStatus.dwCurrentState = SERVICE_STOPPED;
			g_ServiceStatus.dwWin32ExitCode = ERROR_OUTOFMEMORY;
			SetServiceStatus( g_ServiceStatusHandle, &g_ServiceStatus );
		}
	}
	if(g_ServiceStatus.dwCurrentState == SERVICE_STOPPED)
		return;

	g_ServiceStatus.dwCurrentState = SERVICE_STOPPED;
	g_ServiceStatus.dwWin32ExitCode = GetLastError();
	SetServiceStatus( g_ServiceStatusHandle, &g_ServiceStatus );
}
示例#22
0
static void test_GetVolumeInformationA(void)
{
    BOOL ret;
    UINT result;
    char Root_Colon[]="C:";
    char Root_Slash[]="C:\\";
    char Root_UNC[]="\\\\?\\C:\\";
    char volume[MAX_PATH+1];
    DWORD vol_name_size=MAX_PATH+1, vol_serial_num=-1, max_comp_len=0, fs_flags=0, fs_name_len=MAX_PATH+1;
    char vol_name_buf[MAX_PATH+1], fs_name_buf[MAX_PATH+1];
    char windowsdir[MAX_PATH+10];
    char currentdir[MAX_PATH+1];

    ok( pGetVolumeInformationA != NULL, "GetVolumeInformationA not found\n");
    if(!pGetVolumeInformationA) {
        return;
    }

    /* get windows drive letter and update strings for testing */
    result = GetWindowsDirectoryA(windowsdir, sizeof(windowsdir));
    ok(result < sizeof(windowsdir), "windowsdir is abnormally long!\n");
    ok(result != 0, "GetWindowsDirectory: error %d\n", GetLastError());
    Root_Colon[0] = windowsdir[0];
    Root_Slash[0] = windowsdir[0];
    Root_UNC[4] = windowsdir[0];

    result = GetCurrentDirectoryA(MAX_PATH, currentdir);
    ok(result, "GetCurrentDirectory: error %d\n", GetLastError());
    /* Note that GetCurrentDir yields no trailing slash for subdirs */

    /* check for NO error on no trailing \ when current dir is root dir */
    ret = SetCurrentDirectoryA(Root_Slash);
    ok(ret, "SetCurrentDirectory: error %d\n", GetLastError());
    ret = pGetVolumeInformationA(Root_Colon, vol_name_buf, vol_name_size, NULL,
            NULL, NULL, fs_name_buf, fs_name_len);
    ok(ret, "GetVolumeInformationA root failed, last error %u\n", GetLastError());

    /* check for error on no trailing \ when current dir is subdir (windows) of queried drive */
    ret = SetCurrentDirectoryA(windowsdir);
    ok(ret, "SetCurrentDirectory: error %d\n", GetLastError());
    SetLastError(0xdeadbeef);
    ret = pGetVolumeInformationA(Root_Colon, vol_name_buf, vol_name_size, NULL,
            NULL, NULL, fs_name_buf, fs_name_len);
    ok(!ret && (GetLastError() == ERROR_INVALID_NAME),
        "GetVolumeInformationA did%s fail, last error %u\n", ret ? " not":"", GetLastError());

    /* reset current directory */
    ret = SetCurrentDirectoryA(currentdir);
    ok(ret, "SetCurrentDirectory: error %d\n", GetLastError());

    if (toupper(currentdir[0]) == toupper(windowsdir[0])) {
        skip("Please re-run from another device than %c:\n", windowsdir[0]);
        /* FIXME: Use GetLogicalDrives to find another device to avoid this skip. */
    } else {
        char Root_Env[]="=C:"; /* where MS maintains the per volume directory */
        Root_Env[1] = windowsdir[0];

        /* C:\windows becomes the current directory on drive C: */
        /* Note that paths to subdirs are stored without trailing slash, like what GetCurrentDir yields. */
        ret = SetEnvironmentVariableA(Root_Env, windowsdir);
        ok(ret, "SetEnvironmentVariable %s failed\n", Root_Env);

        ret = SetCurrentDirectoryA(windowsdir);
        ok(ret, "SetCurrentDirectory: error %d\n", GetLastError());
        ret = SetCurrentDirectoryA(currentdir);
        ok(ret, "SetCurrentDirectory: error %d\n", GetLastError());

        /* windows dir is current on the root drive, call fails */
        SetLastError(0xdeadbeef);
        ret = pGetVolumeInformationA(Root_Colon, vol_name_buf, vol_name_size, NULL,
                NULL, NULL, fs_name_buf, fs_name_len);
        ok(!ret && (GetLastError() == ERROR_INVALID_NAME),
           "GetVolumeInformationA did%s fail, last error %u\n", ret ? " not":"", GetLastError());

        /* Try normal drive letter with trailing \ */
        ret = pGetVolumeInformationA(Root_Slash, vol_name_buf, vol_name_size, NULL,
                NULL, NULL, fs_name_buf, fs_name_len);
        ok(ret, "GetVolumeInformationA with \\ failed, last error %u\n", GetLastError());

        ret = SetCurrentDirectoryA(Root_Slash);
        ok(ret, "SetCurrentDirectory: error %d\n", GetLastError());
        ret = SetCurrentDirectoryA(currentdir);
        ok(ret, "SetCurrentDirectory: error %d\n", GetLastError());

        /* windows dir is STILL CURRENT on root drive; the call fails as before,   */
        /* proving that SetCurrentDir did not remember the other drive's directory */
        SetLastError(0xdeadbeef);
        ret = pGetVolumeInformationA(Root_Colon, vol_name_buf, vol_name_size, NULL,
                NULL, NULL, fs_name_buf, fs_name_len);
        ok(!ret && (GetLastError() == ERROR_INVALID_NAME),
           "GetVolumeInformationA did%s fail, last error %u\n", ret ? " not":"", GetLastError());

        /* Now C:\ becomes the current directory on drive C: */
        ret = SetEnvironmentVariableA(Root_Env, Root_Slash); /* set =C:=C:\ */
        ok(ret, "SetEnvironmentVariable %s failed\n", Root_Env);

        /* \ is current on root drive, call succeeds */
        ret = pGetVolumeInformationA(Root_Colon, vol_name_buf, vol_name_size, NULL,
                NULL, NULL, fs_name_buf, fs_name_len);
        ok(ret, "GetVolumeInformationA failed, last error %u\n", GetLastError());

        /* again, SetCurrentDirectory on another drive does not matter */
        ret = SetCurrentDirectoryA(Root_Slash);
        ok(ret, "SetCurrentDirectory: error %d\n", GetLastError());
        ret = SetCurrentDirectoryA(currentdir);
        ok(ret, "SetCurrentDirectory: error %d\n", GetLastError());

        /* \ is current on root drive, call succeeds */
        ret = pGetVolumeInformationA(Root_Colon, vol_name_buf, vol_name_size, NULL,
                NULL, NULL, fs_name_buf, fs_name_len);
        ok(ret, "GetVolumeInformationA failed, last error %u\n", GetLastError());
    }

    /* try null root directory to return "root of the current directory"  */
    ret = pGetVolumeInformationA(NULL, vol_name_buf, vol_name_size, NULL,
            NULL, NULL, fs_name_buf, fs_name_len);
    ok(ret, "GetVolumeInformationA failed on null root dir, last error %u\n", GetLastError());

    /* Try normal drive letter with trailing \  */
    ret = pGetVolumeInformationA(Root_Slash, vol_name_buf, vol_name_size,
            &vol_serial_num, &max_comp_len, &fs_flags, fs_name_buf, fs_name_len);
    ok(ret, "GetVolumeInformationA failed, root=%s, last error=%u\n", Root_Slash, GetLastError());

    /* try again with drive letter and the "disable parsing" prefix */
    SetLastError(0xdeadbeef);
    ret = pGetVolumeInformationA(Root_UNC, vol_name_buf, vol_name_size,
            &vol_serial_num, &max_comp_len, &fs_flags, fs_name_buf, fs_name_len);
    ok(ret, "GetVolumeInformationA did%s fail, root=%s, last error=%u\n", ret ? " not":"", Root_UNC, GetLastError());

    /* try again with device name space  */
    Root_UNC[2] = '.';
    SetLastError(0xdeadbeef);
    ret = pGetVolumeInformationA(Root_UNC, vol_name_buf, vol_name_size,
            &vol_serial_num, &max_comp_len, &fs_flags, fs_name_buf, fs_name_len);
    ok(ret, "GetVolumeInformationA did%s fail, root=%s, last error=%u\n", ret ? " not":"", Root_UNC, GetLastError());

    /* try again with a directory off the root - should generate error  */
    if (windowsdir[strlen(windowsdir)-1] != '\\') strcat(windowsdir, "\\");
    SetLastError(0xdeadbeef);
    ret = pGetVolumeInformationA(windowsdir, vol_name_buf, vol_name_size,
            &vol_serial_num, &max_comp_len, &fs_flags, fs_name_buf, fs_name_len);
    ok(!ret && (GetLastError()==ERROR_DIR_NOT_ROOT),
          "GetVolumeInformationA did%s fail, root=%s, last error=%u\n", ret ? " not":"", windowsdir, GetLastError());
    /* A subdir with trailing \ yields DIR_NOT_ROOT instead of INVALID_NAME */
    if (windowsdir[strlen(windowsdir)-1] == '\\') windowsdir[strlen(windowsdir)-1] = 0;
    SetLastError(0xdeadbeef);
    ret = pGetVolumeInformationA(windowsdir, vol_name_buf, vol_name_size,
            &vol_serial_num, &max_comp_len, &fs_flags, fs_name_buf, fs_name_len);
    ok(!ret && (GetLastError()==ERROR_INVALID_NAME),
          "GetVolumeInformationA did%s fail, root=%s, last error=%u\n", ret ? " not":"", windowsdir, GetLastError());

    if (!pGetVolumeNameForVolumeMountPointA) {
        win_skip("GetVolumeNameForVolumeMountPointA not found\n");
        return;
    }
    /* get the unique volume name for the windows drive  */
    ret = pGetVolumeNameForVolumeMountPointA(Root_Slash, volume, MAX_PATH);
    ok(ret == TRUE, "GetVolumeNameForVolumeMountPointA failed\n");

    /* try again with unique volume name */
    ret = pGetVolumeInformationA(volume, vol_name_buf, vol_name_size,
            &vol_serial_num, &max_comp_len, &fs_flags, fs_name_buf, fs_name_len);
    ok(ret, "GetVolumeInformationA failed, root=%s, last error=%u\n", volume, GetLastError());
}
示例#23
0
int SimulatorWin::run()
{
    auto player = player::PlayerWin::create();

    INITCOMMONCONTROLSEX InitCtrls;
    InitCtrls.dwSize = sizeof(InitCtrls);
    InitCtrls.dwICC = ICC_WIN95_CLASSES;
    InitCommonControlsEx(&InitCtrls);

    parseCocosProjectConfig(_project);

    // load project config from command line args
    vector<string> args;
    for (int i = 0; i < __argc; ++i)
    {
        wstring ws(__wargv[i]);
        string s;
        s.assign(ws.begin(), ws.end());
        args.push_back(s);
    }
    _project.parseCommandLine(args);

    if (_project.getProjectDir().empty())
    {
        if (args.size() == 2)
        {
            // for Code IDE before RC2
            _project.setProjectDir(args.at(1));
            _project.setDebuggerType(kCCRuntimeDebuggerCodeIDE);
        }
    }

    // create the application instance
    _app = new AppDelegate();
    _app->setProjectConfig(_project);

    // create console window
    if (_project.isShowConsole())
    {
        AllocConsole();
        _hwndConsole = GetConsoleWindow();
        if (_hwndConsole != NULL)
        {
            ShowWindow(_hwndConsole, SW_SHOW);
            BringWindowToTop(_hwndConsole);
            freopen("CONOUT$", "wt", stdout);
            freopen("CONOUT$", "wt", stderr);

            HMENU hmenu = GetSystemMenu(_hwndConsole, FALSE);
            if (hmenu != NULL)
            {
                DeleteMenu(hmenu, SC_CLOSE, MF_BYCOMMAND);
            }
        }
    }

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

    // set environments
    SetCurrentDirectoryA(_project.getProjectDir().c_str());
    FileUtils::getInstance()->setDefaultResourceRootPath(_project.getProjectDir());
    FileUtils::getInstance()->setWritablePath(_project.getWritableRealPath().c_str());

    // check screen DPI
    HDC screen = GetDC(0);
    int dpi = GetDeviceCaps(screen, LOGPIXELSX);
    ReleaseDC(0, screen);

    // set scale with DPI
    //  96 DPI = 100 % scaling
    // 120 DPI = 125 % scaling
    // 144 DPI = 150 % scaling
    // 192 DPI = 200 % scaling
    // http://msdn.microsoft.com/en-us/library/windows/desktop/dn469266%28v=vs.85%29.aspx#dpi_and_the_desktop_scaling_factor
    //
    // enable DPI-Aware with DeclareDPIAware.manifest
    // http://msdn.microsoft.com/en-us/library/windows/desktop/dn469266%28v=vs.85%29.aspx#declaring_dpi_awareness
    float screenScale = 1.0f;
    if (dpi >= 120 && dpi < 144)
    {
        screenScale = 1.25f;
    }
    else if (dpi >= 144 && dpi < 192)
    {
        screenScale = 1.5f;
    }
    else if (dpi >= 192)
    {
        screenScale = 2.0f;
    }
    CCLOG("SCREEN DPI = %d, SCREEN SCALE = %0.2f", dpi, screenScale);

    // create opengl view
    Size frameSize = _project.getFrameSize();
    float frameScale = 1.0f;
    if (_project.isRetinaDisplay())
    {
        frameSize.width *= screenScale;
        frameSize.height *= screenScale;
    }
    else
    {
        frameScale = screenScale;
    }

    const Rect frameRect = Rect(0, 0, frameSize.width, frameSize.height);
    const bool isResize = _project.isResizeWindow();
    std::stringstream title;
    title << "Cocos Simulator - " << ConfigParser::getInstance()->getInitViewName();
    initGLContextAttrs();
    auto glview = GLViewImpl::createWithRect(title.str(), frameRect, frameScale);
    _hwnd = glview->getWin32Window();
    DragAcceptFiles(_hwnd, TRUE);
    //SendMessage(_hwnd, WM_SETICON, ICON_BIG, (LPARAM)icon);
    //SendMessage(_hwnd, WM_SETICON, ICON_SMALL, (LPARAM)icon);
    //FreeResource(icon);

    auto director = Director::getInstance();
    director->setOpenGLView(glview);

    director->setAnimationInterval(1.0 / 60.0);

    // set window position
    if (_project.getProjectDir().length())
    {
        setZoom(_project.getFrameScale()); 
    }
    Vec2 pos = _project.getWindowOffset();
    if (pos.x != 0 && pos.y != 0)
    {
        RECT rect;
        GetWindowRect(_hwnd, &rect);
        MoveWindow(_hwnd, pos.x, pos.y, rect.right - rect.left, rect.bottom - rect.top, FALSE);
    }

    // path for looking Lang file, Studio Default images
    FileUtils::getInstance()->addSearchPath(getApplicationPath().c_str());

    // init player services
    initServices();
    setupUI();
    DrawMenuBar(_hwnd);

    // prepare
    FileUtils::getInstance()->setPopupNotify(false);
    _project.dump();
    auto app = Application::getInstance();

    g_oldWindowProc = (WNDPROC)SetWindowLong(_hwnd, GWL_WNDPROC, (LONG)SimulatorWin::windowProc);

    // update window size
    RECT rect;
    GetWindowRect(_hwnd, &rect);
    MoveWindow(_hwnd, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top + GetSystemMetrics(SM_CYMENU), FALSE);

    // startup message loop
    return app->run();
}
示例#24
0
bool StartStage_AutoPatch::processMessage(unsigned int uiMsgID, void* pParam)
{
	WriteConWarning("Entry Proecess Message For C++\n");

	switch (uiMsgID)
	{
	case MSG_DOWNLOAD_URL:
		{
			NDMsg_DownloadUrl* pkUrl = (NDMsg_DownloadUrl*) pParam;
			m_bRequestedDownload = true;

			if (pkUrl->getMsgID() != uiMsgID)
			{
				return false;
			}

			if (!pkUrl->getNeedDownload())
			{
				setDone();
				return true;
			}

			m_pkStageUI->showProgress(true);

			const StringVector& kVec = pkUrl->getUrlVector();

#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
			char szExeFileName[500] = {0};
			GetModuleFileNameA(0, szExeFileName, sizeof(szExeFileName));
			string strCurrentDir = getPath(szExeFileName);
			SetCurrentDirectoryA(strCurrentDir.c_str());
			strCurrentDir.erase(strCurrentDir.end() - 1);
			strCurrentDir = getUpFolder(strCurrentDir);
#endif

			WriteConWarning("Will Download Patch From Server!\n");

			for (unsigned int uiIndex = 0; uiIndex < kVec.size(); uiIndex++)
			{
				const string& strUrl = kVec[uiIndex];

				if (0 == strUrl.size())
				{
					continue;
				}

				int nPos = strUrl.find_last_of('/');

				if (-1 == nPos)
				{
					continue;
				}

				string strFileName = strUrl.substr(nPos + 1, strUrl.length());

				DownloadPackage* pkPackage = new DownloadPackage;
				pkPackage->FromUrl(strUrl.c_str());

				string strPath = "";
				char szTempPath[2048] = { 0 };
				//SDCARD_GAME_NAME_SLASH
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
				strPath = string(SDCARD_GAME_NAME_SLASH) + strFileName;
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
				strPath = strCurrentDir + strFileName;
#endif

				WriteCon(
					"%d:%s will be download...Add to download task list.\n Save to %s...\n",
					uiIndex + 1, strUrl.c_str(), strPath.c_str());

				pkPackage->ToPath(strPath.c_str());
				pkPackage->setDownloadListener(this);

				m_kDownloadList.push_back(pkPackage);

				beginDownload();
			}
		}
		break;
	default:
		return false;
	}

	return true;
}
示例#25
0
void chdir_to_data_dir() {
    LONG    lReturnValue;
    HKEY    hkSetupHive;
    char    szPath[MAX_PATH];
    LPSTR   lpszValue = NULL;
    LPSTR   lpszExpandedValue = NULL;
    DWORD   dwValueType = REG_EXPAND_SZ;
    DWORD   dwSize = 0;

    // change the current directory to the boinc data directory if it exists
    lReturnValue = RegOpenKeyExA(
        HKEY_LOCAL_MACHINE, 
        "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 = RegQueryValueExA(
            hkSetupHive,
            "DATADIR",
            NULL,
            &dwValueType,
            NULL,
            &dwSize
        );
        if (lReturnValue != ERROR_FILE_NOT_FOUND) {
            // Allocate the buffer space.
            lpszValue = (LPSTR) malloc(dwSize);
            (*lpszValue) = NULL;

            // Now get the data
            lReturnValue = RegQueryValueExA( 
                hkSetupHive,
                "DATADIR",
                NULL,
                &dwValueType,
                (LPBYTE)lpszValue,
                &dwSize
            );

            // Expand the Strings
            // We need to get the size of the buffer needed
            dwSize = 0;
            lReturnValue = ExpandEnvironmentStringsA(lpszValue, NULL, dwSize);
   
            if (lReturnValue) {
                // Make the buffer big enough for the expanded string
                lpszExpandedValue = (LPSTR) malloc(lReturnValue);
                (*lpszExpandedValue) = NULL;
                dwSize = lReturnValue;
   
                ExpandEnvironmentStringsA(lpszValue, lpszExpandedValue, dwSize);

                SetCurrentDirectoryA(lpszExpandedValue);
            }
        }
    } else {
        if (SUCCEEDED(SHGetFolderPathA(NULL, CSIDL_COMMON_APPDATA|CSIDL_FLAG_CREATE, NULL, SHGFP_TYPE_CURRENT, szPath))) {
            strncat(szPath, "\\boinc", (sizeof(szPath) - strlen(szPath)));
            if (boinc_file_exists(szPath)) {
                SetCurrentDirectoryA(szPath);
            }
        }
    }

    if (hkSetupHive) RegCloseKey(hkSetupHive);
    if (lpszValue) free(lpszValue);
    if (lpszExpandedValue) free(lpszExpandedValue);
}
示例#26
0
文件: gvwmisc.c 项目: 131/gsview
/* change directory and drive */
int
gs_chdir(char *dirname)
{
    return !SetCurrentDirectoryA(dirname);
}
示例#27
0
文件: directory.c 项目: AmesianX/wine
static void test_CreateDirectoryA(void)
{
    char tmpdir[MAX_PATH];
    WCHAR curdir[MAX_PATH];
    BOOL ret;

    ret = CreateDirectoryA(NULL, NULL);
    ok(ret == FALSE && (GetLastError() == ERROR_PATH_NOT_FOUND ||
                        GetLastError() == ERROR_INVALID_PARAMETER),
       "CreateDirectoryA(NULL): ret=%d err=%d\n", ret, GetLastError());

    ret = CreateDirectoryA("", NULL);
    ok(ret == FALSE && (GetLastError() == ERROR_BAD_PATHNAME ||
                        GetLastError() == ERROR_PATH_NOT_FOUND),
       "CreateDirectoryA(%s): ret=%d err=%d\n", tmpdir, ret, GetLastError());

    ret = GetSystemDirectoryA(tmpdir, MAX_PATH);
    ok(ret < MAX_PATH, "System directory should fit into MAX_PATH\n");

    GetCurrentDirectoryW(MAX_PATH, curdir);
    ret = SetCurrentDirectoryA(tmpdir);
    ok(ret == TRUE, "could not chdir to the System directory\n");

    ret = CreateDirectoryA(".", NULL);
    ok(ret == FALSE && GetLastError() == ERROR_ALREADY_EXISTS,
       "CreateDirectoryA(%s): ret=%d err=%d\n", tmpdir, ret, GetLastError());


    ret = CreateDirectoryA("..", NULL);
    ok(ret == FALSE && GetLastError() == ERROR_ALREADY_EXISTS,
       "CreateDirectoryA(%s): ret=%d err=%d\n", tmpdir, ret, GetLastError());

    GetTempPathA(MAX_PATH, tmpdir);
    tmpdir[3] = 0; /* truncate the path */
    ret = CreateDirectoryA(tmpdir, NULL);
    ok(ret == FALSE && (GetLastError() == ERROR_ALREADY_EXISTS ||
                        GetLastError() == ERROR_ACCESS_DENIED),
       "CreateDirectoryA(%s): ret=%d err=%d\n", tmpdir, ret, GetLastError());

    GetTempPathA(MAX_PATH, tmpdir);
    lstrcatA(tmpdir, "Please Remove Me");
    ret = CreateDirectoryA(tmpdir, NULL);
    ok(ret == TRUE,       "CreateDirectoryA(%s) failed err=%d\n", tmpdir, GetLastError());

    ret = CreateDirectoryA(tmpdir, NULL);
    ok(ret == FALSE && GetLastError() == ERROR_ALREADY_EXISTS,
       "CreateDirectoryA(%s): ret=%d err=%d\n", tmpdir, ret, GetLastError());

    ret = RemoveDirectoryA(tmpdir);
    ok(ret == TRUE,
       "RemoveDirectoryA(%s) failed err=%d\n", tmpdir, GetLastError());


    lstrcatA(tmpdir, "?");
    ret = CreateDirectoryA(tmpdir, NULL);
    ok(ret == FALSE && (GetLastError() == ERROR_INVALID_NAME ||
			GetLastError() == ERROR_PATH_NOT_FOUND),
       "CreateDirectoryA(%s): ret=%d err=%d\n", tmpdir, ret, GetLastError());
    RemoveDirectoryA(tmpdir);

    tmpdir[lstrlenA(tmpdir) - 1] = '*';
    ret = CreateDirectoryA(tmpdir, NULL);
    ok(ret == FALSE && (GetLastError() == ERROR_INVALID_NAME ||
			GetLastError() == ERROR_PATH_NOT_FOUND),
       "CreateDirectoryA(%s): ret=%d err=%d\n", tmpdir, ret, GetLastError());
    RemoveDirectoryA(tmpdir);

    GetTempPathA(MAX_PATH, tmpdir);
    lstrcatA(tmpdir, "Please Remove Me/Please Remove Me");
    ret = CreateDirectoryA(tmpdir, NULL);
    ok(ret == FALSE && GetLastError() == ERROR_PATH_NOT_FOUND, 
       "CreateDirectoryA(%s): ret=%d err=%d\n", tmpdir, ret, GetLastError());
    RemoveDirectoryA(tmpdir);

    /* Test behavior with a trailing dot.
     * The directory should be created without the dot.
     */
    GetTempPathA(MAX_PATH, tmpdir);
    lstrcatA(tmpdir, "Please Remove Me.");
    ret = CreateDirectoryA(tmpdir, NULL);
    ok(ret == TRUE,
       "CreateDirectoryA(%s) failed err=%d\n", tmpdir, GetLastError());

    lstrcatA(tmpdir, "/Please Remove Me");
    ret = CreateDirectoryA(tmpdir, NULL);
    ok(ret == TRUE,
       "CreateDirectoryA(%s) failed err=%d\n", tmpdir, GetLastError());
    ret = RemoveDirectoryA(tmpdir);
    ok(ret == TRUE,
       "RemoveDirectoryA(%s) failed err=%d\n", tmpdir, GetLastError());

    GetTempPathA(MAX_PATH, tmpdir);
    lstrcatA(tmpdir, "Please Remove Me");
    ret = RemoveDirectoryA(tmpdir);
    ok(ret == TRUE,
       "RemoveDirectoryA(%s) failed err=%d\n", tmpdir, GetLastError());

    /* Test behavior with two trailing dots.
     * The directory should be created without the trailing dots.
     */
    GetTempPathA(MAX_PATH, tmpdir);
    lstrcatA(tmpdir, "Please Remove Me..");
    ret = CreateDirectoryA(tmpdir, NULL);
    ok(ret == TRUE,
       "CreateDirectoryA(%s) failed err=%d\n", tmpdir, GetLastError());

    lstrcatA(tmpdir, "/Please Remove Me");
    ret = CreateDirectoryA(tmpdir, NULL);
    ok(ret == TRUE || /* On Win98 */
       (ret == FALSE && GetLastError() == ERROR_PATH_NOT_FOUND), /* On NT! */
       "CreateDirectoryA(%s): ret=%d err=%d\n", tmpdir, ret, GetLastError());
    if (ret == TRUE)
    {
        ret = RemoveDirectoryA(tmpdir);
        ok(ret == TRUE,
           "RemoveDirectoryA(%s) failed err=%d\n", tmpdir, GetLastError());
    }

    GetTempPathA(MAX_PATH, tmpdir);
    lstrcatA(tmpdir, "Please Remove Me");
    ret = RemoveDirectoryA(tmpdir);
    ok(ret == TRUE,
       "RemoveDirectoryA(%s) failed err=%d\n", tmpdir, GetLastError());

    /* Test behavior with a trailing space.
     * The directory should be created without the trailing space.
     */
    GetTempPathA(MAX_PATH, tmpdir);
    lstrcatA(tmpdir, "Please Remove Me ");
    ret = CreateDirectoryA(tmpdir, NULL);
    ok(ret == TRUE,
       "CreateDirectoryA(%s) failed err=%d\n", tmpdir, GetLastError());

    lstrcatA(tmpdir, "/Please Remove Me");
    ret = CreateDirectoryA(tmpdir, NULL);
    ok(ret == TRUE || /* On Win98 */
       (ret == FALSE && GetLastError() == ERROR_PATH_NOT_FOUND), /* On NT! */
       "CreateDirectoryA(%s): ret=%d err=%d\n", tmpdir, ret, GetLastError());
    if (ret == TRUE)
    {
        ret = RemoveDirectoryA(tmpdir);
        ok(ret == TRUE,
           "RemoveDirectoryA(%s) failed err=%d\n", tmpdir, GetLastError());
    }

    GetTempPathA(MAX_PATH, tmpdir);
    lstrcatA(tmpdir, "Please Remove Me");
    ret = RemoveDirectoryA(tmpdir);
    ok(ret == TRUE,
       "RemoveDirectoryA(%s) failed err=%d\n", tmpdir, GetLastError());

    /* Test behavior with a trailing space.
     * The directory should be created without the trailing spaces.
     */
    GetTempPathA(MAX_PATH, tmpdir);
    lstrcatA(tmpdir, "Please Remove Me  ");
    ret = CreateDirectoryA(tmpdir, NULL);
    ok(ret == TRUE,
       "CreateDirectoryA(%s) failed err=%d\n", tmpdir, GetLastError());

    lstrcatA(tmpdir, "/Please Remove Me");
    ret = CreateDirectoryA(tmpdir, NULL);
    ok(ret == TRUE || /* On Win98 */
       (ret == FALSE && GetLastError() == ERROR_PATH_NOT_FOUND), /* On NT! */
       "CreateDirectoryA(%s): ret=%d err=%d\n", tmpdir, ret, GetLastError());
    if (ret == TRUE)
    {
        ret = RemoveDirectoryA(tmpdir);
        ok(ret == TRUE,
           "RemoveDirectoryA(%s) failed err=%d\n", tmpdir, GetLastError());
    }

    GetTempPathA(MAX_PATH, tmpdir);
    lstrcatA(tmpdir, "Please Remove Me");
    ret = RemoveDirectoryA(tmpdir);
    ok(ret == TRUE,
       "RemoveDirectoryA(%s) failed err=%d\n", tmpdir, GetLastError());
    SetCurrentDirectoryW(curdir);
}
示例#28
0
/*++
Function:
  SetCurrentDirectoryW

See MSDN doc.
--*/
BOOL
PALAPI
SetCurrentDirectoryW(
            IN LPCWSTR lpPathName)
{
    BOOL bRet;
    DWORD dwLastError = 0;
    PathCharString dirPathString;
    int  size;
    size_t length;
    char * dir;
    
    PERF_ENTRY(SetCurrentDirectoryW);
    ENTRY("SetCurrentDirectoryW(lpPathName=%p (%S))\n",
          lpPathName?lpPathName:W16_NULLSTRING,
          lpPathName?lpPathName:W16_NULLSTRING);

   /*check if the given path is null. If so
     return FALSE*/
    if (lpPathName == NULL )
    {
        ERROR("Invalid path/directory name\n");
        dwLastError = ERROR_INVALID_NAME;
        bRet = FALSE;
        goto done;
    }

    length = (PAL_wcslen(lpPathName)+1) * 3;
    dir = dirPathString.OpenStringBuffer(length);
    if (NULL == dir)
    {
        dwLastError = ERROR_NOT_ENOUGH_MEMORY;
        bRet = FALSE;
        goto done;
    }
    
    size = WideCharToMultiByte( CP_ACP, 0, lpPathName, -1, dir, length,
                                NULL, NULL );
    dirPathString.CloseBuffer(size);
    
    if( size == 0 )
    {
        dwLastError = GetLastError();
        if( dwLastError == ERROR_INSUFFICIENT_BUFFER )
        {
            WARN("lpPathName is larger than MAX_LONGPATH (%d)!\n", MAX_LONGPATH);
            dwLastError = ERROR_FILENAME_EXCED_RANGE;
        }
        else
        {
            ASSERT("WideCharToMultiByte failure! error is %d\n", dwLastError);
            dwLastError = ERROR_INTERNAL_ERROR;
        }
        bRet = FALSE;
        goto done;
    }

    bRet = SetCurrentDirectoryA(dir);
done:
    if( dwLastError )
    {
        SetLastError(dwLastError);
    }

    LOGEXIT("SetCurrentDirectoryW returns BOOL %d\n", bRet);
    PERF_EXIT(SetCurrentDirectoryW);
    return bRet;
}
示例#29
0
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
int main(int argc, char **argv)
{
#if _WIN32
	char current_path[MAX_PATH + 1];
	GetDirectoryName(current_path, argv[0]);
	SetCurrentDirectoryA(current_path);
#endif

	InitWindow();

	// 描画用インスタンスの生成
	g_renderer = ::EffekseerRendererDX9::Renderer::Create( g_d3d_device, 2000 );
	
	// Specify a distortion function
	// 歪み機能を設定

	// If you'd like to distort background and particles by rendering, it need to specify it.
	// It is a bit heavy
	// もし、描画するごとに背景とパーティクルを歪ませたい場合、設定する必要がある
	// やや重い
	g_renderer->SetDistortingCallback(new DistortingCallback());

	// 背景バッファの生成
	g_d3d_device->CreateTexture(
		640,
		480,
		1,
		D3DUSAGE_RENDERTARGET,
		D3DFMT_A8R8G8B8,
		D3DPOOL_DEFAULT,
		&g_backgroundTexture,
		NULL
		);

	g_backgroundTexture->GetSurfaceLevel(0, &g_backgroundSurface);

	// エフェクト管理用インスタンスの生成
	g_manager = ::Effekseer::Manager::Create( 2000 );

	// 描画用インスタンスから描画機能を設定
	g_manager->SetSpriteRenderer( g_renderer->CreateSpriteRenderer() );
	g_manager->SetRibbonRenderer( g_renderer->CreateRibbonRenderer() );
	g_manager->SetRingRenderer( g_renderer->CreateRingRenderer() );
	g_manager->SetTrackRenderer(g_renderer->CreateTrackRenderer());
	g_manager->SetModelRenderer( g_renderer->CreateModelRenderer() );
	
	// 描画用インスタンスからテクスチャの読込機能を設定
	// 独自拡張可能、現在はファイルから読み込んでいる。
	g_manager->SetTextureLoader( g_renderer->CreateTextureLoader() );
	g_manager->SetModelLoader( g_renderer->CreateModelLoader() );

	// 音再生用インスタンスの生成
	g_sound = ::EffekseerSound::Sound::Create( g_xa2, 16, 16 );

	// 音再生用インスタンスから再生機能を指定
	g_manager->SetSoundPlayer( g_sound->CreateSoundPlayer() );
	
	// 音再生用インスタンスからサウンドデータの読込機能を設定
	// 独自拡張可能、現在はファイルから読み込んでいる。
	g_manager->SetSoundLoader( g_sound->CreateSoundLoader() );

	// 視点位置を確定
	g_position = ::Effekseer::Vector3D(10.0f, 5.0f, 20.0f) * 0.25;

	// 投影行列を設定
	g_renderer->SetProjectionMatrix(
		::Effekseer::Matrix44().PerspectiveFovRH(90.0f / 180.0f * 3.14f, (float)g_window_width / (float)g_window_height, 1.0f, 50.0f));

	// カメラ行列を設定
	g_renderer->SetCameraMatrix(
		::Effekseer::Matrix44().LookAtRH(g_position, ::Effekseer::Vector3D(0.0f, 0.0f, 0.0f), ::Effekseer::Vector3D(0.0f, 1.0f, 0.0f)));

	// エフェクトの読込
	g_effect = Effekseer::Effect::Create(g_manager, (const EFK_CHAR*)L"distortion.efk");

	// エフェクトの再生
	g_handle = g_manager->Play(g_effect, 0, 0, 0);
	
	MainLoop();

	// エフェクトの停止
	g_manager->StopEffect(g_handle);

	// エフェクトの破棄
	ES_SAFE_RELEASE(g_effect);

	// 先にエフェクト管理用インスタンスを破棄
	g_manager->Destroy();

	// 次に音再生用インスタンスを破棄
	g_sound->Destroy();

	// 次に描画用インスタンスを破棄
	g_renderer->Destroy();

	// XAudio2の解放
	if( g_xa2_master != NULL )
	{
		g_xa2_master->DestroyVoice();
		g_xa2_master = NULL;
	}
	ES_SAFE_RELEASE( g_xa2 );

	// バックバッファの破棄
	ES_SAFE_RELEASE( g_backgroundTexture );
	ES_SAFE_RELEASE( g_backgroundSurface );

	// DirectXの解放
	ES_SAFE_RELEASE( g_d3d_device );
	ES_SAFE_RELEASE( g_d3d );

	// COMの終了処理
	CoUninitialize();

	return 0;
}
示例#30
0
i32 RCMain()
{
	i32 bail = 0;
#ifdef WIN32
	while (!SetCurrentDirectoryA(RC_RESOURCE_PATH) && SetCurrentDirectoryA("..")) {
		bail++;
		if (bail >= 32) {
			printf("Can't find resource folder. Build directory must be located further down in the hierarchy than /res/\n");
			exit(0);
		}
	}
	SetCurrentDirectoryA("..");
#else
    char *fbuf = __FILE__;
    char fpath [8192];
    char *epos = strrchr(fbuf, '/');
    strncpy(fpath, fbuf, (epos - fbuf));
    fpath[(epos - fbuf)] = 0;
    chdir(fpath);
    while (chdir(RC_RESOURCE_PATH) != 0 && chdir("..") == 0) {
		bail++;
		if (bail >= 32) {
			printf("Can't find resource folder. Build directory must be located further down in the hierarchy than /res/\n");
			exit(0);
		}
	}
	chdir("..");
#endif

	char buf[4096];
	
	printf("Result setup...\n");
	ResultInit();
	printf("Done\n");

	printf("Display setup...\n");
	Platform::setDisplay(false, RC_DEFAULT_DISPLAY_WIDTH, RC_DEFAULT_DISPLAY_HEIGHT);
	printf("Done\n");

	printf("Renderer init...\n");
	Renderer::init();
	printf("Done\n");
	
	printf("SceneGraph setup...\n");
	SceneGraph::init();
	printf("Done\n");

	printf("Console setup...\n");
	Console::init();
	printf("Done\n");

	printf("Command setup...\n");
	Command::init();
	printf("Done\n");

	printf("Frame init...\n");
	Platform::initFrame();
	printf("Done\n");

	Console::log("~c9995=============================");
	Console::log("~c3939~g3939   _");
	Console::log("~c3939~g6969  c \"     ~r-[ RenderChimp ]-");
	Console::log("~c6969~g9999   (-       ~r-[ v 0.3.2a ]-\n ");
	Console::log("~c9995=============================\n \n ");
	//Console::log("~c9995Press ~c6966F1~c9995 to bring up the console.");
	Console::log("~c9995Press F1 to bring up the console.");

	sprintf(buf, "/config %sconfig/config.cfg", RC_RESOURCE_PATH);
	Command::run(buf);

#if defined RC_WIN32
	Console::log("Running on Win32 platform");
#else
	Console::log("Running on some platform");
#endif

	printf("Running RCInit...\n");
	RCInit();
	printf("Done\n");

	Console::log("Initiated...");

	rs.enableDepthTest(CMP_LESS);
	rs.enableDepthWrite();

	printf("Running main loop...\n");
	Platform::run();

	return 0;
}