Esempio n. 1
0
// WINDOWS MAIN FUNCTION
// hInst = current instance of the program
// hPrevInst = previous instance which is not used anymore.
// cmdLine = holds command line arguments to be passed in to the program
// cmdShow = holds an integer to specify if we want to show this window.
int CALLBACK WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR cmdLine, int cmdShow)
{
    WNDCLASS wc = {0};
    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.hInstance = hInst;
    wc.hbrBackground = (HBRUSH)COLOR_WINDOW;
    wc.lpszClassName = wndClassName;
    wc.hCursor = 0; //TODO: Add cursors and icons to this program.
    wc.hIcon = 0;
    wc.lpfnWndProc = (WNDPROC)wndProc;

    RegisterClass(&wc);

    HWND window = CreateWindow(wndClassName, wndTitle,
                               WS_OVERLAPPEDWINDOW,
                               CW_USEDEFAULT, CW_USEDEFAULT,
                               wndWidth, wndHeight,
                               0, 0, hInst, 0);
    
    if(window)
    {
        ShowWindow(window, SW_SHOW);
        UpdateWindow(window);

        // NOTE: Initializing SDL
        if(SDL_Init(SDL_INIT_VIDEO) != 0 )
        {
            DestroyWindow(window);
            return -2;
        }

        IMG_Init(IMG_INIT_JPG | IMG_INIT_PNG);
        
        sdlWindow = SDL_CreateWindowFrom((void*)window);

        char error[MAX_PATH];
        stringCopy(error, SDL_GetError());
        OutputDebugStringA(error);

        if(!sdlWindow)
        {
            SDL_Quit();
            DestroyWindow(window);
            return -3;
        }
        
        renderer = SDL_CreateRenderer(sdlWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);

        if(!renderer)
        {
            SDL_DestroyWindow(sdlWindow);
            SDL_Quit();
            DestroyWindow(window);
            return -4;
        }

        i32 RefreshRate = 0;
        HDC dc = GetDC(window);
        i32 winRefreshRate = GetDeviceCaps(dc, VREFRESH);

        if( winRefreshRate > 1 )
        {
            RefreshRate = winRefreshRate / 2;
        }
        else
        {
            RefreshRate = 30;
        }

        r32 targetSecsPerFrame = 1.0f / RefreshRate;

        GameMemory memory = {};
        memory.permanentSize = Megabytes(64);
        memory.transientSize = Megabytes(64);
        memory.totalSize = memory.permanentSize + memory.transientSize;
        
        gameMemoryBlock = VirtualAlloc( 0, memory.totalSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);

        if(!gameMemoryBlock)
        {
            SDL_DestroyRenderer(renderer);
            SDL_DestroyWindow(sdlWindow);
            SDL_Quit();
            DestroyWindow(window);
            return -5;
        }

        memory.permanentBlock = gameMemoryBlock;
        memory.transientBlock = (i8*)gameMemoryBlock + memory.permanentSize;
        memory.readEntireFile = ReadEntireFile;
        memory.freeFile = FreeFile;
        memory.writeEntireFile = WriteEntireFile;

        Win32Dims windowDims = GetWindowDimensions(window);
        
        Render render = {};
        render.renderer = renderer;
        render.screenW = windowDims.width;
        render.screenH = windowDims.height;
        
        GameController input = {0};
        input.dt = targetSecsPerFrame;
        
        Win32State state = {0};
        state.memoryBlock = gameMemoryBlock;
        state.memorySize = memory.totalSize;

        GameCodeDLL gameCode =  Win32LoadGameCode("Game.dll", "Game_temp.dll", "lock.tmp");
        
        isRunning = true;

        r32 sleepIsGranular = (timeBeginPeriod(1) == TIMERR_NOERROR);
        
        LARGE_INTEGER lastCounter = Win32GetClock();

        i64 lastCycles = __rdtsc();
        
        LARGE_INTEGER performanceFreqPerSecRes;
        QueryPerformanceFrequency(&performanceFreqPerSecRes);
        globalPerformanceCountFreq = performanceFreqPerSecRes.QuadPart;
        
        // NOTE: PROGRAM LOOP!!
        while(isRunning)
        {
            // NOTE: compare File times for us to be able to reload the new game code
            FILETIME currentFileTime = Win32GetLastWriteTime("Game.dll");
            if(CompareFileTime(&currentFileTime, &gameCode.lastWriteTime) != 0)
            {
                Win32UnloadGameCode(&gameCode);
                gameCode = Win32LoadGameCode("Game.dll", "Game_temp.dll", "lock.tmp");
            }
            
            MSG msg = {0};
            while(PeekMessage(&msg, window, 0, 0, PM_REMOVE))
            {
                switch(msg.message)
                {
                    case WM_CLOSE:
                    {
                        isRunning = false;
                    }break;

                    case WM_KEYUP:
                    case WM_KEYDOWN:
                    case WM_SYSKEYUP:
                    case WM_SYSKEYDOWN:
                    {
                        u32 vkCode = (u32)msg.wParam;   // This contains the keycode for the key that the user pressed.
                        bool isDown = ((msg.lParam & (1 << 31)) == 0);  // Check to see if the key is down now.
                        bool wasDown = ((msg.lParam & (1 << 30)) != 0); // Check to see if the key was down previously.

                        if(isDown != wasDown)
                        {
                            if(vkCode == 'W')
                            {
                                input.moveUp.isDown = isDown;
                            }
                            else if(vkCode == 'S')
                            {
                                input.moveDown.isDown = isDown;
                            }
                            else if(vkCode == 'A')
                            {
                                input.moveLeft.isDown = isDown;
                            }
                            else if(vkCode == 'D')
                            {
                                input.moveRight.isDown = isDown;
                            }
                            if(vkCode == VK_UP)
                            {
                                input.actionUp.isDown = isDown;
                            }
                            else if(vkCode == VK_DOWN)
                            {
                                input.actionDown.isDown = isDown;
                            }
                            else if(vkCode == VK_LEFT)
                            {
                                input.actionLeft.isDown = isDown;
                            }
                            else if(vkCode == VK_RIGHT)
                            {
                                input.actionRight.isDown = isDown;
                            }
                            else if(vkCode == VK_ESCAPE)
                            {
                                input.back.isDown = isDown;
                            }
                            else if(vkCode == 'O')
                            {
                                if(isDown)
                                {
                                    if(state.recordingIndex == 0)
                                    {
                                        BeginRecording(&state, 1);
                                    }
                                    else
                                    {
                                        EndRecording(&state);
                                        BeginPlayback(&state, 1);
                                    }
                                }
                            }
                            else if(vkCode == 'P')
                            {
                                if(isDown)
                                {
                                    if(state.playbackIndex > 0)
                                    {
                                        EndPlayback(&state);
                                        ZeroMemory(&input, sizeof(input));
                                    }
                                }
                            }
                        }

                        if(isDown)
                        {
                            bool AltKeyWasDown = ((msg.lParam & (1 << 29)) != 0);
                            if(vkCode == VK_RETURN && AltKeyWasDown)
                            {
                                if(msg.hwnd)
                                {
                                    isFullscreen = !isFullscreen;
                                    Win32FullscreenToggle(msg.hwnd);
                                }
                            }
                        }

                    }break;

                    default:
                    {
                        TranslateMessage(&msg);
                        DispatchMessage(&msg);
                    }
                }
            }

            if(input.back.isDown)
            {
                isRunning = false;
                PostQuitMessage(0);
            }

            if(state.recordingIndex > 0)
            {
                RecordingInput(&state, &input);
            }
            else if(state.playbackIndex > 0)
            {
                PlaybackInput(&state, &input);
            }

            Win32Dims windowDims = GetWindowDimensions(window);
            Win32UpdateWindow(windowDims, (i32*)&render.screenW, (i32*)&render.screenH);
            
            if(gameCode.UpdateRender)
            {
                gameCode.UpdateRender(&memory, &input, &render);
            }

            LARGE_INTEGER workCounter = Win32GetClock();
            r32 workSecsElapsed = Win32GetSecondsElapsed(lastCounter, workCounter);

            r32 secondsElapsed = workSecsElapsed;
            if(secondsElapsed < targetSecsPerFrame)
            {
                if(sleepIsGranular)
                {
                    DWORD sleepMS = (DWORD)(1000.0f * (targetSecsPerFrame - secondsElapsed));
                    if(sleepMS > 0)
                    {
                        Sleep(sleepMS);
                    }
                }

                r32 testSecsElapsed = Win32GetSecondsElapsed(lastCounter, Win32GetClock());
                if(testSecsElapsed < targetSecsPerFrame)
                {
                    //TODO: LOG MISSED SLEEP HERE!!
                }

                while(secondsElapsed < targetSecsPerFrame)
                {
                    secondsElapsed = Win32GetSecondsElapsed(lastCounter, Win32GetClock());
                }
            }
            else
            {
                //TODO: MISSED FRAME RATE!!
            }
            
            LARGE_INTEGER endCounter = Win32GetClock();

            i64 endCycles = __rdtsc();
            
            r64 elapsedCounts = (r64)(endCounter.QuadPart - lastCounter.QuadPart);
            r64 elapsedCycles = (r64)(endCycles - lastCycles);

            r32 MSperFrame = ((1000.0f * Win32GetSecondsElapsed(lastCounter, endCounter)));
            r32 FPS = (r32)(globalPerformanceCountFreq / elapsedCounts);
            r32 MegaCyclesPerFrame = (r32)(elapsedCycles / (1000.0f * 1000.0f));
            
            char buffer[256];
            sprintf_s(buffer, "%.02fms, %.02ffps, %.02fmcpf\n", MSperFrame, FPS, MegaCyclesPerFrame);            
            OutputDebugStringA(buffer);
            
            lastCounter = endCounter;
            lastCycles = endCycles;
            
        } // NOTE: END OF WHILE LOOP

        //IMPORTANT: Unload this when we exit the program.
        Win32UnloadGameCode(&gameCode);        
    }
    else
    {
        // TODO: Handle Error Loggin here!!
        return -1;
    }

    if(gameMemoryBlock)
    {
        VirtualFree(gameMemoryBlock, 0, MEM_RELEASE);
    }
    
    //Close
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(sdlWindow);
    IMG_Quit();
    SDL_Quit();
    DestroyWindow(window);

    return 0;
}
Esempio n. 2
0
int PluginClass::GetFindData(PluginPanelItem **pPanelItem,int *pItemsNumber,int OpMode)
{
  HANDLE ArcFindHandle;
  WIN32_FIND_DATA NewArcFindData;
  ArcFindHandle=FindFirstFile(ArcName,&NewArcFindData);
  FindClose(ArcFindHandle);

  if (ArcFindHandle==INVALID_HANDLE_VALUE)
    return FALSE;

  if (CompareFileTime(&NewArcFindData.ftLastWriteTime,&ArcFindData.ftLastWriteTime)!=0 ||
      NewArcFindData.nFileSizeLow!=ArcFindData.nFileSizeLow || ArcData==NULL)
  {
    BOOL ReadArcOK=FALSE;
    DWORD size = (DWORD)Info.AdvControl(Info.ModuleNumber,ACTL_GETPLUGINMAXREADDATA,(void *)0);
    HANDLE h=CreateFile(ArcName, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
    if (h!=INVALID_HANDLE_VALUE)
    {
      unsigned char *Data=new unsigned char[size];
      DWORD read;
      int ret = ReadFile(h, Data, size, &read, 0);
      CloseHandle(h);
      if (Data && ret)
      {
        DWORD SFXSize;
        if (ArcPlugin->IsArchive(ArcPluginNumber, ArcName, Data, read, &SFXSize))
        {
          ReadArcOK=ReadArchive(ArcName);
        }
      }
      delete[] Data;
    }
    if (!ReadArcOK) return FALSE;
  }
  int CurDirLength=lstrlen(CurDir);
  *pPanelItem=NULL;
  *pItemsNumber=0;
  int AlocatedItemsNumber=0;
  for (int I=0;I<ArcDataCount;I++)
  {
    char Name[NM];
    PluginPanelItem CurItem=ArcData[I];
    BOOL Append=FALSE;
    lstrcpy(Name,CurItem.FindData.cFileName);

    if (Name[0]=='\\')
      Append=TRUE;

    if (Name[0]=='.' && (Name[1]=='\\' || (Name[1]=='.' && Name[2]=='\\')))
      Append=TRUE;

    if (!Append && lstrlen(Name)>CurDirLength && FSF.LStrnicmp(Name,CurDir,CurDirLength)==0 && (CurDirLength==0 || Name[CurDirLength]=='\\'))
    {
      char *StartName,*EndName;
      StartName=Name+CurDirLength+(CurDirLength!=0);

      if ((EndName=strchr(StartName,'\\'))!=NULL)
      {
        *EndName=0;
        CurItem.FindData.dwFileAttributes=FILE_ATTRIBUTE_DIRECTORY;
        CurItem.FindData.nFileSizeLow=CurItem.PackSize=0;
      }

      lstrcpy(CurItem.FindData.cFileName,StartName);
      Append=TRUE;

      if (CurItem.FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
      {
        for (int J=0; J < *pItemsNumber; J++)
          if ((*pPanelItem)[J].FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            if (FSF.LStricmp(CurItem.FindData.cFileName,(*pPanelItem)[J].FindData.cFileName)==0)
            {
              Append=FALSE;
              (*pPanelItem)[J].FindData.dwFileAttributes |= CurItem.FindData.dwFileAttributes;
            }
      }
    }

    if (Append)
    {
      PluginPanelItem *NewPanelItem=*pPanelItem;
      if (*pItemsNumber>=AlocatedItemsNumber)
      {
        AlocatedItemsNumber=AlocatedItemsNumber+256+AlocatedItemsNumber/4;
        NewPanelItem=(PluginPanelItem *)realloc(*pPanelItem,AlocatedItemsNumber*sizeof(PluginPanelItem));

        if (NewPanelItem==NULL)
          break;

        *pPanelItem=NewPanelItem;
      }
      NewPanelItem[*pItemsNumber]=CurItem;
      (*pItemsNumber)++;
    }
  }
  if (*pItemsNumber>0)
    *pPanelItem=(PluginPanelItem *)realloc(*pPanelItem,*pItemsNumber*sizeof(PluginPanelItem));
  return TRUE;
}
Esempio n. 3
0
bool IsDateModifyLess(const MFT_STANDARD & attr, const FILETIME& fileTime)
{
    return (CompareFileTime((const FILETIME*)&attr.n64Modify, &fileTime) < 0);
}
void CCreateNewDatabase::AddFolder(SallyAPI::Database::CDatabaseConnection* dbconn, std::string& folder, 
								  const std::string& mediaDirectory)
{
	HANDLE				hFile;
	WIN32_FIND_DATA		FileInformation;

	std::string firstFile;

	folder = SallyAPI::String::PathHelper::CorrectPath(folder);

	firstFile.append(folder);
	firstFile.append("*");

	hFile = FindFirstFile(firstFile.c_str(), &FileInformation);

	if(hFile != INVALID_HANDLE_VALUE)
	{
		do
		{
			if ((strcmp(FileInformation.cFileName, ".") != NULL) &&
				(strcmp(FileInformation.cFileName, "..") != NULL))
			{
				std::string filename;
				filename.append(folder);
				filename.append(FileInformation.cFileName);

				if (FileInformation.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
				{
					AddFolder(dbconn, filename, mediaDirectory);
				}
				else if (CAudioFile::IsAudioFile(filename) || CVideoFile::IsVideoFile(filename))
				{
					// compare the last file write time with the lastRun time
					FILETIME writeTimeTemp = FileInformation.ftLastWriteTime;
					FILETIME creationTimeTemp = FileInformation.ftCreationTime;

					FILETIME writeTime;
					FILETIME creationTime;

					FileTimeToLocalFileTime(&writeTimeTemp, &writeTime);
					FileTimeToLocalFileTime(&creationTimeTemp, &creationTime);

					// get file Infos
					std::string sDBFileName = SallyAPI::String::StringHelper::ReplaceString(filename, "'", "#");

					if ((CompareFileTime(&m_ftLastRun, &writeTime) <= 0) ||
						(CompareFileTime(&m_ftLastRun, &creationTime) <= 0))
					{
						SYSTEMTIME creationTimeSystem;

						FileTimeToSystemTime(&creationTime, &creationTimeSystem);

						std::string sDBFileCreated = SallyAPI::Date::DateHelper::GetDateString(creationTimeSystem, false);

						// check if it exists in the database
						std::string queryFind;
						queryFind.append("SELECT Filename FROM media WHERE UPPER(Filename) = UPPER('");
						queryFind.append(sDBFileName);
						queryFind.append("');");

						dbconn->LockDatabase();
						SallyAPI::Database::CStatement* stmtFind = dbconn->CreateStatement();

						bool found = false;

						try
						{
							SallyAPI::Database::CResultSet* rslt = stmtFind->ExecuteQuery(queryFind.c_str());
							found = rslt->Next();
						}
						catch (SallyAPI::Database::CSQLException* e)
						{
							SallyAPI::System::CLogger* logger = SallyAPI::Core::CGame::GetLogger();
							logger->Error(e->GetMessage());
						}

						dbconn->ReleaseDatabase();

						if (found)
						{
							UpdateItem(filename, sDBFileName, sDBFileCreated);

							if (m_iUpdateItem == 15)
							{
								ExecuteUpdateItem(dbconn);
							}
						}
						else
						{
							CreateItem(filename, sDBFileName, sDBFileCreated);

							if (m_iCreateItem == 15)
							{
								ExecuteCreateItem(dbconn);
							}
						}
					}
					else
					{
						NoItemUpdate(sDBFileName);

						if (m_iNoUpdateItem == 15)
						{
							ExecuteNoUpdateItem(dbconn);
						}
					}
					
					// update processbar
					m_pProcessbar->SetPosition(m_pProcessbar->GetPosition() + 1);
				}
			}
		} while ((FindNextFile(hFile, &FileInformation) == TRUE) && (m_bPleaseStop == false));
	}
	FindClose(hFile);
	return;
}
Esempio n. 5
0
bool CDateTimeSpan::operator ==(const CDateTimeSpan& right) const
{
  return CompareFileTime(&m_timeSpan, &right.m_timeSpan)==0;
}
Esempio n. 6
0
void LoadFile(HWND hDlg, char *filename, char *error, FILETIME *lastwritetime, bool newfile)
{
	*error = 0;

	if (!*filename)
	{
		return;
	}


	HANDLE hFind;
	WIN32_FIND_DATA FileEntry;
	if ((hFind = FindFirstFile(filename, &FileEntry)) == INVALID_HANDLE_VALUE)
	{
		sprintf(error, "Couldn't find file: '%s'", filename);
		return;
	}
	FindClose(hFind);


	if (CompareFileTime(&FileEntry.ftLastWriteTime, lastwritetime) <= 0)
	{
		return;
	}
	*lastwritetime = FileEntry.ftLastWriteTime;


	FILE *fh;
	if (!(fh = fopen(filename, "rb")))
	{
		sprintf(error, "Couldn't open file: '%s'", filename);
		return;
	}


	fseek(fh, 0, SEEK_END);
	long size = ftell(fh);

	unsigned long long bufsize;
	if (newfile)
	{
		g_offset = size;
		bufsize = 0;
	}
	else
	{
		if (size < g_offset)
		{
			g_offset = size;
		}

		bufsize = size - g_offset;
	}


	if (bufsize)
	{
		char *buf1;
		buf1 = (char *)malloc(bufsize);
		if (!buf1)
		{
			fclose(fh);
			sprintf(error, "Out of memory: %llu bytes.", bufsize);
			return;
		}

		char *buf2;
		buf2 = (char *)malloc(bufsize * 2 + 1);  // For null terminator
		if (!buf2)
		{
			fclose(fh);
			free(buf1);
			sprintf(error, "Out of memory: %llu bytes.", bufsize);
			return;
		}

		fseek(fh, g_offset, SEEK_SET);
		fread(buf1, bufsize, 1, fh);

		fclose(fh);

		bufsize = FixCRLF(buf1, bufsize, buf2);

		buf2[bufsize] = 0;  // Null terminate buf

		SetDlgItemText(hDlg, IDC_TEXT, buf2);

		free(buf1);
		free(buf2);
	}
	else
	{
		fclose(fh);
		SetDlgItemText(hDlg, IDC_TEXT, "");
	}


	char szTitle[1000];
	sprintf(szTitle, "%s - Tail", filename);
	SetWindowText(hDlg, szTitle);


	return;
}
Esempio n. 7
0
BOOL
EnumAvailableApplications(INT EnumType, AVAILENUMPROC lpEnumProc)
{
    HANDLE hFind = INVALID_HANDLE_VALUE;
    WIN32_FIND_DATAW FindFileData;
    WCHAR szPath[MAX_PATH];
    WCHAR szAppsPath[MAX_PATH];
    WCHAR szCabPath[MAX_PATH];
    PAPPLICATION_INFO Info;
    HRESULT hr;

    if (!GetStorageDirectory(szPath, _countof(szPath)))
        return FALSE;

    hr = StringCbPrintfW(szCabPath, sizeof(szCabPath),
                         L"%ls\\rappmgr.cab",
                         szPath);
    if (FAILED(hr))
        return FALSE;

    hr = StringCbCatW(szPath, sizeof(szPath), L"\\rapps\\");

    if (FAILED(hr))
        return FALSE;

    hr = StringCbCopyW(szAppsPath, sizeof(szAppsPath), szPath);

    if (FAILED(hr))
        return FALSE;

    if (!CreateDirectory(szPath, NULL) &&
        GetLastError() != ERROR_ALREADY_EXISTS)
    {
        return FALSE;
    }

    hr = StringCbCatW(szPath, sizeof(szPath), L"*.txt");

    if (FAILED(hr))
        return FALSE;

    hFind = FindFirstFileW(szPath, &FindFileData);

    if (hFind == INVALID_HANDLE_VALUE)
    {
        if (GetFileAttributesW(szCabPath) == INVALID_FILE_ATTRIBUTES)
            DownloadApplicationsDB(APPLICATION_DATABASE_URL);

        ExtractFilesFromCab(szCabPath, szAppsPath);
        hFind = FindFirstFileW(szPath, &FindFileData);

        if (hFind == INVALID_HANDLE_VALUE)
            return FALSE;
    }

    do
    {
        /* loop for all the cached entries */
        for (pCachedEntry = CachedEntriesHead.Flink; pCachedEntry != &CachedEntriesHead; pCachedEntry = pCachedEntry->Flink)
        {
            Info = CONTAINING_RECORD(pCachedEntry, APPLICATION_INFO, List);

            /* do we already have this entry in cache? */
            if(_wcsicmp(FindFileData.cFileName, Info->cFileName) == 0)
            {
                /* is it current enough, or the file has been modified since our last time here? */
                if (CompareFileTime(&FindFileData.ftLastWriteTime, &Info->ftCacheStamp) == 1)
                {
                    /* recreate our cache, this is the slow path */
                    RemoveEntryList(&Info->List);
                    HeapFree(GetProcessHeap(), 0, Info);
                }
                else
                {
                    /* speedy path, compare directly, we already have the data */
                    goto skip_if_cached;
                }

                break;
            }
        }

        /* create a new entry */
        Info = (PAPPLICATION_INFO)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(APPLICATION_INFO));

        if(!Info)
            break;

        Info->Category = ParserGetInt(L"Category", FindFileData.cFileName);

        /* copy the cache-related fields for the next time */
        RtlCopyMemory(&Info->cFileName,    &FindFileData.cFileName, MAX_PATH);
        RtlCopyMemory(&Info->ftCacheStamp, &FindFileData.ftLastWriteTime, sizeof(FILETIME));

        /* add our cached entry to the cached list */
        InsertTailList(&CachedEntriesHead, &Info->List);

skip_if_cached:

        if (Info->Category == FALSE)
            continue;

        if (EnumType != Info->Category && EnumType != ENUM_ALL_AVAILABLE)
            continue;

        /* if our cache hit was only partial, we need to parse
           and lazily fill the rest of fields only when needed */

        if (Info->szUrlDownload[0] == 0)
        {
            GET_STRING1(L"Name",        Info->szName);
            GET_STRING1(L"URLDownload", Info->szUrlDownload);

            GET_STRING2(L"RegName",     Info->szRegName);
            GET_STRING2(L"Version",     Info->szVersion);
            GET_STRING2(L"License",     Info->szLicense);
            GET_STRING2(L"Description", Info->szDesc);
            GET_STRING2(L"Size",        Info->szSize);
            GET_STRING2(L"URLSite",     Info->szUrlSite);
            GET_STRING2(L"CDPath",      Info->szCDPath);
            GET_STRING2(L"SHA1",        Info->szSHA1);
        }

        if (!lpEnumProc(Info))
            break;

    } while (FindNextFileW(hFind, &FindFileData) != 0);

    FindClose(hFind);

    return TRUE;
}
static int32_t __cdecl mediainfo_compare(const MediaInfo **a, const MediaInfo **b) 
{
	return CompareFileTime(&((*a)->m_History), &((*b)->m_History));
}
Esempio n. 9
0
//////////////////////////////////////////////////////////////////////////
//参数:
//		pSrcDir [IN]	--		源, 如: D:\\aaa\\*
//		pDstDir [IN]	--		备份到哪里去, 如: E:\\bbb\\*
//
//////////////////////////////////////////////////////////////////////////
bool CFileBackUp::BackUp(const wstring& src, const wstring& dst)
{
	return CopyFile(src.c_str(), dst.c_str(), FALSE);   

	bool bRet=TRUE;   
	int iSrcFile=0;   
	int iDstFile=0;   

	TCHAR* pSrcDir = const_cast<TCHAR*>(src.c_str());
	TCHAR* pDstDir = const_cast<TCHAR*>(dst.c_str());

    //在源目录下遍历所有的文件保存在SrcFiles结构体中   
    HANDLE hFile=FindFirstFile(pSrcDir,&fd);   
    while(hFile!=INVALID_HANDLE_VALUE && bRet)   
    {   
        if(fd.dwFileAttributes==FILE_ATTRIBUTE_ARCHIVE)   
        {   
            SrcFiles[iSrcFile].fd=fd;   
            SrcFiles[iSrcFile].bIsNew=FALSE;   
            //out<<SrcFiles[iSrcFile].fd.cFileName<<endl;   
            iSrcFile++;   
        }   
        bRet=FindNextFile(hFile,&fd);   
    }   
       
    //在目标目录下遍历所有的文件保存在DstFiles结构体中   
    bRet=TRUE;   
    hFile=FindFirstFile(pDstDir,&fd);   
    while(hFile!=INVALID_HANDLE_VALUE && bRet)   
    {   
        if(fd.dwFileAttributes==FILE_ATTRIBUTE_ARCHIVE)   
        {   
            DstFiles[iDstFile].fd=fd;   
            DstFiles[iDstFile].bIsMatch=FALSE;   
            iDstFile++;   
        }   
        bRet=FindNextFile(hFile,&fd);   
    }   
///////////////////////////////////////////////////////////////    
//  下面开始比较源目录和目标目录的所有文件名称与建表时间     //   
//  找出SrcFile中那些文件比DstFile文件时间上更早,           //   
//  就讲bIsNew设为TRUE,同时DstFile文件中存在,而在SrcFile中 //   
//  不存在,就把bMatch设为False                              //   
    for(int i=0;i<iSrcFile-1;i++)   
    {   
        bool bNull=TRUE;   
        for(int j=0;j<iDstFile-1;j++)   
        {   
            if(lstrcmpi(SrcFiles[i].fd.cFileName,DstFiles[j].fd.cFileName)==0)   
            {   
                DstFiles[j].bIsMatch=TRUE;   
                bNull=FALSE;   
                if(1==CompareFileTime(&SrcFiles[i].fd.ftCreationTime,&DstFiles[j].fd.ftCreationTime))   
            //  if(SrcFiles[i].fd.ftCreationTime.dwLowDateTime > DstFiles[j].fd.ftCreationTime.dwLowDateTime)   
                    SrcFiles[i].bIsNew=TRUE;   
                break;   
            }   
        }   
        if(bNull==TRUE)   
            SrcFiles[i].bIsNew=TRUE;   
    }   
   
   
    //拷贝SrcFile中bIsNew位TRUE的文件到DstFile中去   
    for(int a=0;a<iSrcFile-1;a++)   
    {   
        if(SrcFiles[a].bIsNew)   
        {   
            CopyFile(SrcFiles[a].fd.cFileName,pDstDir,FALSE);   
        }   
    }   
       
    //删除目标中bMatch为FALSE的文件   
    for (int b=0; b<iDstFile; b++)    
    {   
        if (!DstFiles[b].bIsMatch)   
        {   
            lstrcat(pDstDir, DstFiles[b].fd.cFileName);   
            DeleteFile(pDstDir);   
            // printf("delete %s \n", dest);   
        }   
    }   
   
    return 0;
}
Esempio n. 10
0
int __cdecl main( int argc, char **argv ) 

{
    int i, j, k;
    int *total;
    
    HANDLE hProcess;    
    FILETIME createTime;
    FILETIME exitTime;
    FILETIME kernelTime1;
    FILETIME userTime1;
    FILETIME kernelTime2;
    FILETIME userTime2;

    DWORD dwError;
    
    /* initialize the PAL */
    if( PAL_Initialize(argc, argv) != 0 )
    {
	    return( FAIL );
    }

    /* get our own process handle */
    hProcess = GetCurrentProcess();
    if( hProcess == NULL )
    {
        Fail(   "GetCurrentProcess() returned a NULL handle.\n" );
    }
    
    /* zero our time structures */
    ZeroMemory( &createTime, sizeof(createTime) );
    ZeroMemory( &exitTime, sizeof(exitTime) );
    ZeroMemory( &kernelTime1, sizeof(kernelTime1) );
    ZeroMemory( &userTime1, sizeof(userTime1) );
    ZeroMemory( &kernelTime2, sizeof(kernelTime2) );
    ZeroMemory( &userTime2, sizeof(userTime2) );

    /* check the process times for the child process */
    if( ! GetProcessTimes(  hProcess,
                            &createTime,
                            &exitTime,
                            &kernelTime1,
                            &userTime1 ) )
    {
        dwError = GetLastError();
        Fail( "GetProcessTimes() call failed with error code %d\n",
              dwError ); 
    }


    /* simulate some activity */
    for( i=0; i<1000; i++ )
    {
        for( j=0; j<1000; j++ )
        {
            /* do kernel work to increase system usage counters */
            total = (int*)malloc(1024 * 1024);

            *total = j * i;
            for( k=0; k<1000; k++ )
            {
                *total += k + i;
            }

            free(total);
        }
    }

    /* check the process times for the child process */
    if( ! GetProcessTimes(  hProcess,
                            &createTime,
                            &exitTime,
                            &kernelTime2,
                            &userTime2 ) )
    {
        dwError = GetLastError();
        Fail( "GetProcessTimes() call failed with error code %d\n",
              dwError ); 
    }


    /* very simple logical checking of the results */
    if( CompareFileTime( &kernelTime1, &kernelTime2 ) > 0 )
    {
        Fail( "Unexpected kernel time value reported.\n" );
    }
    
    if( CompareFileTime( &userTime1, &userTime2 ) > 0 )
    {
        Fail( "Unexpected user time value reported.\n" );
    }
        

    /* terminate the PAL */
    PAL_Terminate();
    
    /* return success */
    return PASS; 
}
Esempio n. 11
0
int Compare_FileTime(const FileTime& fa, const FileTime& fb)
{
	return CompareFileTime(&fa, &fb);
}
Esempio n. 12
0
BOOL
	CProcessControl::GetParentPid(
	__in	ULONG	ulPid,
	__out	PULONG	pulParentPid 
	)
{
	BOOL						bRet = FALSE;

	HANDLE						hProcess = NULL;
	HANDLE						hProcessParent = NULL;
	PROCESS_BASIC_INFORMATION	ProcessBasicInfo = {0};
	ULONG						ulRet = 0;
	NTSTATUS					ntStatus = 0;
	FILETIME					CreateTime		= {0};
	FILETIME					ExitTime			= {0};
	FILETIME					KernelTime		= {0};
	FILETIME					USerTime			= {0};
	FILETIME					ParentCreateTime		= {0};
	FILETIME					ParentExitTime			= {0};
	FILETIME					ParentKernelTime		= {0};
	FILETIME					ParentUSerTime			= {0};


	__try
	{
		if (!ulPid || !pulParentPid)
		{
			printfPublic("input arguments error. ulPid(%d) pulParentPid(0x%p)", ulPid, pulParentPid);
			__leave;
		}

		hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, ulPid);
		if (!hProcess)
		{
			printfPublic("OpenProcess failed. (%d)", GetLastError());
			__leave;
		}

		ntStatus = m_NtQueryInformationProcess(
			 hProcess,
			 ProcessBasicInformation,
			 &ProcessBasicInfo,
			 sizeof(ProcessBasicInfo),
			 &ulRet			 
			 );
		if (!NT_SUCCESS(ntStatus))
		{
			printfPublic("m_NtQueryInformationProcess failed. (0x%x)", ntStatus);
			__leave;
		}

		hProcessParent = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, (DWORD)ProcessBasicInfo.Reserved3);
		if (!hProcessParent)
			__leave;

		if (!ProcessBasicInfo.UniqueProcessId)
		{
			bRet = TRUE;
			__leave;
		}
	
		if (!GetProcessTimes(
			hProcessParent,
			&ParentCreateTime,
			&ParentExitTime,
			&ParentKernelTime,
			&ParentUSerTime
			))
		{
			printfPublic("GetProcessTimes failed. (%d)", GetLastError());
			__leave;
		}

		if (!GetProcessTimes(
			hProcess,
			&CreateTime,
			&ExitTime,
			&KernelTime,
			&USerTime
			))
		{
			printfPublic("GetProcessTimes failed. (%d)", GetLastError());
			__leave;
		}

		if (-1 != CompareFileTime(&ParentCreateTime, &CreateTime))
			__leave;

		*pulParentPid = (ULONG)ProcessBasicInfo.Reserved3;

		bRet = TRUE;
	}
	__finally
	{
		if (hProcess)
		{
			CloseHandle(hProcess);
			hProcess = NULL;
		}

		if (hProcessParent)
		{
			CloseHandle(hProcessParent);
			hProcessParent = NULL;
		}
	}
	
	return bRet;
}
Esempio n. 13
0
// update an alarm so that the systemtime reflects the next time the alarm will go off, based on the last_check time
bool UpdateAlarm(SYSTEMTIME &time, Occurrence occ) {

	FILETIME ft_now, ft_then;
	ULARGE_INTEGER uli_then;

	switch(occ) {
	case OC_DAILY:
	case OC_WEEKDAYS:
	case OC_WEEKLY:
		time.wDay = last_check.wDay;
	case OC_MONTHLY:
		time.wMonth = last_check.wMonth;
	case OC_YEARLY:
		time.wYear = last_check.wYear;
	case OC_ONCE:
		break; // all fields valid
	};

	SystemTimeToFileTime(&last_check, &ft_now); // consider 'now' to be last check time
	SystemTimeToFileTime(&time, &ft_then);
	
	switch(occ) {
	case OC_ONCE:
		if (CompareFileTime(&ft_then, &ft_now) < 0)
			return false;
		break;
	case OC_YEARLY:
		while(CompareFileTime(&ft_then, &ft_now) < 0) {
			time.wYear++;
			SystemTimeToFileTime(&time, &ft_then);
		}
		break;
	case OC_MONTHLY:
		while(CompareFileTime(&ft_then, &ft_now) < 0) {
			if (time.wMonth == 12) {
				time.wMonth = 1;
				time.wYear++;
			} else
				time.wMonth++;
			SystemTimeToFileTime(&time, &ft_then);
		}
		break;
	case OC_WEEKLY:
		{
			SYSTEMTIME temp;
			uli_then.HighPart = ft_then.dwHighDateTime;
			uli_then.LowPart = ft_then.dwLowDateTime;
			FileTimeToSystemTime(&ft_then, &temp);
			do {
				if (temp.wDayOfWeek != time.wDayOfWeek || CompareFileTime(&ft_then, &ft_now) < 0) {
					uli_then.QuadPart += mult.QuadPart * (ULONGLONG)24 * (ULONGLONG)60;
					ft_then.dwHighDateTime = uli_then.HighPart;
					ft_then.dwLowDateTime = uli_then.LowPart;
					FileTimeToSystemTime(&ft_then, &temp);
				}
			} while(temp.wDayOfWeek != time.wDayOfWeek || CompareFileTime(&ft_then, &ft_now) < 0);
		}
		break;
	case OC_WEEKDAYS:
		{
			SYSTEMTIME temp;
			uli_then.HighPart = ft_then.dwHighDateTime;
			uli_then.LowPart = ft_then.dwLowDateTime;
			do {
				FileTimeToSystemTime(&ft_then, &temp);
				if (temp.wDayOfWeek == 0 || temp.wDayOfWeek == 6 || CompareFileTime(&ft_then, &ft_now) < 0) {
					uli_then.QuadPart += mult.QuadPart * (ULONGLONG)24 * (ULONGLONG)60;
					ft_then.dwHighDateTime = uli_then.HighPart;
					ft_then.dwLowDateTime = uli_then.LowPart;
				}
			} while(temp.wDayOfWeek == 0 || temp.wDayOfWeek == 6 || CompareFileTime(&ft_then, &ft_now) < 0);
		}
		break;
	case OC_DAILY:
		uli_then.HighPart = ft_then.dwHighDateTime;
		uli_then.LowPart = ft_then.dwLowDateTime;
		while(CompareFileTime(&ft_then, &ft_now) < 0) {
			uli_then.QuadPart += mult.QuadPart * (ULONGLONG)24 * (ULONGLONG)60;
			ft_then.dwHighDateTime = uli_then.HighPart;
			ft_then.dwLowDateTime = uli_then.LowPart;
		}
		break;
	}

	FileTimeToSystemTime(&ft_then, &time);
	return true;
}
Esempio n. 14
0
/* Returns true if we find cached prompts.
   Called with kt->cs held.
 */
static khm_boolean
cached_kinit_prompter(k5_kinit_task * kt) {
    khm_boolean rv = FALSE;
    khm_handle csp_idconfig = NULL;
    khm_handle csp_k5config = NULL;
    khm_handle csp_prcache = NULL;
    khm_size cb;
    khm_size n_cur_prompts;
    khm_int32 n_prompts;
    khm_int32 i;
    khm_int64 iexpiry;
    FILETIME expiry;

    assert(kt->nc);

    if (KHM_FAILED(kcdb_identity_get_config(kt->identity, 0, &csp_idconfig)) ||

        KHM_FAILED(khc_open_space(csp_idconfig, CSNAME_KRB5CRED,
                                  0, &csp_k5config)) ||

        KHM_FAILED(khc_open_space(csp_k5config, CSNAME_PROMPTCACHE,
                                  0, &csp_prcache)) ||

        KHM_FAILED(khc_read_int32(csp_prcache, L"PromptCount",
                                  &n_prompts)) ||
        n_prompts == 0)

        goto _cleanup;

    if (KHM_SUCCEEDED(khc_read_int64(csp_prcache, L"ExpiresOn", &iexpiry))) {
        FILETIME current;

        /* has the cache expired? */
        expiry = IntToFt(iexpiry);
        GetSystemTimeAsFileTime(&current);

        if (CompareFileTime(&expiry, &current) < 0)
            /* already expired */
            goto _cleanup;
    } else {
        /* if there is no value for ExpiresOn, we assume the prompts
           have already expired. */
        goto _cleanup;
    }

    /* we found a prompt cache.  We take this to imply that the
       principal is valid. */
    kt->is_valid_principal = TRUE;

    /* check if there are any prompts currently showing.  If there are
       we check if they are the same as the ones we are going to show.
       In which case we just reuse the exisitng prompts */
    if (KHM_FAILED(khui_cw_get_prompt_count(kt->nc, &n_cur_prompts)) ||
        n_prompts != (khm_int32) n_cur_prompts)
        goto _show_new_prompts;

    for(i = 0; i < n_prompts; i++) {
        wchar_t wsname[8];
        wchar_t wprompt[KHUI_MAXCCH_PROMPT];
        khm_handle csp_p = NULL;
        khm_int32 p_type;
        khm_int32 p_flags;
        khui_new_creds_prompt * p;

        if (KHM_FAILED(khui_cw_get_prompt(kt->nc, i, &p)))
            break;

        StringCbPrintf(wsname, sizeof(wsname), L"%d", i);

        if (KHM_FAILED(khc_open_space(csp_prcache, wsname, 0, &csp_p)))
            break;

        cb = sizeof(wprompt);
        if (KHM_FAILED(khc_read_string(csp_p, L"Prompt",
                                       wprompt, &cb))) {
            khc_close_space(csp_p);
            break;
        }

        if (KHM_FAILED(khc_read_int32(csp_p, L"Type", &p_type)))
            p_type = 0;

        if (KHM_FAILED(khc_read_int32(csp_p, L"Flags", &p_flags)))
            p_flags = 0;

        if (                    /* if we received a prompt string,
                                   then it should be the same as the
                                   one that is displayed */
            (wprompt[0] &&
             (p->prompt == NULL ||
              wcscmp(wprompt, p->prompt))) ||

                                /* if we didn't receive one, then
                                   there shouldn't be one displayed.
                                   This case really shouldn't happen
                                   in reality, but we check anyway. */
            (!wprompt[0] &&
             p->prompt != NULL) ||

                                /* the type should match */
            (p_type != p->type) ||

                                /* if this prompt should be hidden,
                                   then it must also be so */
            (p_flags != p->flags)
            ) {

            khc_close_space(csp_p);
            break;

        }


        khc_close_space(csp_p);
    }

    if (i == n_prompts) {
        /* We are already showing the right set of prompts. */
        rv = TRUE;
        goto _cleanup;
    }

 _show_new_prompts:

    khui_cw_clear_prompts(kt->nc);

    {
        wchar_t wbanner[KHUI_MAXCCH_BANNER];
        wchar_t wpname[KHUI_MAXCCH_PNAME];

        cb = sizeof(wbanner);
        if (KHM_FAILED(khc_read_string(csp_prcache, L"Banner",
                                      wbanner, &cb)))
            wbanner[0] = 0;

        cb = sizeof(wpname);
        if (KHM_FAILED(khc_read_string(csp_prcache, L"Name",
                                       wpname, &cb)))
            wpname[0] = 0;

        if (wpname[0] == L'\0')
            LoadString(hResModule, IDS_PNAME_PW, wpname, ARRAYLENGTH(wpname));

        khui_cw_begin_custom_prompts(kt->nc,
                                     n_prompts,
                                     (wbanner[0]? wbanner: NULL),
                                     (wpname[0]? wpname: NULL));
    }

    for(i = 0; i < n_prompts; i++) {
        wchar_t wsname[8];
        wchar_t wprompt[KHUI_MAXCCH_PROMPT];
        khm_handle csp_p = NULL;
        khm_int32 p_type;
        khm_int32 p_flags;

        StringCbPrintf(wsname, sizeof(wsname), L"%d", i);

        if (KHM_FAILED(khc_open_space(csp_prcache, wsname, 0, &csp_p)))
            break;

        cb = sizeof(wprompt);
        if (KHM_FAILED(khc_read_string(csp_p, L"Prompt",
                                       wprompt, &cb))) {
            khc_close_space(csp_p);
            break;
        }

        if (KHM_FAILED(khc_read_int32(csp_p, L"Type", &p_type)))
            p_type = 0;

        if (KHM_FAILED(khc_read_int32(csp_p, L"Flags", &p_flags)))
            p_flags = 0;

        khui_cw_add_prompt(kt->nc, p_type, wprompt, NULL, p_flags);

        khc_close_space(csp_p);
    }

    if (i < n_prompts) {
        khui_cw_clear_prompts(kt->nc);
    } else {
        rv = TRUE;
    }

 _cleanup:

    if (csp_prcache)
        khc_close_space(csp_prcache);

    if (csp_k5config)
        khc_close_space(csp_k5config);

    if (csp_idconfig)
        khc_close_space(csp_idconfig);

    return rv;
}
Esempio n. 15
0
BOOL scanDir( LPTSTR tDir, List* resList, Item* parentItem, BOOL fstLevel, BOOL dbg )
{
    TCHAR dirStr[ MAX_PATH ] = { 0 };
    HANDLE hFind = INVALID_HANDLE_VALUE;

    Item currentItem = { 0 };
    
    LARGE_INTEGER parentSize = { 0 };
    LARGE_INTEGER currentSize = { 0 };

    // Prepare string for use with FindFile functions.  First, copy the
    // string to a buffer, then append '\*' to the directory name.
    wcscpy_s( dirStr, MAX_PATH, tDir );

    if ( dirStr[ wcslen( dirStr ) - 1 ] == TEXT( '\\' ) )
        wcscat_s( dirStr, MAX_PATH, TEXT( "*" ) );
    else
        wcscat_s( dirStr, MAX_PATH, TEXT( "\\*" ) );

    // Find the first file in the directory.
    hFind = FindFirstFile( dirStr, &currentItem.findInfo );

    // Validate search handle
    if ( INVALID_HANDLE_VALUE == hFind )
    {
        // Only report error if different from 'Access Denied'.
        // For example, system symbolic links report 'access denied'.
        // If a handle is obtained and the size is requested,
        // Win32 reports 0 bytes.
        // See results using '..\progsDev\others\TestGetFileSizeEx\'
        if ( GetLastError() != ERROR_ACCESS_DENIED )
            ReportError( TEXT( "FindFirstFile failed." ), 0, TRUE );

        // Exit in any case
        return FALSE;
    }

    // List all the files/subdirs in the directory
    do
    {
        // Do not follow symbolic links
        // Symbolic links are listed but,
        // they do not affect dirs nor files count
        // Their size (0 bytes) and date are taken into account
        if ( !( currentItem.findInfo.dwFileAttributes &
                FILE_ATTRIBUTE_REPARSE_POINT ) )
        {
            // Subdirectory found ?
            if ( currentItem.findInfo.dwFileAttributes &
                 FILE_ATTRIBUTE_DIRECTORY )
            {
                // Dir found

                // Skip '.' or '..'
                if ( ptDir( currentItem.findInfo.cFileName ) )
                    continue;

                // Increment dirs count of parent
                ++parentItem->dirsCount.QuadPart;

                // Prepare the recursive call
                wcscpy_s( dirStr, MAX_PATH, tDir );
                wcscat_s( dirStr, MAX_PATH, TEXT( "\\" ) );
                wcscat_s( dirStr, MAX_PATH, currentItem.findInfo.cFileName );

                // Debug output
                if ( dbg )
                    wprintf_s( TEXT( "    %s\n" ), dirStr );

                // Scan subdir
                scanDir( dirStr, resList, &currentItem, FALSE, dbg );

                // Update dirs count of parent using found subdirs
                parentItem->dirsCount.QuadPart +=
                    currentItem.dirsCount.QuadPart;

                // Update files count of parent using found files
                parentItem->filesCount.QuadPart +=
                    currentItem.filesCount.QuadPart;
            }
            else
            {
                // File found

                // Increment files count of parent
                ++parentItem->filesCount.QuadPart;

                // Current item has one file
                currentItem.filesCount.QuadPart = 1;
            }
        }

        // Update last write time information of the parent.
        // Is current item's LastWriteTime later
        // than parent's LastWriteTime ?
        if ( CompareFileTime( &currentItem.findInfo.ftLastWriteTime,
            &parentItem->findInfo.ftLastWriteTime ) == 1 )
        {
            // Parent gets the LastWriteTime from current item
            parentItem->findInfo.ftLastWriteTime =
                currentItem.findInfo.ftLastWriteTime;
        }

        // Get size of current found file(s)
        currentSize.LowPart = currentItem.findInfo.nFileSizeLow;
        currentSize.HighPart = currentItem.findInfo.nFileSizeHigh;

        // Get size of parent so far
        parentSize.LowPart = parentItem->findInfo.nFileSizeLow;
        parentSize.HighPart = parentItem->findInfo.nFileSizeHigh;

        // Add current size to parent size (64-bit addition)
        parentSize.QuadPart += currentSize.QuadPart;

        // Update parent file size
        parentItem->findInfo.nFileSizeLow = parentSize.LowPart;
        parentItem->findInfo.nFileSizeHigh = parentSize.HighPart;

        // Update list
        if ( fstLevel )
        {
            // Append current item to results list
            if ( AddItem( currentItem, resList ) == false )
            {
                wprintf_s( TEXT( "Problem allocating memory\n" ) );
                return FALSE;
            }
        }

        // Reset current item
        memset( &currentItem, 0, sizeof( Item ) );

    } while ( FindNextFile( hFind, &currentItem.findInfo ) != 0 );

    // Validate end of search
    if ( GetLastError() != ERROR_NO_MORE_FILES )
    {
        ReportError( TEXT( "\nFindNextFile failed.\n" ), 0, TRUE );
        return FALSE;
    }

    // Close search handle
    FindClose( hFind );

    return TRUE;
}
Esempio n. 16
0
bool TopMenuCore::loadInto(DWORD _pid)
{
   TopMenu_CSLock lock(s_cs);

   SetLastError(ERROR_SUCCESS);
   DWORD le;

   char szLibPath[MAX_PATH];
   if(!GetModuleFileName((HINSTANCE)&__ImageBase, szLibPath, MAX_PATH)) {
      le = GetLastError();
      return false;
   }

   HMODULE hKernel32 = ::GetModuleHandle("Kernel32");

   HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, _pid);
   if(!hProcess) {
      le = GetLastError();
      return false;
   }
   
   FILETIME ftCreationTime;
   FILETIME ftExitTime;
   FILETIME ftKernelTime;
   FILETIME ftUserTime;
   if(!GetProcessTimes(hProcess, &ftCreationTime, &ftExitTime, &ftKernelTime, &ftUserTime)) {
      le = GetLastError();
      ::CloseHandle(hProcess);
      return false;
   }

   if(CompareFileTime(&s_lastLoadTime, &ftCreationTime) > 0) {
      le = GetLastError();
      ::CloseHandle(hProcess);
      return false;
   }

#if defined(_M_X64)
   BOOL isWow64Proc = FALSE;
   if(!IsWow64Process(hProcess, &isWow64Proc) || isWow64Proc) {
      le = GetLastError();
      ::CloseHandle(hProcess);
      return false;
   }
#endif

   HMODULE hMods[1024];
   DWORD cbNeeded;
   if(!EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded))
   {
      le = GetLastError();
      ::CloseHandle(hProcess);
      return false;
   }

   for(DWORD i = 0; i < (cbNeeded / sizeof(HMODULE)); i++)
   {
      char szModName[MAX_PATH];
      if(GetModuleFileNameEx(hProcess, hMods[i], szModName, sizeof(szModName) / sizeof(char)))
      {
         if(_strnicmp(szModName, szLibPath, MAX_PATH) == 0) {
            ::CloseHandle(hProcess);
            return true; // already loaded
         }
      }
   }

   // 1. Allocate memory in the remote process for szLibPath
   void* pLibRemote = ::VirtualAllocEx(hProcess, NULL, sizeof(szLibPath), MEM_COMMIT, PAGE_READWRITE);
   if(!pLibRemote) {
      le = GetLastError();
      ::CloseHandle(hProcess);
      return false;
   }
   
   // 2. Write szLibPath to the allocated memory
   if(!::WriteProcessMemory(hProcess, pLibRemote, (void*)szLibPath, sizeof(szLibPath), NULL)) {
      le = GetLastError();
      ::VirtualFreeEx(hProcess, pLibRemote, 0, MEM_RELEASE); //lint !e534 JLD
      ::CloseHandle(hProcess);
      return false;
   }

   // Load into the remote process
   // (via CreateRemoteThread & LoadLibrary)
   HANDLE hThread = ::CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE) ::GetProcAddress(hKernel32,"LoadLibraryA"), pLibRemote, 0, NULL);
   if(!hThread) {
      le = GetLastError();
      ::VirtualFreeEx(hProcess, pLibRemote, 0, MEM_RELEASE); //lint !e534 JLD
      ::CloseHandle(hProcess);
      return false;
   }

   ::WaitForSingleObject(hThread, INFINITE); //lint !e534 JLD

   // Get handle of the loaded module
   DWORD hLibModule;
   ::GetExitCodeThread(hThread, &hLibModule); //lint !e534 JLD
   if(!hLibModule) {
      le = GetLastError();
      ::CloseHandle(hThread); //lint !e534 JLD
      ::VirtualFreeEx(hProcess, pLibRemote, 0, MEM_RELEASE); //lint !e534 JLD
      ::CloseHandle(hProcess);
      return false;
   }

   // Clean up
   ::CloseHandle(hThread); //lint !e534 JLD
   ::VirtualFreeEx(hProcess, pLibRemote, 0, MEM_RELEASE); //lint !e534 JLD
   ::CloseHandle(hProcess);

   return true;
} //lint !e550 JLD
Esempio n. 17
0
// compares LastWriteTime of two items
//   1 : item N later than item M
//   0 : item N same time item M
//  -1 : item N earlier item M
int cmpItemsLastWriteTime( Item* pItemN, Item* pItemM )
{
    return CompareFileTime( &pItemN->findInfo.ftLastWriteTime,
        &pItemM->findInfo.ftLastWriteTime );
}
bool CSVNStatusListCtrl::CSorter::operator()
( const FileEntry* entry1
 , const FileEntry* entry2) const
{
#define SGN(x) ((x)==0?0:((x)>0?1:-1))

    int result = 0;
    switch (sortedColumn)
    {
    case 19:
        {
            if (result == 0)
            {
                __int64 fileSize1 = entry1->isfolder ? 0 : entry1->working_size != (-1) ? entry1->working_size : entry1->GetPath().GetFileSize();
                __int64 fileSize2 = entry2->isfolder ? 0 : entry2->working_size != (-1) ? entry2->working_size : entry2->GetPath().GetFileSize();

                result = int(fileSize1 - fileSize2);
            }
        }
    case 18:
        {
            if (result == 0)
            {
                __int64 writetime1 = entry1->GetPath().GetLastWriteTime();
                __int64 writetime2 = entry2->GetPath().GetLastWriteTime();

                FILETIME* filetime1 = (FILETIME*)(__int64*)&writetime1;
                FILETIME* filetime2 = (FILETIME*)(__int64*)&writetime2;

                result = CompareFileTime(filetime1,filetime2);
            }
        }
    case 17:
        {
            if (result == 0)
            {
                result = SGN(entry1->last_commit_date - entry2->last_commit_date);
            }
        }
    case 16:
        {
            if (result == 0)
            {
                result = entry1->remoterev - entry2->remoterev;
            }
        }
    case 15:
        {
            if (result == 0)
            {
                result = entry1->last_commit_rev - entry2->last_commit_rev;
            }
        }
    case 14:
        {
            if (result == 0)
            {
                if (s_bSortLogical)
                    result = StrCmpLogicalW(entry1->last_commit_author, entry2->last_commit_author);
                else
                    result = StrCmpI(entry1->last_commit_author, entry2->last_commit_author);
            }
        }
    case 13:
        {
            if (result == 0)
            {
                result = (int)(entry1->lock_date - entry2->lock_date);
            }
        }
    case 12:
        {
            if (result == 0)
            {
                if (s_bSortLogical)
                    result = StrCmpLogicalW(entry1->lock_comment, entry2->lock_comment);
                else
                    result = StrCmpI(entry1->lock_comment, entry2->lock_comment);
            }
        }
    case 11:
        {
            if (result == 0)
            {
                if (s_bSortLogical)
                    result = StrCmpLogicalW(entry1->lock_owner, entry2->lock_owner);
                else
                    result = StrCmpI(entry1->lock_owner, entry2->lock_owner);
            }
        }
    case 10:
        {
            if (result == 0)
            {
                if (s_bSortLogical)
                    result = StrCmpLogicalW(entry1->url, entry2->url);
                else
                    result = StrCmpI(entry1->url, entry2->url);
            }
        }
    case 9:
        {
            if (result == 0)
            {
                result = entry1->depth - entry2->depth;
            }
        }
    case 8:
        {
            if (result == 0)
            {
                result = entry1->remotepropstatus - entry2->remotepropstatus;
            }
        }
    case 7:
        {
            if (result == 0)
            {
                result = entry1->remotetextstatus - entry2->remotetextstatus;
            }
        }
    case 6:
        {
            if (result == 0)
            {
                result = entry1->propstatus - entry2->propstatus;
            }
        }
    case 5:
        {
            if (result == 0)
            {
                result = entry1->textstatus - entry2->textstatus;
            }
        }
    case 4:
        {
            if (result == 0)
            {
                result = entry1->remotestatus - entry2->remotestatus;
            }
        }
    case 3:
        {
            if (result == 0)
            {
                result = entry1->status - entry2->status;
            }
        }
    case 2:
        {
            if (result == 0)
            {
                if (s_bSortLogical)
                    result = StrCmpLogicalW(entry1->path.GetFileExtension(), entry2->path.GetFileExtension());
                else
                    result = StrCmpI(entry1->path.GetFileExtension(), entry2->path.GetFileExtension());
            }
        }
    case 1:
        {
            // do not sort by file/dirname if the sorting isn't done by this specific column but let the second-order
            // sorting be done by path
            if ((result == 0)&&(sortedColumn == 1))
            {
                if (s_bSortLogical)
                    result = StrCmpLogicalW(entry1->path.GetFileOrDirectoryName(), entry2->path.GetFileOrDirectoryName());
                else
                    result = StrCmpI(entry1->path.GetFileOrDirectoryName(), entry2->path.GetFileOrDirectoryName());
            }
        }
    case 0:     // path column
        {
            if (result == 0)
            {
                if (s_bSortLogical)
                    result = StrCmpLogicalW(entry1->path.GetWinPath(), entry2->path.GetWinPath());
                else
                    result = StrCmpI(entry1->path.GetWinPath(), entry2->path.GetWinPath());
            }
        }
    default:
        if ((result == 0) && (sortedColumn > 0))
        {
            // N/A props are "less than" empty props

            const CString& propName = columnManager->GetName (sortedColumn);

            auto propEntry1 = control->m_PropertyMap.find(entry1->GetPath());
            auto propEntry2 = control->m_PropertyMap.find(entry2->GetPath());
            bool entry1HasProp = (propEntry1 != control->m_PropertyMap.end()) && propEntry1->second.HasProperty (propName);
            bool entry2HasProp = (propEntry2 != control->m_PropertyMap.end()) && propEntry2->second.HasProperty (propName);

            if (entry1HasProp)
            {
                result = entry2HasProp
                    ? propEntry1->second[propName].Compare
                    (propEntry2->second[propName])
                    : 1;
            }
            else
            {
                result = entry2HasProp ? -1 : 0;
            }
        }
    } // switch (m_nSortedColumn)
    if (!ascending)
        result = -result;

    return result < 0;
}
Esempio n. 19
0
BOOL scanDir( LPTSTR tDir, List* resList, Item* parentItem )
{
    TCHAR dirStr[ MAX_PATH ] = { 0 };
    HANDLE hFind = INVALID_HANDLE_VALUE;

    Item currentItem = { 0 };
    
    LARGE_INTEGER parentSize = { 0 };
    LARGE_INTEGER currentSize = { 0 };

    // Prepare string for use with FindFile functions.
    
    // Validate space to extend dirStr
    // There must be enough space to append
    // "*.nmea" + '\0' or "\*.nmea" + '\0'
    if ( wcsnlen( tDir, MAX_PATH ) >= MAX_PATH - 8 )
    {
        wprintf_s( TEXT( "\nDirectory path is too long.\n" ) );
        return FALSE;
    }

    // Copy passed string to buffer,
    // then append "*.nmea" + '\0' or "\*.nmea" + '\0' to the directory name.
    wcscpy_s( dirStr, MAX_PATH, tDir );

    if ( dirStr[ wcslen( dirStr ) - 1 ] == TEXT( '\\' ) )
        wcscat_s( dirStr, MAX_PATH, TEXT( "*.nmea" ) );
    else
        wcscat_s( dirStr, MAX_PATH, TEXT( "\\*.nmea" ) );

    // Find the first file in the directory.
    hFind = FindFirstFile( dirStr, &currentItem.findInfo );

    // Validate search handle
    if ( INVALID_HANDLE_VALUE == hFind )
    {
        // Only report error if different from 'Access Denied'.
        // For example, system symbolic links report 'access denied'.
        // If a handle is obtained and the size is requested,
        // Win32 reports 0 bytes.
        // See results using '..\progsDev\others\TestGetFileSizeEx\'
        if ( GetLastError() != ERROR_ACCESS_DENIED )
            ReportError( TEXT( "FindFirstFile failed." ), 0, TRUE );

        // Exit in any case
        return FALSE;
    }

    // List only nmea files in target dir
    do
    {
        // Do not follow symbolic links
        if ( !( currentItem.findInfo.dwFileAttributes &
                FILE_ATTRIBUTE_REPARSE_POINT ) )
        {
            // Ignore subdirs
            if ( !( currentItem.findInfo.dwFileAttributes &
                FILE_ATTRIBUTE_DIRECTORY ) )
            {
                // File found

                // Update last write time information of the parent.
                // Is current item's LastWriteTime later
                // than parent's LastWriteTime ?
                if ( CompareFileTime( &currentItem.findInfo.ftLastWriteTime,
                    &parentItem->findInfo.ftLastWriteTime ) == 1 )
                {
                    // Parent gets the LastWriteTime from current item
                    parentItem->findInfo.ftLastWriteTime =
                        currentItem.findInfo.ftLastWriteTime;
                }

                // Get size of current found file(s)
                currentSize.LowPart = currentItem.findInfo.nFileSizeLow;
                currentSize.HighPart = currentItem.findInfo.nFileSizeHigh;

                // Get size of parent so far
                parentSize.LowPart = parentItem->findInfo.nFileSizeLow;
                parentSize.HighPart = parentItem->findInfo.nFileSizeHigh;

                // Add current size to parent size (64-bit addition)
                parentSize.QuadPart += currentSize.QuadPart;

                // Update parent file size
                parentItem->findInfo.nFileSizeLow = parentSize.LowPart;
                parentItem->findInfo.nFileSizeHigh = parentSize.HighPart;

                // Apply external tool hpos on current file
                if ( procNmeaFile( currentItem.findInfo.cFileName,
                    currentItem.coords, COORDS ) == FALSE )
                {
                    wprintf_s( TEXT( "Processing NMEA file failed\n" ) );
                    return FALSE;
                }

                // Append current item to results list
                if ( AddItem( currentItem, resList ) == false )
                {
                    wprintf_s( TEXT( "Problem allocating memory\n" ) );
                    return FALSE;
                }
            }
        }

        // Reset current item
        memset( &currentItem, 0, sizeof( Item ) );

    } while ( FindNextFile( hFind, &currentItem.findInfo ) != 0 );

    // Validate end of search
    if ( GetLastError() != ERROR_NO_MORE_FILES )
    {
        ReportError( TEXT( "\nFindNextFile failed.\n" ), 0, TRUE );
        return FALSE;
    }

    // Close search handle
    FindClose( hFind );

    return TRUE;
}
Esempio n. 20
0
File: ctl.c Progetto: Kelimion/wine
BOOL WINAPI CertAddCTLContextToStore(HCERTSTORE hCertStore,
 PCCTL_CONTEXT pCtlContext, DWORD dwAddDisposition,
 PCCTL_CONTEXT* ppStoreContext)
{
    WINECRYPT_CERTSTORE *store = hCertStore;
    BOOL ret = TRUE;
    PCCTL_CONTEXT toAdd = NULL, existing = NULL;

    TRACE("(%p, %p, %08x, %p)\n", hCertStore, pCtlContext, dwAddDisposition,
     ppStoreContext);

    if (dwAddDisposition != CERT_STORE_ADD_ALWAYS)
    {
        existing = CertFindCTLInStore(hCertStore, 0, 0, CTL_FIND_EXISTING,
         pCtlContext, NULL);
    }

    switch (dwAddDisposition)
    {
    case CERT_STORE_ADD_ALWAYS:
        toAdd = CertDuplicateCTLContext(pCtlContext);
        break;
    case CERT_STORE_ADD_NEW:
        if (existing)
        {
            TRACE("found matching CTL, not adding\n");
            SetLastError(CRYPT_E_EXISTS);
            ret = FALSE;
        }
        else
            toAdd = CertDuplicateCTLContext(pCtlContext);
        break;
    case CERT_STORE_ADD_NEWER:
        if (existing)
        {
            LONG newer = CompareFileTime(&existing->pCtlInfo->ThisUpdate,
             &pCtlContext->pCtlInfo->ThisUpdate);

            if (newer < 0)
                toAdd = CertDuplicateCTLContext(pCtlContext);
            else
            {
                TRACE("existing CTL is newer, not adding\n");
                SetLastError(CRYPT_E_EXISTS);
                ret = FALSE;
            }
        }
        else
            toAdd = CertDuplicateCTLContext(pCtlContext);
        break;
    case CERT_STORE_ADD_NEWER_INHERIT_PROPERTIES:
        if (existing)
        {
            LONG newer = CompareFileTime(&existing->pCtlInfo->ThisUpdate,
             &pCtlContext->pCtlInfo->ThisUpdate);

            if (newer < 0)
            {
                toAdd = CertDuplicateCTLContext(pCtlContext);
                CtlContext_CopyProperties(existing, pCtlContext);
            }
            else
            {
                TRACE("existing CTL is newer, not adding\n");
                SetLastError(CRYPT_E_EXISTS);
                ret = FALSE;
            }
        }
        else
            toAdd = CertDuplicateCTLContext(pCtlContext);
        break;
    case CERT_STORE_ADD_REPLACE_EXISTING:
        toAdd = CertDuplicateCTLContext(pCtlContext);
        break;
    case CERT_STORE_ADD_REPLACE_EXISTING_INHERIT_PROPERTIES:
        toAdd = CertDuplicateCTLContext(pCtlContext);
        if (existing)
            CtlContext_CopyProperties(toAdd, existing);
        break;
    case CERT_STORE_ADD_USE_EXISTING:
        if (existing)
        {
            CtlContext_CopyProperties(existing, pCtlContext);
            if (ppStoreContext)
                *ppStoreContext = CertDuplicateCTLContext(existing);
        }
        else
            toAdd = CertDuplicateCTLContext(pCtlContext);
        break;
    default:
        FIXME("Unimplemented add disposition %d\n", dwAddDisposition);
        ret = FALSE;
    }

    if (toAdd)
    {
        if (store)
            ret = store->ctls.addContext(store, (void *)toAdd,
             (void *)existing, (const void **)ppStoreContext);
        else if (ppStoreContext)
            *ppStoreContext = CertDuplicateCTLContext(toAdd);
        CertFreeCTLContext(toAdd);
    }
    CertFreeCTLContext(existing);

    TRACE("returning %d\n", ret);
    return ret;
}
Esempio n. 21
0
LONG CScavengerNode::Compare(CScavengerNode *pItem1, CScavengerNode *pItem2)
{
    return CompareFileTime( &(pItem1->_ftLastAccess), &(pItem2->_ftLastAccess));
}
Esempio n. 22
0
void
Win32MUSH_setup(void)
{
  int indb_OK, outdb_OK, panicdb_OK;
  FILETIME indb_time, outdb_time, panicdb_time;
  long indb_size, outdb_size, panicdb_size;

#ifndef _DEBUG
  char FileName[256];
  if (GetModuleFileName(NULL, FileName, 256) != 0) {
    if (!strcasecmp(strrchr(FileName, '\\') + 1, "pennmush.exe")) {
      if (CopyFile("pennmush.exe", "pennmush_run.exe", FALSE)) {
        do_rawlog(LT_ERR, "Successfully copied executable, starting copy.");
#ifdef WIN32SERVICES
        execl("pennmush_run.exe", "pennmush_run.exe", "/run", NULL);
#else
        execl("pennmush_run.exe", "pennmush_run.exe", confname, NULL);
#endif
      }
    }
  }
#endif                          /*  */
  ConcatenateFiles("txt\\hlp\\*.hlp", "txt\\help.txt");
  ConcatenateFiles("txt\\nws\\*.nws", "txt\\news.txt");
  ConcatenateFiles("txt\\evt\\*.evt", "txt\\events.txt");
  ConcatenateFiles("txt\\rul\\*.rul", "txt\\rules.txt");
  ConcatenateFiles("txt\\idx\\*.idx", "txt\\index.txt");
  indb_OK = CheckDatabase(options.input_db, &indb_time, &indb_size);
  outdb_OK = CheckDatabase(options.output_db, &outdb_time, &outdb_size);
  panicdb_OK = CheckDatabase(options.crash_db, &panicdb_time, &panicdb_size);
  if (indb_OK) {                /* Look at outdb */
    if (outdb_OK) {             /* Look at panicdb */
      if (panicdb_OK) {         /* outdb or panicdb or indb */
        if (CompareFileTime(&panicdb_time, &outdb_time) > 0) {  /* panicdb or indb */
          if (CompareFileTime(&panicdb_time, &indb_time) > 0) { /* panicdb */
            ConcatenateFiles(options.crash_db, options.input_db);
          } else {              /* indb */
          }
        } else {                /* outdb or indb */
          if (CompareFileTime(&outdb_time, &indb_time) > 0) {   /* outdb */
            ConcatenateFiles(options.output_db, options.input_db);
          } else {              /* indb */
          }
        }
      } else {                  /* outdb or indb */
        if (CompareFileTime(&outdb_time, &indb_time) > 0) {     /* outdb */
          ConcatenateFiles(options.output_db, options.input_db);
        } else {                /* indb */
        }
      }
    } else {                    /* outdb not OK */
      if (panicdb_OK) {         /* panicdb or indb */
        if (CompareFileTime(&panicdb_time, &indb_time) > 0) {   /* panicdb */
          ConcatenateFiles(options.crash_db, options.input_db);
        } else {                /* indb */
        }
      } else {                  /* indb */
      }
    }
  } else {                      /* indb not OK */
    if (outdb_OK) {             /* look at panicdb */
      if (panicdb_OK) {         /* out or panic */
        if (CompareFileTime(&panicdb_time, &outdb_time) > 0) {  /* panicdb */
          ConcatenateFiles(options.crash_db, options.input_db);
        } else {                /* outdb */
          ConcatenateFiles(options.output_db, options.input_db);
        }
      } else {                  /* outdb */
        ConcatenateFiles(options.output_db, options.input_db);
      }
    } else {                    /* outdb not OK */
      if (panicdb_OK) {         /* panicdb */
        ConcatenateFiles(options.crash_db, options.input_db);
      } else {                  /* NOTHING */
        return;
      }
    }
  }

/* Final failsafe - input database SHOULD still be OK. */
  do_rawlog(LT_ERR, "Verifying selected database.");
  if (!CheckDatabase(options.input_db, &indb_time, &indb_size)) {
    do_rawlog(LT_ERR, "File corrupted during selection process.");
    exit(-1);
  } else {
    do_rawlog(LT_ERR, "Input database verified. Proceeding to analysis.");
  }
}
Esempio n. 23
0
UINT CFileEvent::FileEventProc (LPVOID lpParam)
  {
    CFileEvent *pFileEvent = (CFileEvent*) lpParam;
    int nFilePathCount = pFileEvent->m_lstFilePath.GetCount ();
    HANDLE *phChanges = new HANDLE[nFilePathCount + 1];
    for (int i;;)
      {
        *phChanges = pFileEvent->m_evWatching;
        POSITION pos = pos = pFileEvent->m_lstFilePath.GetHeadPosition ();
        CFilePath *pFilePath;
        int j = 0;
        for (i = 0; i < nFilePathCount; i++)
          {
            if (!pos)
              {
                nFilePathCount = i;
                break;
              }
            pFilePath = pFileEvent->m_lstFilePath.GetNext (pos);
            ASSERT (pFilePath);
            HANDLE hFC = FindFirstChangeNotification (pFilePath->GetPath(), FALSE,
              FILE_NOTIFY_CHANGE_LAST_WRITE|FILE_NOTIFY_CHANGE_SIZE|FILE_NOTIFY_CHANGE_FILE_NAME);
            if (hFC != INVALID_HANDLE_VALUE) // if i can gen a notification --
              phChanges[++j] = hFC;
          }
        DWORD dwResult = WaitForMultipleObjects (j + 1, phChanges, FALSE, INFINITE);
        for (i = 1; i < j; i++)
          VERIFY (FindCloseChangeNotification (phChanges[i + 1]));
        if (dwResult == WAIT_OBJECT_0)
          break;
        int nPath = dwResult - WAIT_OBJECT_0 - 1;
        pos = pFileEvent->m_lstFilePath.FindIndex (nPath);
        //ASSERT (pos);
		if(pos == 0)
		{
			break;
		}
        pFilePath = pFileEvent->m_lstFilePath.GetAt (pos);
        //ASSERT (pFilePath);
		if(pFilePath == NULL)
		{
			break;
		}
        CString sPathName;
        CFileInfo *pFileInfo;
        for (pos = pFileEvent->m_mapFileInfo.GetStartPosition (); pos;)
          {
            pFileEvent->m_mapFileInfo.GetNextAssoc (pos, sPathName, pFileInfo);
            ASSERT (pFileInfo);
            if (!_tcscmp (pFilePath->GetPath (), pFileInfo->GetPath ()))
              {
                HANDLE hFile = CreateFile (sPathName, GENERIC_READ, FILE_SHARE_READ /*|FILE_SHARE_WRITE|FILE_SHARE_DELETE*/,
                  NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
				// add at 2006-05-06 by blueant
				if (hFile == INVALID_HANDLE_VALUE)
				{
					// 文件保存过程中很大情况下返回的是无效句柄,需要延迟一段时间等保存完毕再打开
					Sleep(50);
					hFile = CreateFile (sPathName, GENERIC_READ, FILE_SHARE_READ /*|FILE_SHARE_WRITE|FILE_SHARE_DELETE*/,
						NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
				}
                if (hFile != INVALID_HANDLE_VALUE)
                  {
                    FILETIME ftModified;
                    VERIFY (GetFileTime (hFile, NULL, NULL, &ftModified));
                    DWORD dwSize;
					// ->HE
					dwSize= GetFileSize (hFile, NULL);
					ASSERT(dwSize != (DWORD)-1);
					// <-HE
                   CloseHandle (hFile);
                    WPARAM wEvent = FE_NONE;
                    if (CompareFileTime (&pFileInfo->GetModified (), &ftModified) < 0)
                      {
                        pFileInfo->SetModified (ftModified);
                        wEvent |= FE_CHANGED_TIME;
                      }
                    if (pFileInfo->GetSize () != dwSize)
                      {
                        pFileInfo->SetSize (dwSize);
                        wEvent |= FE_CHANGED_SIZE;
                      }
                    if (wEvent)
                      pFileEvent->OnFileEvent (wEvent, sPathName);
                  }
                else
                  {
                    pFileEvent->OnFileEvent (FE_DELETED, sPathName);
                    pFileEvent->RemoveFile (sPathName);
                  }
              }
          }
      }
    delete [] phChanges;
    return 0;
  }
Esempio n. 24
0
unsigned int __stdcall MyThreadFunction(void*) {
    EGraphicsApi graphicsApi = EGraphicsApi::D3D11;
    if (!LoadRenderApiImpl(graphicsApi)) {
        s_running.store(false);
        return 1;
    }

    // Init time
    QueryPerformanceFrequency(&s_perfFreq);
    QueryPerformanceCounter(&s_lastTime);

    GameInfo gameInfo;
    ZeroMemory(&gameInfo, sizeof(gameInfo));
    gameInfo.graphicsApi = graphicsApi;
    gameInfo.imguiState = ImGui::GetCurrentContext();
    //heapArea = new HeapArea(512 * 1024 * 1024);
    //memory::SimpleArena arena(heapArea);
    //gameInfo.allocator = &arena;
    gameInfo.CalculateDeltaTime = CalculateDeltaTime;
    gameInfo.gfxFuncs = g_renderApi;
    gameInfo.config = &s_config;
    gameInfo.controls = &s_controls;
    gameInfo.CreateThread = slCreateThread;
    gameInfo.reloadOnSave = true;

    // Hardware info
    {
        SYSTEM_INFO sysinfo;
        GetSystemInfo(&sysinfo);
        s_hardware.numLogicalThreads = (uint32_t) sysinfo.dwNumberOfProcessors;
    }
    
    gameInfo.hardware = &s_hardware;

    // ENet
    if (enet_initialize() != 0)
    {
        s_running.store(false);
        return 1;
    }

    // Main loop
    while (s_running.load())
    {
        // Check if graphics API change was requested
        if (gameInfo.graphicsApi != graphicsApi) {
            if (LoadRenderApiImpl(gameInfo.graphicsApi)) {
                graphicsApi = gameInfo.graphicsApi;
                g_renderApi = gameInfo.gfxFuncs;
            } else {
                gameInfo.graphicsApi = graphicsApi;
                gameInfo.gfxFuncs = g_renderApi;
            }
        }

#ifdef _DEBUG
        {
            // Reload DLL
            FILETIME NewDLLWriteTime = Win32GetLastWriteTime((char*)s_dllName);

            // If the .DLL is being written to, the last write time may change multiple times
            // So we need to add a cooldown
            LARGE_INTEGER currentTime;
            QueryPerformanceCounter(&currentTime);

            if (CompareFileTime(&NewDLLWriteTime, &s_gameFuncs.DLLLastWriteTime) != 0
                && (currentTime.QuadPart - s_lastDLLLoadTime.QuadPart) / s_perfFreq.QuadPart >= 1) {

                if (s_gameFuncs.dll) {
                    FreeLibrary(s_gameFuncs.dll);
                }

                s_gameFuncs = LoadGameFuncs();
                g_LogInfo("Reloaded DLL.");
            } else {
                // Ignore changes
                s_gameFuncs.DLLLastWriteTime = NewDLLWriteTime;
            }
        }
#endif

        // Reload Lua
        if (gameInfo.reloadOnSave) {
            DWORD obj = WaitForSingleObject(hDirectoryChange, 0);
            if (obj == WAIT_OBJECT_0) {
                if (!FindNextChangeNotification(hDirectoryChange)) {
                    g_LogInfo("Error: FindNextChangeNotification failed.");
                }
                
                // TODO: Change only of lua files changed (or make separate lua directory)
                LARGE_INTEGER currentTime;
                static LARGE_INTEGER s_lastLuaLoadTime;
                QueryPerformanceCounter(&currentTime);

                if ((currentTime.QuadPart - s_lastLuaLoadTime.QuadPart) / s_perfFreq.QuadPart >= 1) {
                    s_lastLuaLoadTime = currentTime;
                    gameInfo.reloadLua = true;
                }
            }
        }

        ParseMessages();

        g_renderApi->ImGuiNewFrame();
        s_controls.BeginFrame();

        s_gameFuncs.UpdateGame(&gameInfo);

        s_controls.EndFrame();

        // Rendering
        g_renderApi->Render();
    }

    s_gameFuncs.DestroyGame(&gameInfo);
    g_renderApi->Destroy();
    ImGui::Shutdown();
    g_renderApi = nullptr;

    //delete heapArea;

    enet_deinitialize();

    return 0;
}
Esempio n. 25
0
// returns true if at least one set of skin data was read, else false...
//
static bool Skins_Read(LPCSTR psModelFilename)
{
	LPCSTR psError = NULL;

	CWaitCursor;

	LPCSTR psSkinsPath = Skins_ModelNameToSkinPath(psModelFilename);	// eg "models/characters/skins"

	if (psSkinsPath)
	{
		string strThisModelBaseName(String_ToLower(Filename_WithoutExt(Filename_WithoutPath(psModelFilename))));

		char **ppsSkinFiles;
		int iSkinFiles;

		// scan for skin files...
		//
		ppsSkinFiles =	//ri.FS_ListFiles( "shaders", ".shader", &iSkinFiles );
						Sys_ListFiles(	va("%s%s",gamedir,psSkinsPath),// const char *directory, 
										".g2skin",	// const char *extension, 
										NULL,		// char *filter, 
										&iSkinFiles,// int *numfiles, 
										qfalse		// qboolean wantsubs 
										);

		if ( !ppsSkinFiles || !iSkinFiles )
		{
			CurrentSkins.clear();	
			CurrentSkinsSurfacePrefs.clear();
			return false;
		}

		if ( iSkinFiles > MAX_SKIN_FILES ) 
		{
			WarningBox(va("%d skin files found, capping to %d\n\n(tell me if this ever happens -Ste)", iSkinFiles, MAX_SKIN_FILES ));

			iSkinFiles = MAX_SKIN_FILES;
		}

		// load and parse skin files...
		//					
		// for now, I just scan each file and if it's out of date then I invalidate it's model-prefs info...
		//
		extern bool GetFileTime(LPCSTR psFileName, FILETIME &ft);
		for (int i=0; i<iSkinFiles; i++)
		{
			bool bReParseThisFile = false;

			char sFileName[MAX_QPATH];
			LPCSTR psFileName = ppsSkinFiles[i];
			Com_sprintf( sFileName, sizeof( sFileName ), "%s/%s", psSkinsPath, psFileName );
			psFileName = &sFileName[0];
											  
			// have a go at getting this time/date stamp if not already present...
			//
			if (!SkinFileTimeDates[psFileName].bValid)
			{
				FILETIME ft;
				if (GetFileTime(psFileName, ft))
				{
					SkinFileTimeDates[psFileName].ft = ft;
					SkinFileTimeDates[psFileName].bValid = true;
				}
			}

			// now see if there's a valid time-stamp, and use it if so, else give up and re-scan all files...
			//
			if (SkinFileTimeDates[psFileName].bValid)
			{
				FILETIME ft;
				if (GetFileTime(psFileName, ft))
				{
					LONG l = CompareFileTime( &SkinFileTimeDates[psFileName].ft, &ft);

					bReParseThisFile = (l<0);
				}
				else
				{
					bReParseThisFile = true;
				}
			}
			else
			{
				bReParseThisFile = true;
			}	
			
			if (bReParseThisFile)
			{
				G2SkinModelPrefs[sFileName].clear();
			}
		}		
		
		if (1)//bReParseSkinFiles || !CurrentSkins.size())
		{
			CurrentSkins.clear();	
			CurrentSkinsSurfacePrefs.clear();

			char *buffers[MAX_SKIN_FILES]={0};
//			long iTotalBytesLoaded = 0;
			for ( int i=0; i<iSkinFiles && !psError; i++ )
			{
				char sFileName[MAX_QPATH];

				string strThisSkinFile(ppsSkinFiles[i]);

				Com_sprintf( sFileName, sizeof( sFileName ), "%s/%s", psSkinsPath, strThisSkinFile.c_str() );
				StatusMessage( va("Scanning skin %d/%d: \"%s\"...",i+1,iSkinFiles,sFileName));

				//ri.Printf( PRINT_ALL, "...loading '%s'\n", sFileName );

				bool _bDiskLoadOccured = false;	// debug use only, but wtf?

#define LOAD_SKIN_FILE									\
/*iTotalBytesLoaded += */ ri.FS_ReadFile( sFileName, (void **)&buffers[i] );	\
if ( !buffers[i] )										\
{														\
	CurrentSkins.clear();								\
	CurrentSkinsSurfacePrefs.clear();					\
														\
	ri.Error( ERR_DROP, "Couldn't load %s", sFileName );\
}														\
_bDiskLoadOccured = true;


				// see if we should pay attention to the contents of this file...
				//
				CGPGroup	*pFileGroup			= NULL;
				CGPGroup *pParseGroup_Prefs	= NULL;
				CGenericParser2 SkinParser;
				//
				bool bParseThisFile = false;
				//
				// if we have any information about this skin file as regards what models it refers to, use the info...
				//
				if (G2SkinModelPrefs[sFileName].size())
				{
					map<string, int>::iterator it = G2SkinModelPrefs[sFileName].find( strThisModelBaseName );
					if (it != G2SkinModelPrefs[sFileName].end())
					{
						// this skin file contains this entry, so just check that we can setup the parse groups ok...
						//
						LOAD_SKIN_FILE;

						char *psDataPtr = buffers[i];
						if (SkinParser.Parse(&psDataPtr, true))
						{
							pFileGroup = SkinParser.GetBaseParseGroup();
							if (pFileGroup)
							{
								pParseGroup_Prefs = pFileGroup->FindSubGroup(sSKINKEYWORD_PREFS);//, true);
								if (pParseGroup_Prefs)
								{
									bParseThisFile = true;
								}
							}
						}
						else
						{
							ErrorBox(va("{} - Brace mismatch error in file \"%s\"!",sFileName));
						}
					}
				}
				else
				{
					// no size info for this file, so check it manually...
					//
					LOAD_SKIN_FILE;

					if (Skins_ParseThisFile(SkinParser, buffers[i], strThisModelBaseName, pFileGroup, pParseGroup_Prefs, 
											sFileName, G2SkinModelPrefs)
						)
					{
						bParseThisFile = true;
					}
				}

				if (bParseThisFile)
				{
					psError = Skins_Parse( strThisSkinFile, pFileGroup, pParseGroup_Prefs);
					if (psError)
					{
						ErrorBox(va("Skins_Read(): Error reading file \"%s\"!\n\n( Skins will be ignored for this model )\n\nError was:\n\n",sFileName,psError));
					}
				}
				else
				{
					//OutputDebugString(va("Skipping parse of file \"%s\" %s\n",sFileName, _bDiskLoadOccured?"":"( and no load! )"));
				}
			}
			//
			// free loaded skin files...
			//
			for ( i=0; i<iSkinFiles; i++ )
			{
				if (buffers[i])
				{
					ri.FS_FreeFile( buffers[i] );
				}
			}
		}

		StatusMessage(NULL);
		Sys_FreeFileList( ppsSkinFiles );
	}
	else
	{
		CurrentSkins.clear();	
		CurrentSkinsSurfacePrefs.clear();
	}

	if (psError)
	{
		return false;
	}

	return !!(CurrentSkins.size());
}
Esempio n. 26
0
/*
 * Class:     sun_security_krb5_Credentials
 * Method:    acquireDefaultNativeCreds
 * Signature: ()Lsun/security/krb5/Credentials;
 */
JNIEXPORT jobject JNICALL Java_sun_security_krb5_Credentials_acquireDefaultNativeCreds(
                JNIEnv *env,
                jclass krbcredsClass) {

        KERB_QUERY_TKT_CACHE_REQUEST CacheRequest;
        PKERB_RETRIEVE_TKT_RESPONSE TktCacheResponse = NULL;
        PKERB_RETRIEVE_TKT_REQUEST pTicketRequest = NULL;
        PKERB_RETRIEVE_TKT_RESPONSE pTicketResponse = NULL;
        NTSTATUS Status, SubStatus;
        ULONG requestSize = 0;
        ULONG responseSize = 0;
        ULONG rspSize = 0;
        HANDLE LogonHandle = NULL;
        ULONG PackageId;
        jobject ticket, clientPrincipal, targetPrincipal, encryptionKey;
        jobject ticketFlags, startTime, endTime, krbCreds = NULL;
        jobject authTime, renewTillTime, hostAddresses = NULL;
        KERB_EXTERNAL_TICKET *msticket;
        int ignore_cache = 0;
        FILETIME Now, EndTime, LocalEndTime;

        while (TRUE) {

        if (krbcredsConstructor == 0) {
                krbcredsConstructor = (*env)->GetMethodID(env, krbcredsClass, "<init>",
        "(Lsun/security/krb5/internal/Ticket;Lsun/security/krb5/PrincipalName;Lsun/security/krb5/PrincipalName;Lsun/security/krb5/EncryptionKey;Lsun/security/krb5/internal/TicketFlags;Lsun/security/krb5/internal/KerberosTime;Lsun/security/krb5/internal/KerberosTime;Lsun/security/krb5/internal/KerberosTime;Lsun/security/krb5/internal/KerberosTime;Lsun/security/krb5/internal/HostAddresses;)V");
            if (krbcredsConstructor == 0) {
                printf("Couldn't find sun.security.krb5.Credentials constructor\n");
                break;
            }
        }

        #ifdef DEBUG
        printf("Found KrbCreds constructor\n");
        #endif

        //
        // Get the logon handle and package ID from the
        // Kerberos package
        //
        if (!PackageConnectLookup(&LogonHandle, &PackageId))
            break;

        #ifdef DEBUG
        printf("Got handle to Kerberos package\n");
        #endif /* DEBUG */

        // Get the MS TGT from cache
        CacheRequest.MessageType = KerbRetrieveTicketMessage;
        CacheRequest.LogonId.LowPart = 0;
        CacheRequest.LogonId.HighPart = 0;

        Status = LsaCallAuthenticationPackage(
                        LogonHandle,
                        PackageId,
                        &CacheRequest,
                        sizeof(CacheRequest),
                        &TktCacheResponse,
                        &rspSize,
                        &SubStatus
                        );

        #ifdef DEBUG
        printf("Response size is %d\n", rspSize);
        #endif

        if (!LSA_SUCCESS(Status) || !LSA_SUCCESS(SubStatus)) {
            if (!LSA_SUCCESS(Status)) {
                ShowNTError("LsaCallAuthenticationPackage", Status);
            } else {
                ShowNTError("Protocol status", SubStatus);
            }
            break;
        }

        // got the native MS TGT
        msticket = &(TktCacheResponse->Ticket);

        // check TGT validity
        switch (msticket->SessionKey.KeyType) {
            case KERB_ETYPE_DES_CBC_CRC:
            case KERB_ETYPE_DES_CBC_MD5:
            case KERB_ETYPE_NULL:
            case KERB_ETYPE_RC4_HMAC_NT:
                GetSystemTimeAsFileTime(&Now);
                EndTime.dwLowDateTime = msticket->EndTime.LowPart;
                EndTime.dwHighDateTime = msticket->EndTime.HighPart;
                FileTimeToLocalFileTime(&EndTime, &LocalEndTime);
                if (CompareFileTime(&Now, &LocalEndTime) >= 0) {
                    ignore_cache = 1;
                }
                if (msticket->TicketFlags & KERB_TICKET_FLAGS_invalid) {
                    ignore_cache = 1;
                }
                break;
            case KERB_ETYPE_RC4_MD4:
            default:
                // not supported
                ignore_cache = 1;
                break;
        }

        if (ignore_cache) {
            #ifdef DEBUG
            printf("MS TGT in cache is invalid/not supported; request new ticket\n");
            #endif /* DEBUG */

            // use domain to request Ticket
            Status = ConstructTicketRequest(msticket->TargetDomainName,
                                &pTicketRequest, &requestSize);
            if (!LSA_SUCCESS(Status)) {
                ShowNTError("ConstructTicketRequest status", Status);
                break;
            }

            pTicketRequest->MessageType = KerbRetrieveEncodedTicketMessage;
            pTicketRequest->EncryptionType = KERB_ETYPE_DES_CBC_MD5;
            pTicketRequest->CacheOptions = KERB_RETRIEVE_TICKET_DONT_USE_CACHE;

            Status = LsaCallAuthenticationPackage(
                        LogonHandle,
                        PackageId,
                        pTicketRequest,
                        requestSize,
                        &pTicketResponse,
                        &responseSize,
                        &SubStatus
                        );

            #ifdef DEBUG
            printf("Response size is %d\n", responseSize);
            #endif /* DEBUG */

            if (!LSA_SUCCESS(Status) || !LSA_SUCCESS(SubStatus)) {
                if (!LSA_SUCCESS(Status)) {
                    ShowNTError("LsaCallAuthenticationPackage", Status);
                } else {
                    ShowNTError("Protocol status", SubStatus);
                }
                break;
            }

            // got the native MS Kerberos TGT
            msticket = &(pTicketResponse->Ticket);
        }

/*

typedef struct _KERB_RETRIEVE_TKT_RESPONSE {
    KERB_EXTERNAL_TICKET Ticket;
} KERB_RETRIEVE_TKT_RESPONSE, *PKERB_RETRIEVE_TKT_RESPONSE;

typedef struct _KERB_EXTERNAL_TICKET {
    PKERB_EXTERNAL_NAME ServiceName;
    PKERB_EXTERNAL_NAME TargetName;
    PKERB_EXTERNAL_NAME ClientName;
    UNICODE_STRING DomainName;
    UNICODE_STRING TargetDomainName;
    UNICODE_STRING AltTargetDomainName;
    KERB_CRYPTO_KEY SessionKey;
    ULONG TicketFlags;
    ULONG Flags;
    LARGE_INTEGER KeyExpirationTime;
    LARGE_INTEGER StartTime;
    LARGE_INTEGER EndTime;
    LARGE_INTEGER RenewUntil;
    LARGE_INTEGER TimeSkew;
    ULONG EncodedTicketSize;
    PUCHAR EncodedTicket; <========== Here's the good stuff
} KERB_EXTERNAL_TICKET, *PKERB_EXTERNAL_TICKET;

typedef struct _KERB_EXTERNAL_NAME {
    SHORT NameType;
    USHORT NameCount;
    UNICODE_STRING Names[ANYSIZE_ARRAY];
} KERB_EXTERNAL_NAME, *PKERB_EXTERNAL_NAME;

typedef struct _LSA_UNICODE_STRING {
    USHORT Length;
    USHORT MaximumLength;
    PWSTR  Buffer;
} LSA_UNICODE_STRING, *PLSA_UNICODE_STRING;

typedef LSA_UNICODE_STRING UNICODE_STRING, *PUNICODE_STRING;

typedef struct KERB_CRYPTO_KEY {
    LONG KeyType;
    ULONG Length;
    PUCHAR Value;
} KERB_CRYPTO_KEY, *PKERB_CRYPTO_KEY;

*/
        // Build a com.sun.security.krb5.Ticket
        ticket = BuildTicket(env, msticket->EncodedTicket,
                                msticket->EncodedTicketSize);
        if (ticket == NULL) {
                break;
        }
        // OK, have a Ticket, now need to get the client name
        clientPrincipal = BuildPrincipal(env, msticket->ClientName,
                                msticket->TargetDomainName); // mdu
        if (clientPrincipal == NULL) {
                break;
        }

        // and the "name" of tgt
        targetPrincipal = BuildPrincipal(env, msticket->ServiceName,
                        msticket->DomainName);
        if (targetPrincipal == NULL) {
                break;
        }

        // Get the encryption key
        encryptionKey = BuildEncryptionKey(env, &(msticket->SessionKey));
        if (encryptionKey == NULL) {
                break;
        }

        // and the ticket flags
        ticketFlags = BuildTicketFlags(env, &(msticket->TicketFlags));
        if (ticketFlags == NULL) {
                break;
        }

        // Get the start time
        startTime = BuildKerberosTime(env, &(msticket->StartTime));
        if (startTime == NULL) {
                break;
        }

        /*
         * mdu: No point storing the eky expiration time in the auth
         * time field. Set it to be same as startTime. Looks like
         * windows does not have post-dated tickets.
         */
        authTime = startTime;

        // and the end time
        endTime = BuildKerberosTime(env, &(msticket->EndTime));
        if (endTime == NULL) {
                break;
        }

        // Get the renew till time
        renewTillTime = BuildKerberosTime(env, &(msticket->RenewUntil));
        if (renewTillTime == NULL) {
                break;
        }

        // and now go build a KrbCreds object
        krbCreds = (*env)->NewObject(
                env,
                krbcredsClass,
                krbcredsConstructor,
                ticket,
                clientPrincipal,
                targetPrincipal,
                encryptionKey,
                ticketFlags,
                authTime, // mdu
                startTime,
                endTime,
                renewTillTime, //mdu
                hostAddresses);

        break;
        } // end of WHILE

        // clean up resources
        if (TktCacheResponse != NULL) {
                LsaFreeReturnBuffer(TktCacheResponse);
        }
        if (pTicketRequest) {
                LocalFree(pTicketRequest);
        }
        if (pTicketResponse != NULL) {
                LsaFreeReturnBuffer(pTicketResponse);
        }

        return krbCreds;
}
int CLibraryDetailView::ListCompare(LPCVOID pA, LPCVOID pB)
{
	LDVITEM* ppA	= (LDVITEM*)pA;
	LDVITEM* ppB	= (LDVITEM*)pB;
	int nTest		= 0;

	CLibraryFile* pfA = Library.LookupFile( ppA->nIndex );
	CLibraryFile* pfB = Library.LookupFile( ppB->nIndex );

	if ( ! pfA || ! pfB ) return 0;

	switch ( m_pThis->m_nSortColumn )
	{
	case 0:
		nTest = _tcsicoll( pfA->m_sName, pfB->m_sName );
		break;
	case 1:
		{
			LPCTSTR pszA = _tcsrchr( pfA->m_sName, '.' );
			LPCTSTR pszB = _tcsrchr( pfB->m_sName, '.' );
			if ( ! pszA || ! pszB ) return 0;
			nTest = _tcsicoll( pszA, pszB );
			break;
		}
	case 2:
		if ( pfA->GetSize() == pfB->GetSize() )
			nTest = 0;
		else if ( pfA->GetSize() < pfB->GetSize() )
			nTest = -1;
		else
			nTest = 1;
		break;
	case 3:
		if ( pfA->m_pFolder == NULL || pfB->m_pFolder == NULL ) return 0;
		nTest = _tcsicoll( pfA->m_pFolder->m_sPath, pfB->m_pFolder->m_sPath );
		break;
	case 4:
		if ( pfA->m_nHitsTotal == pfB->m_nHitsTotal )
			nTest = 0;
		else if ( pfA->m_nHitsTotal < pfB->m_nHitsTotal )
			nTest = -1;
		else
			nTest = 1;
		break;
	case 5:
		if ( pfA->m_nUploadsTotal == pfB->m_nUploadsTotal )
			nTest = 0;
		else if ( pfA->m_nUploadsTotal < pfB->m_nUploadsTotal )
			nTest = -1;
		else
			nTest = 1;
		break;
	case 6:
		nTest = CompareFileTime( &pfA->m_pTime, &pfB->m_pTime );
		break;
	default:
		{
			int nColumn = m_pThis->m_nSortColumn - DETAIL_COLUMNS;
			if ( nColumn >= m_pThis->m_pColumns.GetCount() ) return 0;
			POSITION pos = m_pThis->m_pColumns.FindIndex( nColumn );
			if ( pos == NULL ) return 0;
			CSchemaMember* pMember = (CSchemaMember*)m_pThis->m_pColumns.GetAt( pos );

			CString strA, strB;
			if ( pfA->m_pMetadata ) strA = pMember->GetValueFrom( pfA->m_pMetadata, NULL, TRUE );
			if ( pfB->m_pMetadata ) strB = pMember->GetValueFrom( pfB->m_pMetadata, NULL, TRUE );

			if ( *(LPCTSTR)strA && *(LPCTSTR)strB &&
				( ((LPCTSTR)strA)[ _tcslen( strA ) - 1 ] == 'k' || ((LPCTSTR)strA)[ _tcslen( strA ) - 1 ] == '~' )
				&&
				( ((LPCTSTR)strB)[ _tcslen( strB ) - 1 ] == 'k' || ((LPCTSTR)strB)[ _tcslen( strB ) - 1 ] == '~' ) )
			{
				nTest = CLiveList::SortProc( strA, strB, TRUE );
			}
			else
			{
				nTest = _tcsicoll( strA, strB );
			}
		}
	}

	if ( ! m_pThis->m_bSortFlip ) nTest = -nTest;

	return nTest;
}
bool CSorter::operator() (const CTGitPath* entry1 , const CTGitPath* entry2) const
{
#define SGN(x) ((x)==0?0:((x)>0?1:-1))

	int result = 0;
	switch (sortedColumn)
	{
	case 7: // File size
		{
			if (result == 0)
			{
				__int64 fileSize1 = entry1->IsDirectory() ? 0 : entry1->GetFileSize();
				__int64 fileSize2 = entry2->IsDirectory() ? 0 : entry2->GetFileSize();
				
				result = int(fileSize1 - fileSize2);
			}
		}
	case 6: //Last Modification Date
		{
			if (result == 0)
			{
				__int64 writetime1 = entry1->GetLastWriteTime();
				__int64 writetime2 = entry2->GetLastWriteTime();

				FILETIME* filetime1 = (FILETIME*)(__int64*)&writetime1;
				FILETIME* filetime2 = (FILETIME*)(__int64*)&writetime2;

				result = CompareFileTime(filetime1, filetime2);
			}
		}
	case 5: //Del Number
		{
			if (result == 0)
			{
//				result = entry1->lock_comment.CompareNoCase(entry2->lock_comment);
				result = A2L(entry1->m_StatDel)-A2L(entry2->m_StatDel);
			}
		}
	case 4: //Add Number
		{
			if (result == 0)
			{
				//result = entry1->lock_owner.CompareNoCase(entry2->lock_owner);
				result = A2L(entry1->m_StatAdd)-A2L(entry2->m_StatAdd);
			}
		}

	case 3: // Status
		{
			if (result == 0)
			{
				result = entry1->GetActionName(entry1->m_Action).CompareNoCase(entry2->GetActionName(entry2->m_Action));
			}
		}
	case 2: //Ext file
		{
			if (result == 0)
			{
				result = entry1->GetFileExtension().CompareNoCase(entry2->GetFileExtension());
			}
		}
	case 1: // File name
		{
			if (result == 0)
			{
				result = entry1->GetFileOrDirectoryName().CompareNoCase(entry2->GetFileOrDirectoryName());
			}
		}
	case 0: // Full path column
		{
			if (result == 0)
			{
				result = CTGitPath::Compare(entry1->GetGitPathString(), entry2->GetGitPathString());
			}
		}
	} // switch (m_nSortedColumn)
	if (!ascending)
		result = -result;

	return result < 0;
}
Esempio n. 29
0
bool CDateTime::operator ==(const FILETIME& right) const
{
  return CompareFileTime(&m_time, &right)==0;
}
Esempio n. 30
0
File: time.c Progetto: sambuc/netbsd
int
isc_time_compare(const isc_time_t *t1, const isc_time_t *t2) {
	REQUIRE(t1 != NULL && t2 != NULL);

	return ((int)CompareFileTime(&t1->absolute, &t2->absolute));
}