//************************************************************* LLSD WINAPI Get_Exception_Info(PEXCEPTION_POINTERS pException) //************************************************************* // Allocate Str[DUMP_SIZE_MAX] and return Str with dump, if !pException - just return call stack in Str. { LLSD info; LPWSTR Str; int Str_Len; // int i; LPWSTR Module_Name = new WCHAR[MAX_PATH]; PBYTE Module_Addr; HANDLE hFile; FILETIME Last_Write_Time; FILETIME Local_File_Time; SYSTEMTIME T; Str = new WCHAR[DUMP_SIZE_MAX]; Str_Len = 0; if (!Str) return NULL; Get_Version_Str(info); GetModuleFileName(NULL, Str, MAX_PATH); info["Process"] = ll_convert_wide_to_string(Str); info["ThreadID"] = (S32)GetCurrentThreadId(); // If exception occurred. if (pException) { EXCEPTION_RECORD & E = *pException->ExceptionRecord; CONTEXT & C = *pException->ContextRecord; // If module with E.ExceptionAddress found - save its path and date. if (Get_Module_By_Ret_Addr((PBYTE)E.ExceptionAddress, Module_Name, Module_Addr)) { info["Module"] = ll_convert_wide_to_string(Module_Name); if ((hFile = CreateFile(Module_Name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) != INVALID_HANDLE_VALUE) { if (GetFileTime(hFile, NULL, NULL, &Last_Write_Time)) { FileTimeToLocalFileTime(&Last_Write_Time, &Local_File_Time); FileTimeToSystemTime(&Local_File_Time, &T); info["DateModified"] = llformat("%02d/%02d/%d", T.wMonth, T.wDay, T.wYear); } CloseHandle(hFile); } } else { info["ExceptionAddr"] = (int)E.ExceptionAddress; } info["ExceptionCode"] = (int)E.ExceptionCode; /* //TODO: Fix this if (E.ExceptionCode == EXCEPTION_ACCESS_VIOLATION) { // Access violation type - Write/Read. LLSD exception_info; exception_info["Type"] = E.ExceptionInformation[0] ? "Write" : "Read"; exception_info["Address"] = llformat("%08x", E.ExceptionInformation[1]); info["Exception Information"] = exception_info; } */ // Save instruction that caused exception. /* std::string str; for (i = 0; i < 16; i++) str += llformat(" %02X", PBYTE(E.ExceptionAddress)[i]); info["Instruction"] = str; */ LLSD registers; registers["EAX"] = (int)C.Eax; registers["EBX"] = (int)C.Ebx; registers["ECX"] = (int)C.Ecx; registers["EDX"] = (int)C.Edx; registers["ESI"] = (int)C.Esi; registers["EDI"] = (int)C.Edi; registers["ESP"] = (int)C.Esp; registers["EBP"] = (int)C.Ebp; registers["EIP"] = (int)C.Eip; registers["EFlags"] = (int)C.EFlags; info["Registers"] = registers; } //if (pException) // Save call stack info. Get_Call_Stack(pException->ExceptionRecord, pException->ContextRecord, info); return info; } //Get_Exception_Info
static DIRECTORY_STACK *WCMD_list_directory (DIRECTORY_STACK *inputparms, int level) { WCHAR string[1024], datestring[32], timestring[32]; WCHAR real_path[MAX_PATH]; WIN32_FIND_DATAW *fd; FILETIME ft; SYSTEMTIME st; HANDLE hff; int dir_count, file_count, entry_count, i, widest, cur_width, tmp_width; int numCols, numRows; int rows, cols; ULARGE_INTEGER byte_count, file_size; DIRECTORY_STACK *parms; int concurrentDirs = 0; BOOL done_header = FALSE; static const WCHAR fmtDir[] = {'%','1','0','s',' ',' ','%','8','s',' ',' ', '<','D','I','R','>',' ',' ',' ',' ',' ',' ',' ',' ',' ','\0'}; static const WCHAR fmtFile[] = {'%','1','0','s',' ',' ','%','8','s',' ',' ', ' ',' ','%','1','0','s',' ',' ','\0'}; static const WCHAR fmt2[] = {'%','-','1','3','s','\0'}; static const WCHAR fmt3[] = {'%','-','2','3','s','\0'}; static const WCHAR fmt4[] = {'%','s','\0'}; static const WCHAR fmt5[] = {'%','s','%','s','\0'}; dir_count = 0; file_count = 0; entry_count = 0; byte_count.QuadPart = 0; widest = 0; cur_width = 0; /* Loop merging all the files from consecutive parms which relate to the same directory. Note issuing a directory header with no contents mirrors what windows does */ parms = inputparms; fd = HeapAlloc(GetProcessHeap(),0,sizeof(WIN32_FIND_DATAW)); while (parms && strcmpW(inputparms->dirName, parms->dirName) == 0) { concurrentDirs++; /* Work out the full path + filename */ strcpyW(real_path, parms->dirName); strcatW(real_path, parms->fileName); /* Load all files into an in memory structure */ WINE_TRACE("Looking for matches to '%s'\n", wine_dbgstr_w(real_path)); hff = FindFirstFileW(real_path, (fd+entry_count)); if (hff != INVALID_HANDLE_VALUE) { do { /* Skip any which are filtered out by attribute */ if (((fd+entry_count)->dwFileAttributes & attrsbits) != showattrs) continue; entry_count++; /* Keep running track of longest filename for wide output */ if (wide || orderByCol) { int tmpLen = strlenW((fd+(entry_count-1))->cFileName) + 3; if ((fd+(entry_count-1))->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) tmpLen = tmpLen + 2; if (tmpLen > widest) widest = tmpLen; } fd = HeapReAlloc(GetProcessHeap(),0,fd,(entry_count+1)*sizeof(WIN32_FIND_DATAW)); if (fd == NULL) { FindClose (hff); WINE_ERR("Out of memory\n"); errorlevel = 1; return parms->next; } } while (FindNextFileW(hff, (fd+entry_count)) != 0); FindClose (hff); } /* Work out the actual current directory name without a trailing \ */ strcpyW(real_path, parms->dirName); real_path[strlenW(parms->dirName)-1] = 0x00; /* Output the results */ if (!bare) { if (level != 0 && (entry_count > 0)) WCMD_output (newline); if (!recurse || ((entry_count > 0) && done_header==FALSE)) { static const WCHAR headerW[] = {'D','i','r','e','c','t','o','r','y',' ','o','f', ' ','%','s','\n','\n','\0'}; WCMD_output (headerW, real_path); done_header = TRUE; } } /* Move to next parm */ parms = parms->next; } /* Handle case where everything is filtered out */ if (entry_count > 0) { /* Sort the list of files */ qsort (fd, entry_count, sizeof(WIN32_FIND_DATAW), WCMD_dir_sort); /* Work out the number of columns */ WINE_TRACE("%d entries, maxwidth=%d, widest=%d\n", entry_count, max_width, widest); if (wide || orderByCol) { numCols = max(1, (int)max_width / widest); numRows = entry_count / numCols; if (entry_count % numCols) numRows++; } else { numCols = 1; numRows = entry_count; } WINE_TRACE("cols=%d, rows=%d\n", numCols, numRows); for (rows=0; rows<numRows; rows++) { BOOL addNewLine = TRUE; for (cols=0; cols<numCols; cols++) { WCHAR username[24]; /* Work out the index of the entry being pointed to */ if (orderByCol) { i = (cols * numRows) + rows; if (i >= entry_count) continue; } else { i = (rows * numCols) + cols; if (i >= entry_count) continue; } /* /L convers all names to lower case */ if (lower) { WCHAR *p = (fd+i)->cFileName; while ( (*p = tolower(*p)) ) ++p; } /* /Q gets file ownership information */ if (usernames) { strcpyW (string, inputparms->dirName); strcatW (string, (fd+i)->cFileName); WCMD_getfileowner(string, username, sizeof(username)/sizeof(WCHAR)); } if (dirTime == Written) { FileTimeToLocalFileTime (&(fd+i)->ftLastWriteTime, &ft); } else if (dirTime == Access) { FileTimeToLocalFileTime (&(fd+i)->ftLastAccessTime, &ft); } else { FileTimeToLocalFileTime (&(fd+i)->ftCreationTime, &ft); } FileTimeToSystemTime (&ft, &st); GetDateFormatW(0, DATE_SHORTDATE, &st, NULL, datestring, sizeof(datestring)/sizeof(WCHAR)); GetTimeFormatW(0, TIME_NOSECONDS, &st, NULL, timestring, sizeof(timestring)/sizeof(WCHAR)); if (wide) { tmp_width = cur_width; if ((fd+i)->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { static const WCHAR fmt[] = {'[','%','s',']','\0'}; WCMD_output (fmt, (fd+i)->cFileName); dir_count++; tmp_width = tmp_width + strlenW((fd+i)->cFileName) + 2; } else { static const WCHAR fmt[] = {'%','s','\0'}; WCMD_output (fmt, (fd+i)->cFileName); tmp_width = tmp_width + strlenW((fd+i)->cFileName) ; file_count++; file_size.u.LowPart = (fd+i)->nFileSizeLow; file_size.u.HighPart = (fd+i)->nFileSizeHigh; byte_count.QuadPart += file_size.QuadPart; } cur_width = cur_width + widest; if ((cur_width + widest) > max_width) { cur_width = 0; } else { int padding = cur_width - tmp_width; int toWrite = 0; WCHAR temp[101]; /* Note: WCMD_output uses wvsprintf which does not allow %* so manually pad with spaces to appropriate width */ strcpyW(temp, emptyW); while (padding > 0) { strcatW(&temp[toWrite], spaceW); toWrite++; if (toWrite > 99) { WCMD_output(temp); toWrite = 0; strcpyW(temp, emptyW); } padding--; } WCMD_output(temp); } } else if ((fd+i)->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { dir_count++; if (!bare) { WCMD_output (fmtDir, datestring, timestring); if (shortname) WCMD_output (fmt2, (fd+i)->cAlternateFileName); if (usernames) WCMD_output (fmt3, username); WCMD_output(fmt4,(fd+i)->cFileName); } else { if (!((strcmpW((fd+i)->cFileName, dotW) == 0) || (strcmpW((fd+i)->cFileName, dotdotW) == 0))) { WCMD_output (fmt5, recurse?inputparms->dirName:emptyW, (fd+i)->cFileName); } else { addNewLine = FALSE; } } } else { file_count++; file_size.u.LowPart = (fd+i)->nFileSizeLow; file_size.u.HighPart = (fd+i)->nFileSizeHigh; byte_count.QuadPart += file_size.QuadPart; if (!bare) { WCMD_output (fmtFile, datestring, timestring, WCMD_filesize64(file_size.QuadPart)); if (shortname) WCMD_output (fmt2, (fd+i)->cAlternateFileName); if (usernames) WCMD_output (fmt3, username); WCMD_output(fmt4,(fd+i)->cFileName); } else { WCMD_output (fmt5, recurse?inputparms->dirName:emptyW, (fd+i)->cFileName); } } } if (addNewLine) WCMD_output (newline); cur_width = 0; } if (!bare) { if (file_count == 1) { static const WCHAR fmt[] = {' ',' ',' ',' ',' ',' ',' ','1',' ','f','i','l','e',' ', '%','2','5','s',' ','b','y','t','e','s','\n','\0'}; WCMD_output (fmt, WCMD_filesize64 (byte_count.QuadPart)); } else { static const WCHAR fmt[] = {'%','8','d',' ','f','i','l','e','s',' ','%','2','4','s', ' ','b','y','t','e','s','\n','\0'}; WCMD_output (fmt, file_count, WCMD_filesize64 (byte_count.QuadPart)); } } byte_total = byte_total + byte_count.QuadPart; file_total = file_total + file_count; dir_total = dir_total + dir_count; if (!bare && !recurse) { if (dir_count == 1) { static const WCHAR fmt[] = {'%','8','d',' ','d','i','r','e','c','t','o','r','y', ' ',' ',' ',' ',' ',' ',' ',' ',' ','\0'}; WCMD_output (fmt, 1); } else { static const WCHAR fmt[] = {'%','8','d',' ','d','i','r','e','c','t','o','r','i', 'e','s','\0'}; WCMD_output (fmt, dir_count); } } } HeapFree(GetProcessHeap(),0,fd); /* When recursing, look in all subdirectories for matches */ if (recurse) { DIRECTORY_STACK *dirStack = NULL; DIRECTORY_STACK *lastEntry = NULL; WIN32_FIND_DATAW finddata; /* Build path to search */ strcpyW(string, inputparms->dirName); strcatW(string, starW); WINE_TRACE("Recursive, looking for '%s'\n", wine_dbgstr_w(string)); hff = FindFirstFileW(string, &finddata); if (hff != INVALID_HANDLE_VALUE) { do { if ((finddata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && (strcmpW(finddata.cFileName, dotdotW) != 0) && (strcmpW(finddata.cFileName, dotW) != 0)) { DIRECTORY_STACK *thisDir; int dirsToCopy = concurrentDirs; /* Loop creating list of subdirs for all concurrent entries */ parms = inputparms; while (dirsToCopy > 0) { dirsToCopy--; /* Work out search parameter in sub dir */ strcpyW (string, inputparms->dirName); strcatW (string, finddata.cFileName); strcatW (string, slashW); WINE_TRACE("Recursive, Adding to search list '%s'\n", wine_dbgstr_w(string)); /* Allocate memory, add to list */ thisDir = HeapAlloc(GetProcessHeap(),0,sizeof(DIRECTORY_STACK)); if (dirStack == NULL) dirStack = thisDir; if (lastEntry != NULL) lastEntry->next = thisDir; lastEntry = thisDir; thisDir->next = NULL; thisDir->dirName = HeapAlloc(GetProcessHeap(),0, sizeof(WCHAR) * (strlenW(string)+1)); strcpyW(thisDir->dirName, string); thisDir->fileName = HeapAlloc(GetProcessHeap(),0, sizeof(WCHAR) * (strlenW(parms->fileName)+1)); strcpyW(thisDir->fileName, parms->fileName); parms = parms->next; } } } while (FindNextFileW(hff, &finddata) != 0); FindClose (hff); while (dirStack != NULL) { DIRECTORY_STACK *thisDir = dirStack; dirStack = WCMD_list_directory (thisDir, 1); while (thisDir != dirStack) { DIRECTORY_STACK *tempDir = thisDir->next; HeapFree(GetProcessHeap(),0,thisDir->dirName); HeapFree(GetProcessHeap(),0,thisDir->fileName); HeapFree(GetProcessHeap(),0,thisDir); thisDir = tempDir; } } } } /* Handle case where everything is filtered out */ if ((file_total + dir_total == 0) && (level == 0)) { SetLastError (ERROR_FILE_NOT_FOUND); WCMD_print_error (); errorlevel = 1; } return parms; }
/* * Convert a FILETIME to a tm structure */ static struct tm *Convert_FILETIME_To_tm(FILETIME *File_Time) { SYSTEMTIME System_Time; static struct tm tm = {0}; static const short Day_Of_Year_By_Month[12] = {(short)(0), (short)(31), (short)(31 + 28), (short)(31 + 28 + 31), (short)(31 + 28 + 31 + 30), (short)(31 + 28 + 31 + 30 + 31), (short)(31 + 28 + 31 + 30 + 31 + 30), (short)(31 + 28 + 31 + 30 + 31 + 30 + 31), (short)(31 + 28 + 31 + 30 + 31 + 30 + 31 + 31), (short)(31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30), (short)(31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31), (short)(31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30)}; /* * Turn the FILETIME into a SYSTEMTIME */ FileTimeToSystemTime(File_Time, &System_Time); /* * Use SYSTEMTIME to fill in the tm structure */ tm.tm_sec = System_Time.wSecond; tm.tm_min = System_Time.wMinute; tm.tm_hour = System_Time.wHour; tm.tm_mday = System_Time.wDay; tm.tm_mon = System_Time.wMonth - 1; tm.tm_year = System_Time.wYear - 1900; tm.tm_wday = System_Time.wDayOfWeek; tm.tm_yday = Day_Of_Year_By_Month[tm.tm_mon] + tm.tm_mday - 1; if (tm.tm_mon >= 2) { /* * Check for leap year (every 4 years but not every 100 years but every 400 years) */ if ((System_Time.wYear % 4) == 0) { /* * It Is a 4th year */ if ((System_Time.wYear % 100) == 0) { /* * It is a 100th year */ if ((System_Time.wYear % 400) == 0) { /* * It is a 400th year: It is a leap year */ tm.tm_yday++; } } else { /* * It is not a 100th year: It is a leap year */ tm.tm_yday++; } } } return(&tm); }
ULONG DeviceAtaHealthInfo( _In_ PDEVICE_LIST DeviceList, _In_ ULONG DeviceIndex ) { ULONG status = ERROR_SUCCESS; ATA_PT ataPt = {0}; PATA_PASS_THROUGH_EX passThru = &ataPt.AtaPassThrough; ULONG bytesReturned = 0; PUSHORT logpages = (PUSHORT)ataPt.Buffer; PDEVICE_STATISTICS_LOG_PAGE_HEADER pageHeader = (PDEVICE_STATISTICS_LOG_PAGE_HEADER)ataPt.Buffer; PUCHAR pageSupported = (PUCHAR)ataPt.Buffer; BOOLEAN generalPage = FALSE; BOOLEAN freeFallPage = FALSE; BOOLEAN rotatingMediaPage = FALSE; BOOLEAN generalErrorPage = FALSE; BOOLEAN temperaturePage = FALSE; BOOLEAN transportPage = FALSE; BOOLEAN ssdPage = FALSE; BOOLEAN vendorSpecificPage = FALSE; int i = 0; // // Get Log Directory to see if it supports Device Statistics // BuildReadLogExCommand(passThru, IDE_GP_LOG_DIRECTORY_ADDRESS, 0, 1, 0); bytesReturned = AtaSendPassThrough(DeviceList[DeviceIndex].Handle, passThru, sizeof(ATA_PT), sizeof(ATA_PT), FALSE ); if (bytesReturned < (FIELD_OFFSET(ATA_PT, Buffer) + IDE_GP_LOG_SECTOR_SIZE)) { status = ERROR_INVALID_DATA; goto exit; } _tprintf(_T("\n\tATA - Info from Device Statistics Log:\n\n")); if (logpages[0] != 1) { _tprintf(_T("\t Warning: Log Directory Version is not 0x0001. Reported value: %d\n"), logpages[0]); } /* if (logpages[IDE_GP_SUMMARY_SMART_ERROR] > 0) { _tprintf(_T("\t Log Page: Smart Error Page Count: %d\n"), logpages[IDE_GP_SUMMARY_SMART_ERROR]); } if (logpages[IDE_GP_COMPREHENSIVE_SMART_ERROR] > 0) { _tprintf(_T("\t Log Page: Comprehensive Smart Error Page Count: %d\n"), logpages[IDE_GP_COMPREHENSIVE_SMART_ERROR]); } if (logpages[IDE_GP_EXTENDED_COMPREHENSIVE_SMART_ERROR] > 0) { _tprintf(_T("\t Log Page: Extended Comprehensive Smart Error Page Count: %d\n"), logpages[IDE_GP_EXTENDED_COMPREHENSIVE_SMART_ERROR]); } */ if (logpages[IDE_GP_LOG_DEVICE_STATISTICS_ADDRESS] == 0) { status = ERROR_INVALID_DATA; _tprintf(_T("\t Error: Not support Device Statistics Log.\n")); goto exit; } //_tprintf(_T("\t Log Page: Device Statistics Page Count: %d\n"), logpages[IDE_GP_LOG_DEVICE_STATISTICS_ADDRESS]); // // Get supported Device Statistics log pages // ZeroMemory(&ataPt, sizeof(ATA_PT)); BuildReadLogExCommand(passThru, IDE_GP_LOG_DEVICE_STATISTICS_ADDRESS, 0, 1, 0); bytesReturned = AtaSendPassThrough(DeviceList[DeviceIndex].Handle, passThru, sizeof(ATA_PT), sizeof(ATA_PT), FALSE ); if (bytesReturned < (FIELD_OFFSET(ATA_PT, Buffer) + IDE_GP_LOG_SECTOR_SIZE)) { status = ERROR_INVALID_DATA; _tprintf(_T("\t Error: Couldn't get Device Statistics Log supported pages.\n")); goto exit; } // first byte after header is how many entries in following list. UCHAR pageCount = *(pageSupported + sizeof(DEVICE_STATISTICS_LOG_PAGE_HEADER)); // The value of revision number word shall be 0001h. The first supported page shall be 00h. if ((pageHeader->RevisionNumber != IDE_GP_LOG_VERSION) || (pageHeader->PageNumber != IDE_GP_LOG_SUPPORTED_PAGES) || (pageCount == 0)) { status = ERROR_INVALID_DATA; _tprintf(_T("\t Error: Device Statistics - Supported Page data not valid.\n")); goto exit; } // if the page number is shown in supported list, mark it's supported. for (i = 1; i <= pageCount; i++) { if (*(pageSupported + sizeof(DEVICE_STATISTICS_LOG_PAGE_HEADER) + i) == IDE_GP_LOG_DEVICE_STATISTICS_GENERAL_PAGE) { generalPage = TRUE; } else if (*(pageSupported + sizeof(DEVICE_STATISTICS_LOG_PAGE_HEADER) + i) == IDE_GP_LOG_DEVICE_STATISTICS_FREE_FALL_PAGE) { freeFallPage = TRUE; } else if (*(pageSupported + sizeof(DEVICE_STATISTICS_LOG_PAGE_HEADER) + i) == IDE_GP_LOG_DEVICE_STATISTICS_ROTATING_MEDIA_PAGE) { rotatingMediaPage = TRUE; } else if (*(pageSupported + sizeof(DEVICE_STATISTICS_LOG_PAGE_HEADER) + i) == IDE_GP_LOG_DEVICE_STATISTICS_GENERAL_ERROR_PAGE) { generalErrorPage = TRUE; } else if (*(pageSupported + sizeof(DEVICE_STATISTICS_LOG_PAGE_HEADER) + i) == IDE_GP_LOG_DEVICE_STATISTICS_TEMPERATURE_PAGE) { temperaturePage = TRUE; } else if (*(pageSupported + sizeof(DEVICE_STATISTICS_LOG_PAGE_HEADER) + i) == IDE_GP_LOG_DEVICE_STATISTICS_TRANSPORT_PAGE) { transportPage = TRUE; } else if (*(pageSupported + sizeof(DEVICE_STATISTICS_LOG_PAGE_HEADER) + i) == IDE_GP_LOG_DEVICE_STATISTICS_SSD_PAGE) { ssdPage = TRUE; } else if (*(pageSupported + sizeof(DEVICE_STATISTICS_LOG_PAGE_HEADER) + i) == 0xFF) { vendorSpecificPage = TRUE; } } if (temperaturePage) { ZeroMemory(&ataPt, sizeof(ATA_PT)); BuildReadLogExCommand(passThru, IDE_GP_LOG_DEVICE_STATISTICS_ADDRESS, IDE_GP_LOG_DEVICE_STATISTICS_TEMPERATURE_PAGE, 1, 0); bytesReturned = AtaSendPassThrough(DeviceList[DeviceIndex].Handle, passThru, sizeof(ATA_PT), sizeof(ATA_PT), FALSE ); PGP_LOG_TEMPERATURE_STATISTICS temperaturelLog = (PGP_LOG_TEMPERATURE_STATISTICS)ataPt.Buffer; if (bytesReturned < (FIELD_OFFSET(ATA_PT, Buffer) + IDE_GP_LOG_SECTOR_SIZE)) { status = ERROR_INVALID_DATA; _tprintf(_T("\t Error: Couldn't get Device Statistics Log Temperature Page.\n")); } else if (//(generalLog->Header.RevisionNumber != IDE_GP_LOG_VERSION) || (temperaturelLog->Header.PageNumber != IDE_GP_LOG_DEVICE_STATISTICS_TEMPERATURE_PAGE)) { status = ERROR_INVALID_DATA; //_tprintf(_T("\t Error: Couldn't get Device Statistics Log Temperature Page.\n")); } else { if ((temperaturelLog->CurrentTemperature.Supported == 1) && (temperaturelLog->CurrentTemperature.ValidValue == 1)) { _tprintf(_T("\t Current Temperature: %I64d\n"), temperaturelLog->CurrentTemperature.Value); } if ((temperaturelLog->HighestTemperature.Supported == 1) && (temperaturelLog->HighestTemperature.ValidValue == 1)) { _tprintf(_T("\t Highest Temperature: %I64d\n"), temperaturelLog->HighestTemperature.Value); } if ((temperaturelLog->LowestTemperature.Supported == 1) && (temperaturelLog->LowestTemperature.ValidValue == 1)) { _tprintf(_T("\t Lowest Temperature: %I64d\n"), temperaturelLog->LowestTemperature.Value); } if ((temperaturelLog->AverageShortTermTemperature.Supported == 1) && (temperaturelLog->AverageShortTermTemperature.ValidValue == 1)) { _tprintf(_T("\t Average Short Term Temperature: %I64d\n"), temperaturelLog->AverageShortTermTemperature.Value); } if ((temperaturelLog->AverageLongTermTemperature.Supported == 1) && (temperaturelLog->AverageLongTermTemperature.ValidValue == 1)) { _tprintf(_T("\t Average Long Term Temperature: %I64d\n"), temperaturelLog->AverageLongTermTemperature.Value); } if ((temperaturelLog->HighestAverageShortTermTemperature.Supported == 1) && (temperaturelLog->HighestAverageShortTermTemperature.ValidValue == 1)) { _tprintf(_T("\t Highest Average Short TermTemperature: %I64d\n"), temperaturelLog->HighestAverageShortTermTemperature.Value); } if ((temperaturelLog->LowestAverageShortTermTemperature.Supported == 1) && (temperaturelLog->LowestAverageShortTermTemperature.ValidValue == 1)) { _tprintf(_T("\t Lowest Average Short Term Temperature: %I64d\n"), temperaturelLog->LowestAverageShortTermTemperature.Value); } if ((temperaturelLog->HighstAverageLongTermTemperature.Supported == 1) && (temperaturelLog->HighstAverageLongTermTemperature.ValidValue == 1)) { _tprintf(_T("\t Highst Average Long Term Temperature: %I64d\n"), temperaturelLog->HighstAverageLongTermTemperature.Value); } if ((temperaturelLog->LowestAverageLongTermTemperature.Supported == 1) && (temperaturelLog->LowestAverageLongTermTemperature.ValidValue == 1)) { _tprintf(_T("\t Lowest Average Long Term Temperature: %I64d\n"), temperaturelLog->LowestAverageLongTermTemperature.Value); } if ((temperaturelLog->TimeInOverTemperature.Supported == 1) && (temperaturelLog->TimeInOverTemperature.ValidValue == 1)) { _tprintf(_T("\t Time In Over Temperature (Minutes): %I64d\n"), temperaturelLog->TimeInOverTemperature.Value); } if ((temperaturelLog->SpecifiedMaximumOperatingTemperature.Supported == 1) && (temperaturelLog->SpecifiedMaximumOperatingTemperature.ValidValue == 1)) { _tprintf(_T("\t Specified Maximum Operating Temperature: %I64d\n"), temperaturelLog->SpecifiedMaximumOperatingTemperature.Value); } if ((temperaturelLog->TimeInUnderTemperature.Supported == 1) && (temperaturelLog->TimeInUnderTemperature.ValidValue == 1)) { _tprintf(_T("\t Time In Under Temperature (Minutes): %I64d\n"), temperaturelLog->TimeInUnderTemperature.Value); } if ((temperaturelLog->SpecifiedMinimumOperatingTemperature.Supported == 1) && (temperaturelLog->SpecifiedMinimumOperatingTemperature.ValidValue == 1)) { _tprintf(_T("\t Specified Minimum Operating Temperature: %I64d\n"), temperaturelLog->SpecifiedMinimumOperatingTemperature.Value); } _tprintf(_T(" \n")); } } if (generalPage) { ZeroMemory(&ataPt, sizeof(ATA_PT)); BuildReadLogExCommand(passThru, IDE_GP_LOG_DEVICE_STATISTICS_ADDRESS, IDE_GP_LOG_DEVICE_STATISTICS_GENERAL_PAGE, 1, 0); bytesReturned = AtaSendPassThrough(DeviceList[DeviceIndex].Handle, passThru, sizeof(ATA_PT), sizeof(ATA_PT), FALSE ); PGP_LOG_GENERAL_STATISTICS generalLog = (PGP_LOG_GENERAL_STATISTICS)ataPt.Buffer; if (bytesReturned < (FIELD_OFFSET(ATA_PT, Buffer) + IDE_GP_LOG_SECTOR_SIZE)) { status = ERROR_INVALID_DATA; _tprintf(_T("\t Error: Couldn't get Device Statistics Log general page.\n")); } else if (//(generalLog->Header.RevisionNumber != IDE_GP_LOG_VERSION) || (generalLog->Header.PageNumber != IDE_GP_LOG_DEVICE_STATISTICS_GENERAL_PAGE)) { status = ERROR_INVALID_DATA; //_tprintf(_T("\t Error: Couldn't get Device Statistics Log general page.\n")); } else { if ((generalLog->LifeTimePoweronResets.Supported == 1) && (generalLog->LifeTimePoweronResets.ValidValue == 1)) { _tprintf(_T("\t Power-on Reset Count: %I64d\n"), generalLog->LifeTimePoweronResets.Count); } if ((generalLog->PoweronHours.Supported == 1) && (generalLog->PoweronHours.ValidValue == 1)) { _tprintf(_T("\t Power-on Hours: %I64d\n"), generalLog->PoweronHours.Count); } if ((generalLog->LogicalSectorsWritten.Supported == 1) && (generalLog->LogicalSectorsWritten.ValidValue == 1)) { _tprintf(_T("\t Logical Sectors Written: %I64d\n"), generalLog->LogicalSectorsWritten.Count); } if ((generalLog->WriteCommandCount.Supported == 1) && (generalLog->WriteCommandCount.ValidValue == 1)) { _tprintf(_T("\t Write Command Count: %I64d\n"), generalLog->WriteCommandCount.Count); } if ((generalLog->LogicalSectorsRead.Supported == 1) && (generalLog->LogicalSectorsRead.ValidValue == 1)) { _tprintf(_T("\t Logical Sectors Read: %I64d\n"), generalLog->LogicalSectorsRead.Count); } if ((generalLog->ReadCommandCount.Supported == 1) && (generalLog->ReadCommandCount.ValidValue == 1)) { _tprintf(_T("\t Read Command Count: %I64d\n"), generalLog->ReadCommandCount.Count); } if ((generalLog->DateAndTime.Supported == 1) && (generalLog->DateAndTime.ValidValue == 1)) { // convert the value to system time SYSTEMTIME systemTime = {0}; TCHAR localDate[255] = {0}; TCHAR localTime[255] = {0}; ULONGLONG time = generalLog->DateAndTime.TimeStamp + 0xA9741731300; time *= 10000; FileTimeToLocalFileTime((LPFILETIME)&time, (LPFILETIME)&time); FileTimeToSystemTime((LPFILETIME)&time, &systemTime); GetDateFormat(LOCALE_USER_DEFAULT, DATE_LONGDATE, &systemTime, NULL, localDate, 255); GetTimeFormat(LOCALE_USER_DEFAULT, 0, &systemTime, NULL, localTime, 255); _tprintf(_T("\t Time Stamp: %s %s\n"), localDate, localTime); } if ((generalLog->PendingErrorCount.Supported == 1) && (generalLog->PendingErrorCount.ValidValue == 1)) { _tprintf(_T("\t Pending Error Sectors Count: %I64d\n"), generalLog->PendingErrorCount.Count); } if ((generalLog->WorkloadUtilizaton.Supported == 1) && (generalLog->WorkloadUtilizaton.ValidValue == 1)) { _tprintf(_T("\t Workload Utilization Percentage: %I64d\n"), generalLog->WorkloadUtilizaton.Value); } if ((generalLog->UtilizationUsageRate.Supported == 1) && (generalLog->UtilizationUsageRate.ValidValue == 1)) { if (generalLog->UtilizationUsageRate.RateValidity == 0x00) { //valid _tprintf(_T("\t Utilization Usage Rate Percentagge: %I64d"), generalLog->UtilizationUsageRate.Value); if (generalLog->UtilizationUsageRate.RateBasis == 0x0) { _tprintf(_T(" (Based on the time of manufacture until the time indicated by the Date and Time TimeStamp device statistic, including times during which the device was powered off.) \n")); } else if (generalLog->UtilizationUsageRate.RateBasis == 0x4) { _tprintf(_T(" (Based on the time elapsed since the most recent processing of a power-on reset.) \n")); } else if (generalLog->UtilizationUsageRate.RateBasis == 0x8) { _tprintf(_T(" (Based on the Power-on Hours device statistic.) \n")); } else if (generalLog->UtilizationUsageRate.RateBasis == 0xF) { _tprintf(_T(" (Basis is undetermined.) \n")); } else { _tprintf(_T(" (Basis is not a valid value.) \n")); } } else if (generalLog->UtilizationUsageRate.RateValidity == 0x10) { _tprintf(_T("\t UTILIZATION USAGE RATE field is not valid because insufficient information has been collected about the workload utilization.\n")); } else if (generalLog->UtilizationUsageRate.RateValidity == 0x81) { _tprintf(_T("\t UTILIZATION USAGE RATE field is not valid because the most recently processed SET DATE & TIME command specified a timestamp resulted in usage rate that is unreasonable.\n")); } else if (generalLog->UtilizationUsageRate.RateValidity == 0xFF) { _tprintf(_T("\t UTILIZATION USAGE RATE field is not valid for an undetermined reason.\n")); } else { _tprintf(_T("\t UTILIZATION USAGE RATE field is not valid because Rate Validity field has invalid value.\n")); } } _tprintf(_T(" \n")); } } if (ssdPage) { ZeroMemory(&ataPt, sizeof(ATA_PT)); BuildReadLogExCommand(passThru, IDE_GP_LOG_DEVICE_STATISTICS_ADDRESS, IDE_GP_LOG_DEVICE_STATISTICS_SSD_PAGE, 1, 0); bytesReturned = AtaSendPassThrough(DeviceList[DeviceIndex].Handle, passThru, sizeof(ATA_PT), sizeof(ATA_PT), FALSE ); PGP_LOG_SOLID_STATE_DEVICE_STATISTICS ssdLog = (PGP_LOG_SOLID_STATE_DEVICE_STATISTICS)ataPt.Buffer; if (bytesReturned < (FIELD_OFFSET(ATA_PT, Buffer) + IDE_GP_LOG_SECTOR_SIZE)) { status = ERROR_INVALID_DATA; _tprintf(_T("\t Error: Couldn't get Device Statistics Log SSD Page.\n")); } else if (//(generalLog->Header.RevisionNumber != IDE_GP_LOG_VERSION) || (ssdLog->Header.PageNumber != IDE_GP_LOG_DEVICE_STATISTICS_SSD_PAGE)) { status = ERROR_INVALID_DATA; //_tprintf(_T("\t Error: Couldn't get Device Statistics Log SSD Page.\n")); } else { if ((ssdLog->PercentageUsedEnduranceIndicator.Supported == 1) && (ssdLog->PercentageUsedEnduranceIndicator.ValidValue == 1)) { _tprintf(_T("\t Percentage Used Endurance Indicator: %I64d\n"), ssdLog->PercentageUsedEnduranceIndicator.Value); } _tprintf(_T(" \n")); } } if (generalErrorPage) { ZeroMemory(&ataPt, sizeof(ATA_PT)); BuildReadLogExCommand(passThru, IDE_GP_LOG_DEVICE_STATISTICS_ADDRESS, IDE_GP_LOG_DEVICE_STATISTICS_GENERAL_ERROR_PAGE, 1, 0); bytesReturned = AtaSendPassThrough(DeviceList[DeviceIndex].Handle, passThru, sizeof(ATA_PT), sizeof(ATA_PT), FALSE ); PGP_LOG_GENERAL_ERROR_STATISTICS generalErrorlLog = (PGP_LOG_GENERAL_ERROR_STATISTICS)ataPt.Buffer; if (bytesReturned < (FIELD_OFFSET(ATA_PT, Buffer) + IDE_GP_LOG_SECTOR_SIZE)) { status = ERROR_INVALID_DATA; _tprintf(_T("\t Error: Couldn't get Device Statistics Log General Error Page.\n")); } else if (//(generalLog->Header.RevisionNumber != IDE_GP_LOG_VERSION) || (generalErrorlLog->Header.PageNumber != IDE_GP_LOG_DEVICE_STATISTICS_GENERAL_ERROR_PAGE)) { status = ERROR_INVALID_DATA; //_tprintf(_T("\t Error: Couldn't get Device Statistics Log General Error Page.\n")); } else { if ((generalErrorlLog->NumberOfReportedUncorrectableErrors.Supported == 1) && (generalErrorlLog->NumberOfReportedUncorrectableErrors.ValidValue == 1)) { _tprintf(_T("\t Number Of Reported Uncorrectable Errors: %I64d\n"), generalErrorlLog->NumberOfReportedUncorrectableErrors.Count); } if ((generalErrorlLog->NumberOfResetsBetweenCommandAcceptanceAndCommandCompletion.Supported == 1) && (generalErrorlLog->NumberOfResetsBetweenCommandAcceptanceAndCommandCompletion.ValidValue == 1)) { _tprintf(_T("\t Number Of Resets Between Command Acceptance And Command Completion: %I64d\n"), generalErrorlLog->NumberOfResetsBetweenCommandAcceptanceAndCommandCompletion.Count); } _tprintf(_T(" \n")); } } if (freeFallPage) { ZeroMemory(&ataPt, sizeof(ATA_PT)); BuildReadLogExCommand(passThru, IDE_GP_LOG_DEVICE_STATISTICS_ADDRESS, IDE_GP_LOG_DEVICE_STATISTICS_FREE_FALL_PAGE, 1, 0); bytesReturned = AtaSendPassThrough(DeviceList[DeviceIndex].Handle, passThru, sizeof(ATA_PT), sizeof(ATA_PT), FALSE ); PGP_LOG_FREE_FALL_STATISTICS freeFallLog = (PGP_LOG_FREE_FALL_STATISTICS)ataPt.Buffer; if (bytesReturned < (FIELD_OFFSET(ATA_PT, Buffer) + IDE_GP_LOG_SECTOR_SIZE)) { status = ERROR_INVALID_DATA; _tprintf(_T("\t Error: Couldn't get Device Statistics Log Free Fall Page.\n")); } else if (//(generalLog->Header.RevisionNumber != IDE_GP_LOG_VERSION) || (freeFallLog->Header.PageNumber != IDE_GP_LOG_DEVICE_STATISTICS_FREE_FALL_PAGE)) { status = ERROR_INVALID_DATA; //_tprintf(_T("\t Error: Couldn't get Device Statistics Log Free Fall Page.\n")); } else { if ((freeFallLog->NumberofFreeFallEventsDetected.Supported == 1) && (freeFallLog->NumberofFreeFallEventsDetected.ValidValue == 1)) { _tprintf(_T("\t Number of Free Fall Events Detected: %I64d\n"), freeFallLog->NumberofFreeFallEventsDetected.Count); } if ((freeFallLog->OverlimitShockEvents.Supported == 1) && (freeFallLog->OverlimitShockEvents.ValidValue == 1)) { _tprintf(_T("\t Over limit Shock Events: %I64d\n"), freeFallLog->OverlimitShockEvents.Count); } _tprintf(_T(" \n")); } } if (rotatingMediaPage) { ZeroMemory(&ataPt, sizeof(ATA_PT)); BuildReadLogExCommand(passThru, IDE_GP_LOG_DEVICE_STATISTICS_ADDRESS, IDE_GP_LOG_DEVICE_STATISTICS_ROTATING_MEDIA_PAGE, 1, 0); bytesReturned = AtaSendPassThrough(DeviceList[DeviceIndex].Handle, passThru, sizeof(ATA_PT), sizeof(ATA_PT), FALSE ); PGP_LOG_ROTATING_MEDIA_STATISTICS rotatingMediaLog = (PGP_LOG_ROTATING_MEDIA_STATISTICS)ataPt.Buffer; if (bytesReturned < (FIELD_OFFSET(ATA_PT, Buffer) + IDE_GP_LOG_SECTOR_SIZE)) { status = ERROR_INVALID_DATA; _tprintf(_T("\t Error: Couldn't get Device Statistics Log Rotating Media Page.\n")); } else if (//(generalLog->Header.RevisionNumber != IDE_GP_LOG_VERSION) || (rotatingMediaLog->Header.PageNumber != IDE_GP_LOG_DEVICE_STATISTICS_ROTATING_MEDIA_PAGE)) { status = ERROR_INVALID_DATA; //_tprintf(_T("\t Error: Couldn't get Device Statistics Log Rotating Media Page.\n")); } else { if ((rotatingMediaLog->SpindleMotorPoweronHours.Supported == 1) && (rotatingMediaLog->SpindleMotorPoweronHours.ValidValue == 1)) { _tprintf(_T("\t Spindle Motor Power-on Hours: %I64d\n"), rotatingMediaLog->SpindleMotorPoweronHours.Count); } if ((rotatingMediaLog->HeadFlyingHours.Supported == 1) && (rotatingMediaLog->HeadFlyingHours.ValidValue == 1)) { _tprintf(_T("\t Head Flying Hours: %I64d\n"), rotatingMediaLog->HeadFlyingHours.Count); } if ((rotatingMediaLog->HeadLoadEvents.Supported == 1) && (rotatingMediaLog->HeadLoadEvents.ValidValue == 1)) { _tprintf(_T("\t Head Load Events: %I64d\n"), rotatingMediaLog->HeadLoadEvents.Count); } if ((rotatingMediaLog->NumberOfReallocatedLogicalSectors.Supported == 1) && (rotatingMediaLog->NumberOfReallocatedLogicalSectors.ValidValue == 1)) { _tprintf(_T("\t Number Of Reallocated Logical Sectors: %I64d\n"), rotatingMediaLog->NumberOfReallocatedLogicalSectors.Count); } if ((rotatingMediaLog->ReadRecoveryAttempts.Supported == 1) && (rotatingMediaLog->ReadRecoveryAttempts.ValidValue == 1)) { _tprintf(_T("\t Read Recovery Attempts: %I64d\n"), rotatingMediaLog->ReadRecoveryAttempts.Count); } if ((rotatingMediaLog->NumberOfMechanicalStartFailures.Supported == 1) && (rotatingMediaLog->NumberOfMechanicalStartFailures.ValidValue == 1)) { _tprintf(_T("\t Number Of Mechanical Start Failures: %I64d\n"), rotatingMediaLog->NumberOfMechanicalStartFailures.Count); } if ((rotatingMediaLog->NumberOfReallocationCandidateLogicalSectors.Supported == 1) && (rotatingMediaLog->NumberOfReallocationCandidateLogicalSectors.ValidValue == 1)) { _tprintf(_T("\t Number Of Reallocation Candidate Logical Sectors: %I64d\n"), rotatingMediaLog->NumberOfReallocationCandidateLogicalSectors.Count); } if ((rotatingMediaLog->NumberOfHighPriorityUnloadEvents.Supported == 1) && (rotatingMediaLog->NumberOfHighPriorityUnloadEvents.ValidValue == 1)) { _tprintf(_T("\t Number Of High Priority Unload Events: %I64d\n"), rotatingMediaLog->NumberOfHighPriorityUnloadEvents.Count); } _tprintf(_T(" \n")); } } if (transportPage) { ZeroMemory(&ataPt, sizeof(ATA_PT)); BuildReadLogExCommand(passThru, IDE_GP_LOG_DEVICE_STATISTICS_ADDRESS, IDE_GP_LOG_DEVICE_STATISTICS_TRANSPORT_PAGE, 1, 0); bytesReturned = AtaSendPassThrough(DeviceList[DeviceIndex].Handle, passThru, sizeof(ATA_PT), sizeof(ATA_PT), FALSE ); PGP_LOG_TRANSPORT_STATISTICS transportLog = (PGP_LOG_TRANSPORT_STATISTICS)ataPt.Buffer; if (bytesReturned < (FIELD_OFFSET(ATA_PT, Buffer) + IDE_GP_LOG_SECTOR_SIZE)) { status = ERROR_INVALID_DATA; _tprintf(_T("\t Error: Couldn't get Device Statistics Log Transport Page.\n")); } else if (//(generalLog->Header.RevisionNumber != IDE_GP_LOG_VERSION) || (transportLog->Header.PageNumber != IDE_GP_LOG_DEVICE_STATISTICS_TRANSPORT_PAGE)) { status = ERROR_INVALID_DATA; //_tprintf(_T("\t Error: Couldn't get Device Statistics Log Transport Page.\n")); } else { if ((transportLog->NumberOfHardwareResets.Supported == 1) && (transportLog->NumberOfHardwareResets.ValidValue == 1)) { _tprintf(_T("\t Number Of Hardware Resets: %I64d\n"), transportLog->NumberOfHardwareResets.Count); } if ((transportLog->NumberOfAsrEvents.Supported == 1) && (transportLog->NumberOfAsrEvents.ValidValue == 1)) { _tprintf(_T("\t Number Of Asr Events: %I64d\n"), transportLog->NumberOfAsrEvents.Count); } if ((transportLog->NumberOfInterfaceCrcErrors.Supported == 1) && (transportLog->NumberOfInterfaceCrcErrors.ValidValue == 1)) { _tprintf(_T("\t Number Of Interface Crc Errors: %I64d\n"), transportLog->NumberOfInterfaceCrcErrors.Count); } _tprintf(_T(" \n")); } } _tprintf(_T("\n")); exit: return status; }
static int XCOPY_ParseCommandLine(WCHAR *suppliedsource, WCHAR *supplieddestination, DWORD *pflags) { const WCHAR EXCLUDE[] = {'E', 'X', 'C', 'L', 'U', 'D', 'E', ':', 0}; DWORD flags = *pflags; WCHAR *cmdline, *word, *end, *next; int rc = RC_INITERROR; cmdline = _wcsdup(GetCommandLineW()); if (cmdline == NULL) return rc; /* Skip first arg, which is the program name */ if ((rc = find_end_of_word(cmdline, &word)) != RC_OK) goto out; word = skip_whitespace(word); while (*word) { WCHAR first; if ((rc = find_end_of_word(word, &end)) != RC_OK) goto out; next = skip_whitespace(end); first = word[0]; *end = '\0'; strip_quotes(word, &end); WINE_TRACE("Processing Arg: '%s'\n", wine_dbgstr_w(word)); /* First non-switch parameter is source, second is destination */ if (first != '/') { if (suppliedsource[0] == 0x00) { lstrcpyW(suppliedsource, word); } else if (supplieddestination[0] == 0x00) { lstrcpyW(supplieddestination, word); } else { XCOPY_wprintf(XCOPY_LoadMessage(STRING_INVPARMS)); goto out; } } else { /* Process all the switch options Note: Windows docs say /P prompts when dest is created but tests show it is done for each src file regardless of the destination */ switch (toupper(word[1])) { case 'I': flags |= OPT_ASSUMEDIR; break; case 'S': flags |= OPT_RECURSIVE; break; case 'Q': flags |= OPT_QUIET; break; case 'F': flags |= OPT_FULL; break; case 'L': flags |= OPT_SIMULATE; break; case 'W': flags |= OPT_PAUSE; break; case 'T': flags |= OPT_NOCOPY | OPT_RECURSIVE; break; case 'Y': flags |= OPT_NOPROMPT; break; case 'N': flags |= OPT_SHORTNAME; break; case 'U': flags |= OPT_MUSTEXIST; break; case 'R': flags |= OPT_REPLACEREAD; break; case 'H': flags |= OPT_COPYHIDSYS; break; case 'C': flags |= OPT_IGNOREERRORS; break; case 'P': flags |= OPT_SRCPROMPT; break; case 'A': flags |= OPT_ARCHIVEONLY; break; case 'M': flags |= OPT_ARCHIVEONLY | OPT_REMOVEARCH; break; /* E can be /E or /EXCLUDE */ case 'E': if (CompareStringW(LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT, &word[1], 8, EXCLUDE, -1) == CSTR_EQUAL) { if (XCOPY_ProcessExcludeList(&word[9])) { XCOPY_FailMessage(ERROR_INVALID_PARAMETER); goto out; } else flags |= OPT_EXCLUDELIST; } else flags |= OPT_EMPTYDIR | OPT_RECURSIVE; break; /* D can be /D or /D: */ case 'D': if (word[2]==':' && isdigit(word[3])) { SYSTEMTIME st; WCHAR *pos = &word[3]; BOOL isError = FALSE; memset(&st, 0x00, sizeof(st)); /* Microsoft xcopy's usage message implies that the date * format depends on the locale, but that is false. * It is hardcoded to month-day-year. */ st.wMonth = _wtol(pos); while (*pos && isdigit(*pos)) pos++; if (*pos++ != '-') isError = TRUE; if (!isError) { st.wDay = _wtol(pos); while (*pos && isdigit(*pos)) pos++; if (*pos++ != '-') isError = TRUE; } if (!isError) { st.wYear = _wtol(pos); while (*pos && isdigit(*pos)) pos++; if (st.wYear < 100) st.wYear+=2000; } if (!isError && SystemTimeToFileTime(&st, &dateRange)) { SYSTEMTIME st; WCHAR datestring[32], timestring[32]; flags |= OPT_DATERANGE; /* Debug info: */ FileTimeToSystemTime (&dateRange, &st); GetDateFormatW(0, DATE_SHORTDATE, &st, NULL, datestring, sizeof(datestring)/sizeof(WCHAR)); GetTimeFormatW(0, TIME_NOSECONDS, &st, NULL, timestring, sizeof(timestring)/sizeof(WCHAR)); WINE_TRACE("Date being used is: %s %s\n", wine_dbgstr_w(datestring), wine_dbgstr_w(timestring)); } else { XCOPY_FailMessage(ERROR_INVALID_PARAMETER); goto out; } } else { flags |= OPT_DATENEWER; } break; case '-': if (toupper(word[2])=='Y') flags &= ~OPT_NOPROMPT; break; case '?': XCOPY_wprintf(XCOPY_LoadMessage(STRING_HELP)); rc = RC_HELP; goto out; default: WINE_TRACE("Unhandled parameter '%s'\n", wine_dbgstr_w(word)); XCOPY_wprintf(XCOPY_LoadMessage(STRING_INVPARM), word); goto out; } } word = next; } /* Default the destination if not supplied */ if (supplieddestination[0] == 0x00) lstrcpyW(supplieddestination, wchr_dot); *pflags = flags; rc = RC_OK; out: free(cmdline); return rc; }
void CPoomAddressbook::HandleMultiValuedProperties(unsigned int cAggregatedProps,void *rgAggregatedPropVals, CONTACTACC* contact) { SOURCEDPROPVAL* ptrS; CEPROPVAL* ptrPS; for (unsigned int i = 0; i < cAggregatedProps; i++) { ptrS=(SOURCEDPROPVAL*)rgAggregatedPropVals+i; SOURCE *ptrSOURCE; list<SOURCE> item; for (UINT j = 0; j < ptrS->cSources; j++) { ptrSOURCE=(SOURCE*)ptrS->rgSources+j; item.insert(item.begin(),*ptrSOURCE); } ptrPS=((CEPROPVAL*)ptrS->pPropVal); switch (((PIMPR_PROPS) ptrPS->propid)) { case _PIMPR_JOB_TITLE: contact->CONTACT_PIMPR_JOB_TITLE=ptrPS->val.lpwstr; break; case _PIMPR_OFFICE_LOCATION: contact->CONTACT_PIMPR_OFFICE_LOCATION=ptrPS->val.lpwstr; break; case _PIMPR_YOMI_COMPANY: contact->CONTACT_PIMPR_YOMI_COMPANY=ptrPS->val.lpwstr; break; case _PIMPR_COMPANY_NAME: contact->CONTACT_PIMPR_COMPANY_NAME=ptrPS->val.lpwstr; break; case _PIMPR_EMAIL1_ADDRESS: contact->CONTACT_PIMPR_EMAIL1_ADDRESS=ptrPS->val.lpwstr; break; case _PIMPR_EMAIL2_ADDRESS: contact->CONTACT_PIMPR_EMAIL2_ADDRESS=ptrPS->val.lpwstr; break; case _PIMPR_EMAIL3_ADDRESS: contact->CONTACT_PIMPR_EMAIL3_ADDRESS=ptrPS->val.lpwstr; break; case _PIMPR_MOBILE_TELEPHONE_NUMBER: contact->CONTACT_PIMPR_MOBILE_TELEPHONE_NUMBER=ptrPS->val.lpwstr; break; case _PIMPR_MOBILE2_TELEPHONE_NUMBER: contact->CONTACT_PIMPR_MOBILE2_TELEPHONE_NUMBER=ptrPS->val.lpwstr; break; case _PIMPR_BUSINESS_TELEPHONE_NUMBER: contact->CONTACT_PIMPR_BUSINESS_TELEPHONE_NUMBER=ptrPS->val.lpwstr; break; case _PIMPR_BUSINESS2_TELEPHONE_NUMBER: contact->CONTACT_PIMPR_BUSINESS2_TELEPHONE_NUMBER=ptrPS->val.lpwstr; break; case _PIMPR_HOME2_TELEPHONE_NUMBER: contact->CONTACT_PIMPR_HOME2_TELEPHONE_NUMBER=ptrPS->val.lpwstr; break; case _PIMPR_HOME_TELEPHONE_NUMBER: contact->CONTACT_PIMPR_HOME_TELEPHONE_NUMBER=ptrPS->val.lpwstr; break; case _PIMPR_BUSINESS_FAX_NUMBER: contact->CONTACT_PIMPR_BUSINESS_FAX_NUMBER=ptrPS->val.lpwstr; break; case _PIMPR_HOME_FAX_NUMBER: contact->CONTACT_PIMPR_HOME_FAX_NUMBER=ptrPS->val.lpwstr; break; case _PIMPR_PAGER_NUMBER: contact->CONTACT_PIMPR_PAGER_NUMBER=ptrPS->val.lpwstr; break; case _PIMPR_COMPANY_TELEPHONE_NUMBER: contact->CONTACT_PIMPR_COMPANY_TELEPHONE_NUMBER=ptrPS->val.lpwstr; break; case _PIMPR_SPOUSE: contact->CONTACT_PIMPR_SPOUSE=ptrPS->val.lpwstr; break; case _PIMPR_BUSINESS_ADDRESS_STREET: contact->CONTACT_PIMPR_BUSINESS_ADDRESS_STREET=ptrPS->val.lpwstr; break; case _PIMPR_BUSINESS_ADDRESS_CITY: contact->CONTACT_PIMPR_BUSINESS_ADDRESS_CITY=ptrPS->val.lpwstr; break; case _PIMPR_CHILDREN: contact->CONTACT_PIMPR_CHILDREN=ptrPS->val.lpwstr; break; case _PIMPR_WEB_PAGE: contact->CONTACT_PIMPR_WEB_PAGE=ptrPS->val.lpwstr; break; case _PIMPR_BUSINESS_ADDRESS_STATE: contact->CONTACT_PIMPR_BUSINESS_ADDRESS_STATE=ptrPS->val.lpwstr; break; case _PIMPR_BUSINESS_ADDRESS_POSTAL_CODE: contact->CONTACT_PIMPR_BUSINESS_ADDRESS_POSTAL_CODE=ptrPS->val.lpwstr; break; case _PIMPR_BUSINESS_ADDRESS_COUNTRY: contact->CONTACT_PIMPR_BUSINESS_ADDRESS_COUNTRY=ptrPS->val.lpwstr; break; case _PIMPR_HOME_ADDRESS_STREET: contact->CONTACT_PIMPR_HOME_ADDRESS_STREET=ptrPS->val.lpwstr; break; case _PIMPR_HOME_ADDRESS_CITY: contact->CONTACT_PIMPR_HOME_ADDRESS_CITY=ptrPS->val.lpwstr; break; case _PIMPR_HOME_ADDRESS_COUNTRY: contact->CONTACT_PIMPR_HOME_ADDRESS_COUNTRY=ptrPS->val.lpwstr; break; case _PIMPR_OTHER_ADDRESS_STREET: contact->CONTACT_PIMPR_OTHER_ADDRESS_STREET=ptrPS->val.lpwstr; break; case _PIMPR_OTHER_ADDRESS_CITY: contact->CONTACT_PIMPR_OTHER_ADDRESS_CITY=ptrPS->val.lpwstr; break; case _PIMPR_HOME_ADDRESS_STATE: contact->CONTACT_PIMPR_HOME_ADDRESS_STATE=ptrPS->val.lpwstr; break; case _PIMPR_HOME_ADDRESS_POSTAL_CODE: contact->CONTACT_PIMPR_HOME_ADDRESS_POSTAL_CODE=ptrPS->val.lpwstr; break; case _PIMPR_OTHER_ADDRESS_STATE: contact->CONTACT_PIMPR_OTHER_ADDRESS_STATE=ptrPS->val.lpwstr; break; case _PIMPR_OTHER_ADDRESS_POSTAL_CODE: contact->CONTACT_PIMPR_OTHER_ADDRESS_POSTAL_CODE=ptrPS->val.lpwstr; break; case _PIMPR_OTHER_ADDRESS_COUNTRY: contact->CONTACT_PIMPR_OTHER_ADDRESS_COUNTRY=ptrPS->val.lpwstr; break; case _PIMPR_FLOATING_BIRTHDAY: { FILETIME fileTime = {ptrPS->val.filetime.dwLowDateTime, ptrPS->val.filetime.dwHighDateTime}; SYSTEMTIME lpUniversalTime,lpLocalTime; FileTimeToSystemTime(&fileTime, &lpUniversalTime); _SystemTimeToTzSpecificLocalTime(NULL,&lpUniversalTime ,&lpLocalTime); WCHAR msg[32]; swprintf_s(msg, L"%02i/%02i/%04i",lpLocalTime.wDay,lpLocalTime.wMonth,lpLocalTime.wYear); wcscpy((wchar_t*)contact->CONTACT_PIMPR_FLOATING_BIRTHDAY,msg); break; } case _PIMPR_BODY_TEXT: contact->CONTACT_PIMPR_BODY_TEXT=ptrPS->val.lpwstr; break; } } }
/*********************************************************************** * TIME_CompTimeZoneID * * Computes the local time bias for a given time and time zone. * * PARAMS * pTZinfo [in] The time zone data. * lpFileTime [in] The system or local time. * islocal [in] it is local time. * * RETURNS * TIME_ZONE_ID_INVALID An error occurred * TIME_ZONE_ID_UNKNOWN There are no transition time known * TIME_ZONE_ID_STANDARD Current time is standard time * TIME_ZONE_ID_DAYLIGHT Current time is daylight savings time */ static DWORD TIME_CompTimeZoneID ( const TIME_ZONE_INFORMATION *pTZinfo, FILETIME *lpFileTime, BOOL islocal ) { int ret, year; BOOL beforeStandardDate, afterDaylightDate; DWORD retval = TIME_ZONE_ID_INVALID; LONGLONG llTime = 0; /* initialized to prevent gcc complaining */ SYSTEMTIME SysTime; FILETIME ftTemp; if (pTZinfo->DaylightDate.wMonth != 0) { /* if year is 0 then date is in day-of-week format, otherwise * it's absolute date. */ if (pTZinfo->StandardDate.wMonth == 0 || (pTZinfo->StandardDate.wYear == 0 && (pTZinfo->StandardDate.wDay<1 || pTZinfo->StandardDate.wDay>5 || pTZinfo->DaylightDate.wDay<1 || pTZinfo->DaylightDate.wDay>5))) { SetLastError(ERROR_INVALID_PARAMETER); return TIME_ZONE_ID_INVALID; } if (!islocal) { FILETIME2LL( lpFileTime, llTime ); llTime -= pTZinfo->Bias * (LONGLONG)600000000; LL2FILETIME( llTime, &ftTemp) lpFileTime = &ftTemp; } FileTimeToSystemTime(lpFileTime, &SysTime); year = SysTime.wYear; if (!islocal) { llTime -= pTZinfo->DaylightBias * (LONGLONG)600000000; LL2FILETIME( llTime, &ftTemp) FileTimeToSystemTime(lpFileTime, &SysTime); } /* check for daylight savings */ if(year == SysTime.wYear) { ret = TIME_DayLightCompareDate( &SysTime, &pTZinfo->StandardDate); if (ret == -2) return TIME_ZONE_ID_INVALID; beforeStandardDate = ret < 0; } else beforeStandardDate = SysTime.wYear < year; if (!islocal) { llTime -= ( pTZinfo->StandardBias - pTZinfo->DaylightBias ) * (LONGLONG)600000000; LL2FILETIME( llTime, &ftTemp) FileTimeToSystemTime(lpFileTime, &SysTime); } if(year == SysTime.wYear) { ret = TIME_DayLightCompareDate( &SysTime, &pTZinfo->DaylightDate); if (ret == -2) return TIME_ZONE_ID_INVALID; afterDaylightDate = ret >= 0; } else afterDaylightDate = SysTime.wYear > year; retval = TIME_ZONE_ID_STANDARD; if( pTZinfo->DaylightDate.wMonth < pTZinfo->StandardDate.wMonth ) { /* Northern hemisphere */ if( beforeStandardDate && afterDaylightDate ) retval = TIME_ZONE_ID_DAYLIGHT; } else /* Down south */ if( beforeStandardDate || afterDaylightDate ) retval = TIME_ZONE_ID_DAYLIGHT; } else /* No transition date */ retval = TIME_ZONE_ID_UNKNOWN; return retval; }
APR_DECLARE(apr_status_t) apr_time_exp_lt(apr_time_exp_t *result, apr_time_t input) { SYSTEMTIME st; FILETIME ft, localft; AprTimeToFileTime(&ft, input); #if APR_HAS_UNICODE_FS && !defined(_WIN32_WCE) IF_WIN_OS_IS_UNICODE { TIME_ZONE_INFORMATION *tz; SYSTEMTIME localst; apr_time_t localtime; get_local_timezone(&tz); FileTimeToSystemTime(&ft, &st); /* The Platform SDK documents that SYSTEMTIME/FILETIME are * generally UTC. We use SystemTimeToTzSpecificLocalTime * because FileTimeToLocalFileFime is documented that the * resulting time local file time would have DST relative * to the *present* date, not the date converted. */ SystemTimeToTzSpecificLocalTime(tz, &st, &localst); SystemTimeToAprExpTime(result, &localst); result->tm_usec = (apr_int32_t) (input % APR_USEC_PER_SEC); /* Recover the resulting time as an apr time and use the * delta for gmtoff in seconds (and ignore msec rounding) */ SystemTimeToFileTime(&localst, &localft); FileTimeToAprTime(&localtime, &localft); result->tm_gmtoff = (int)apr_time_sec(localtime) - (int)apr_time_sec(input); /* To compute the dst flag, we compare the expected * local (standard) timezone bias to the delta. * [Note, in war time or double daylight time the * resulting tm_isdst is, desireably, 2 hours] */ result->tm_isdst = (result->tm_gmtoff / 3600) - (-(tz->Bias + tz->StandardBias) / 60); } #endif #if APR_HAS_ANSI_FS || defined(_WIN32_WCE) ELSE_WIN_OS_IS_ANSI { TIME_ZONE_INFORMATION tz; /* XXX: This code is simply *wrong*. The time converted will always * map to the *now current* status of daylight savings time. */ FileTimeToLocalFileTime(&ft, &localft); FileTimeToSystemTime(&localft, &st); SystemTimeToAprExpTime(result, &st); result->tm_usec = (apr_int32_t) (input % APR_USEC_PER_SEC); switch (GetTimeZoneInformation(&tz)) { case TIME_ZONE_ID_UNKNOWN: result->tm_isdst = 0; /* Bias = UTC - local time in minutes * tm_gmtoff is seconds east of UTC */ result->tm_gmtoff = tz.Bias * -60; break; case TIME_ZONE_ID_STANDARD: result->tm_isdst = 0; result->tm_gmtoff = (tz.Bias + tz.StandardBias) * -60; break; case TIME_ZONE_ID_DAYLIGHT: result->tm_isdst = 1; result->tm_gmtoff = (tz.Bias + tz.DaylightBias) * -60; break; default: /* noop */; } } #endif return APR_SUCCESS; }
void RarTime::GetLocal(RarLocalTime *lt) { #ifdef _WIN_ALL FILETIME ft; GetWin32(&ft); FILETIME lft; if (WinNT() < WNT_VISTA) { // SystemTimeToTzSpecificLocalTime based code produces 1 hour error on XP. FileTimeToLocalFileTime(&ft,&lft); } else { // We use these functions instead of FileTimeToLocalFileTime according to // MSDN recommendation: "To account for daylight saving time // when converting a file time to a local time ..." SYSTEMTIME st1,st2; FileTimeToSystemTime(&ft,&st1); SystemTimeToTzSpecificLocalTime(NULL,&st1,&st2); SystemTimeToFileTime(&st2,&lft); // Correct precision loss (low 4 decimal digits) in FileTimeToSystemTime. FILETIME rft; SystemTimeToFileTime(&st1,&rft); int64 Corrected=INT32TO64(ft.dwHighDateTime,ft.dwLowDateTime)- INT32TO64(rft.dwHighDateTime,rft.dwLowDateTime)+ INT32TO64(lft.dwHighDateTime,lft.dwLowDateTime); lft.dwLowDateTime=(DWORD)Corrected; lft.dwHighDateTime=(DWORD)(Corrected>>32); } SYSTEMTIME st; FileTimeToSystemTime(&lft,&st); lt->Year=st.wYear; lt->Month=st.wMonth; lt->Day=st.wDay; lt->Hour=st.wHour; lt->Minute=st.wMinute; lt->Second=st.wSecond; lt->wDay=st.wDayOfWeek; lt->yDay=lt->Day-1; static int mdays[12]={31,28,31,30,31,30,31,31,30,31,30,31}; for (uint I=1;I<lt->Month && I<=ASIZE(mdays);I++) lt->yDay+=mdays[I-1]; if (lt->Month>2 && IsLeapYear(lt->Year)) lt->yDay++; st.wMilliseconds=0; FILETIME zft; SystemTimeToFileTime(&st,&zft); // Calculate the time reminder, which is the part of time smaller // than 1 second, represented in 100-nanosecond intervals. lt->Reminder=INT32TO64(lft.dwHighDateTime,lft.dwLowDateTime)- INT32TO64(zft.dwHighDateTime,zft.dwLowDateTime); #else time_t ut=GetUnix(); struct tm *t; t=localtime(&ut); lt->Year=t->tm_year+1900; lt->Month=t->tm_mon+1; lt->Day=t->tm_mday; lt->Hour=t->tm_hour; lt->Minute=t->tm_min; lt->Second=t->tm_sec; lt->Reminder=itime % 10000000; lt->wDay=t->tm_wday; lt->yDay=t->tm_yday; #endif }
// This method compresses the files contained in the report and produces a ZIP archive. BOOL CErrorReportExporter::CompressReportFiles(CErrorReportInfo* eri) { BOOL bStatus = FALSE; strconv_t strconv; zipFile hZip = NULL; CString sMsg; LONG64 lTotalSize = 0; LONG64 lTotalCompressed = 0; BYTE buff[1024]; DWORD dwBytesRead=0; HANDLE hFile = INVALID_HANDLE_VALUE; std::map<CString, ERIFileItem>::iterator it; FILE* f = NULL; CString sMD5Hash; // Add a different log message depending on the current mode. if(m_bExport) m_Assync.SetProgress(_T("[exporting_report]"), 0, false); else m_Assync.SetProgress(_T("[compressing_files]"), 0, false); // Calculate the total size of error report files lTotalSize = eri->GetTotalSize(); // Add a message to log sMsg.Format(_T("Total file size for compression is %I64d bytes"), lTotalSize); m_Assync.SetProgress(sMsg, 0, false); // Determine what name to use for the output ZIP archive file. if(m_bExport) m_sZipName = m_sExportFileName; else m_sZipName = eri->GetErrorReportDirName() + _T(".zip"); // Update progress sMsg.Format(_T("Creating ZIP archive file %s"), m_sZipName); m_Assync.SetProgress(sMsg, 1, false); // Create ZIP archive hZip = zipOpen((const char*)m_sZipName.GetBuffer(0), APPEND_STATUS_CREATE); if(hZip==NULL) { m_Assync.SetProgress(_T("Failed to create ZIP file."), 100, true); goto cleanup; } // Enumerate files contained in the report int i; for(i=0; i<eri->GetFileItemCount(); i++) { ERIFileItem* pfi = eri->GetFileItemByIndex(i); // Check if the operation was cancelled by user if(m_Assync.IsCancelled()) goto cleanup; // Define destination file name in ZIP archive CString sDstFileName = pfi->m_sDestFile.GetBuffer(0); // Define source file name CString sFileName = pfi->m_sSrcFile.GetBuffer(0); // Define file description CString sDesc = pfi->m_sDesc; // Update progress sMsg.Format(_T("Compressing file %s"), sDstFileName); m_Assync.SetProgress(sMsg, 0, false); // Open file for reading hFile = CreateFile(sFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL); if(hFile==INVALID_HANDLE_VALUE) { sMsg.Format(_T("Couldn't open file %s"), sFileName); m_Assync.SetProgress(sMsg, 0, false); continue; } // Get file information. BY_HANDLE_FILE_INFORMATION fi; GetFileInformationByHandle(hFile, &fi); // Convert file creation time to system file time. SYSTEMTIME st; FileTimeToSystemTime(&fi.ftLastWriteTime, &st); // Fill in the ZIP file info zip_fileinfo info; info.dosDate = 0; info.tmz_date.tm_year = st.wYear; info.tmz_date.tm_mon = st.wMonth-1; info.tmz_date.tm_mday = st.wDay; info.tmz_date.tm_hour = st.wHour; info.tmz_date.tm_min = st.wMinute; info.tmz_date.tm_sec = st.wSecond; info.external_fa = FILE_ATTRIBUTE_NORMAL; info.internal_fa = FILE_ATTRIBUTE_NORMAL; // Create new file inside of our ZIP archive int n = zipOpenNewFileInZip( hZip, (const char*)strconv.t2a(sDstFileName.GetBuffer(0)), &info, NULL, 0, NULL, 0, strconv.t2a(sDesc), Z_DEFLATED, Z_DEFAULT_COMPRESSION); if(n!=0) { sMsg.Format(_T("Couldn't compress file %s"), sDstFileName); m_Assync.SetProgress(sMsg, 0, false); continue; } // Read source file contents and write it to ZIP archive for(;;) { // Check if operation was cancelled by user if(m_Assync.IsCancelled()) goto cleanup; // Read a portion of source file BOOL bRead = ReadFile(hFile, buff, 1024, &dwBytesRead, NULL); if(!bRead || dwBytesRead==0) break; // Write a portion into destination file int res = zipWriteInFileInZip(hZip, buff, dwBytesRead); if(res!=0) { zipCloseFileInZip(hZip); sMsg.Format(_T("Couldn't write to compressed file %s"), sDstFileName); m_Assync.SetProgress(sMsg, 0, false); break; } // Update totals lTotalCompressed += dwBytesRead; // Update progress float fProgress = 100.0f*lTotalCompressed/lTotalSize; m_Assync.SetProgress((int)fProgress, false); } // Close file zipCloseFileInZip(hZip); CloseHandle(hFile); hFile = INVALID_HANDLE_VALUE; } // Close ZIP archive if(hZip!=NULL) { zipClose(hZip, NULL); hZip = NULL; } // Check if totals match if(lTotalSize==lTotalCompressed) bStatus = TRUE; cleanup: // Clean up if(hZip!=NULL) zipClose(hZip, NULL); if(hFile!=INVALID_HANDLE_VALUE) CloseHandle(hFile); if(f!=NULL) fclose(f); if(bStatus) m_Assync.SetProgress(_T("Finished compressing files...OK"), 100, true); else m_Assync.SetProgress(_T("File compression failed."), 100, true); if(m_bExport) { if(bStatus) m_Assync.SetProgress(_T("[end_exporting_report_ok]"), 100, false); else m_Assync.SetProgress(_T("[end_exporting_report_failed]"), 100, false); } else { m_Assync.SetProgress(_T("[end_compressing_files]"), 100, false); } return bStatus; }
void FileTimeToStr (FILETIME *time, LPSTR pszDate, LPSTR pszTime, BOOL bSeconds) { SYSTEMTIME s; FileTimeToSystemTime (time, &s); SystemTimeToStr (&s, pszDate, pszTime, bSeconds); }
LPPL_YYSTYPE SysFnSYSVER_EM_YY (LPTOKEN lptkLftArg, // Ptr to left arg token (should be NULL) LPTOKEN lptkFunc, // Ptr to function token LPTOKEN lptkRhtArg, // Ptr to right arg token (should be NULL) LPTOKEN lptkAxis) // Ptr to axis token (may be NULL) { APLUINT ByteRes; // # bytes in the result APLNELM aplNELMRes; // Result NELM HGLOBAL hGlbRes; // Result global memory handle LPAPLCHAR lpMemRes, // Ptr to result global memory lpMemData; // Ptr to result data LPAPLCHAR lpw; // Temporary ptr HANDLE hFile; // File handle from CreateFileW LPPL_YYSTYPE lpYYRes; // Ptr to the result // This function is niladic Assert (lptkLftArg EQ NULL && lptkRhtArg EQ NULL); //*************************************************************** // This function is not sensitive to the axis operator, // so signal a syntax error if present //*************************************************************** if (lptkAxis NE NULL) goto AXIS_SYNTAX_EXIT; // Define maximum length of []SYSVER #ifdef DEBUG #define DEBUGSTR L" (DEBUG)" #else #define DEBUGSTR #endif #define SYSVER L"000.000.0000.00799 Tue Jan 16 17:43:45 2007 Win/32" DEBUGSTR #define SYSVER_NELM strcountof (SYSVER) // Calculate space needed for the result ByteRes = CalcArraySize (ARRAY_CHAR, SYSVER_NELM, 1); // Check for overflow if (ByteRes NE (APLU3264) ByteRes) goto WSFULL_EXIT; // Allocate space for the result hGlbRes = DbgGlobalAlloc (GHND, (APLU3264) ByteRes); if (hGlbRes EQ NULL) goto WSFULL_EXIT; // Lock the memory to get a ptr to it lpMemRes = MyGlobalLock000 (hGlbRes); #define lpHeader ((LPVARARRAY_HEADER) lpMemRes) // Fill in the header lpHeader->Sig.nature = VARARRAY_HEADER_SIGNATURE; lpHeader->ArrType = ARRAY_CHAR; ////lpHeader->PermNdx = PERMNDX_NONE; // Already zero from GHND ////lpHeader->SysVar = FALSE; // Already zero from GHND lpHeader->RefCnt = 1; ////lpHeader->NELM = SYSVER_NELM; // Filled in below lpHeader->Rank = 1; #undef lpHeader // Fill in the dimension ////*VarArrayBaseToDim (lpMemRes) = SYSVER_NELM; // Filled in below // Skip over the header and dimensions to the data lpw = lpMemData = VarArrayDataFmBase (lpMemRes); // Copy the application's File Version String strcpyW (lpw, wszFileVer); // Skip to the trailing zero lpw += lstrlenW (lpw); *lpw++ = L' '; // Blank separators *lpw++ = L' '; // Open the executable file so we get its last write time hFile = CreateFileW (wszAppDPFE, // lpwFileName GENERIC_READ, // dwDesiredAccess FILE_SHARE_READ, // dwShareMode NULL, // lpSecurityAttributes OPEN_EXISTING, // dwCreationDistribution FILE_ATTRIBUTE_NORMAL, // dwFlagsAndAttributes NULL); // hTemplateFile if (hFile NE INVALID_HANDLE_VALUE) { FILETIME ftLastWrite; SYSTEMTIME systemTime; // Get the file's last write time // Note that the file's creation time need not be the // same as the file's last write time. I think the // linker might sometimes rewrite the .exe file // instead of recreating it. GetFileTime (hFile, NULL, NULL, &ftLastWrite); // We no longer need this handle CloseHandle (hFile); hFile = NULL; // Convert the file's last write time to system time FileTimeToSystemTime (&ftLastWrite, &systemTime); // Format the system time as // "Wed Jan 02 02:03:55 1980" wsprintfW (lpw, L"%s %s %02u %02u:%02u:%02u %u", aDaysOfWeek[systemTime.wDayOfWeek], aMonths[systemTime.wMonth - 1], systemTime.wDay, systemTime.wHour, systemTime.wMinute, systemTime.wSecond, systemTime.wYear); // Skip to the trailing zero lpw += lstrlenW (lpw); *lpw++ = L' '; // Blank separators *lpw++ = L' '; } // End IF #ifdef _WIN64 #define SYSTYPE L"Win/64" DEBUGSTR #elif defined (_WIN32) #define SYSTYPE L"Win/32" DEBUGSTR #else #error Need code for this architecture. #endif // Copy to the result CopyMemoryW (lpw, SYSTYPE, strcountof (SYSTYPE)); // Calculate the actual NELM aplNELMRes = lstrlenW (lpMemData); // Fill in actual length of []SYSVER #define lpHeader ((LPVARARRAY_HEADER) lpMemRes) lpHeader->NELM = aplNELMRes; #undef lpHeader // Fill in the dimension *VarArrayBaseToDim (lpMemRes) = aplNELMRes; // We no longer need this ptr MyGlobalUnlock (hGlbRes); lpMemRes = NULL; // Make sure we didn't overwrite if (aplNELMRes < SYSVER_NELM) { // Calculate space needed for the result ByteRes = CalcArraySize (ARRAY_CHAR, aplNELMRes, 1); ////////// Check for overflow ////////if (ByteRes NE (APLU3264) ByteRes) //////// goto WSFULL_EXIT; // Re-allocate the global downwards hGlbRes = MyGlobalReAlloc (hGlbRes, (APLU3264) ByteRes, GMEM_MOVEABLE); } else if (aplNELMRes > SYSVER_NELM) // We should never get here DbgStop (); // Allocate a new YYRes lpYYRes = YYAlloc (); // Fill in the result token lpYYRes->tkToken.tkFlags.TknType = TKT_VARARRAY; ////lpYYRes->tkToken.tkFlags.ImmType = IMMTYPE_ERROR; y // Already zero from YYAlloc ////lpYYRes->tkToken.tkFlags.NoDisplay = FALSE; // Already zero from YYAlloc lpYYRes->tkToken.tkData.tkGlbData = MakePtrTypeGlb (hGlbRes); lpYYRes->tkToken.tkCharIndex = lptkFunc->tkCharIndex; return lpYYRes; AXIS_SYNTAX_EXIT: ErrorMessageIndirectToken (ERRMSG_SYNTAX_ERROR APPEND_NAME, lptkAxis); return NULL; WSFULL_EXIT: ErrorMessageIndirectToken (ERRMSG_WS_FULL APPEND_NAME, lptkFunc); return NULL; } // End SysFnSYSVER_EM_YY
INT_PTR CALLBACK DlgProcAlarm(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) { switch ( msg ) { case WM_INITDIALOG: TranslateDialogDefault( hwndDlg ); { Utils_RestoreWindowPositionNoSize(hwndDlg, 0, MODULE, "Notify"); SetFocus(GetDlgItem(hwndDlg, IDC_SNOOZE)); WindowData *wd = new WindowData; wd->moving = false; wd->alarm = 0; wd->win_num = win_num++; if (wd->win_num > 0) { RECT r; GetWindowRect(hwndDlg, &r); r.top += 20; r.left += 20; SetWindowPos(hwndDlg, 0, r.left, r.top, 0, 0, SWP_NOZORDER | SWP_NOSIZE | SWP_NOACTIVATE); Utils_SaveWindowPosition(hwndDlg, 0, MODULE, "Notify"); } SetWindowLongPtr(hwndDlg, GWLP_USERDATA, (LONG_PTR)wd); // options SendMessage(hwndDlg, WMU_SETOPT, 0, 0); // fonts SendMessage(hwndDlg, WMU_SETFONTS, 0, 0); } return FALSE; case WMU_REFRESH: InvalidateRect(hwndDlg, 0, TRUE); return TRUE; case WM_CTLCOLORSTATIC: { HDC hdc = (HDC)wParam; HWND hwndCtrl = (HWND)lParam; if (hBackgroundBrush) { if (hTitleFont && GetDlgItem(hwndDlg, IDC_TITLE) == hwndCtrl) SetTextColor(hdc, title_font_colour); else if (hWindowFont) SetTextColor(hdc, window_font_colour); SetBkMode(hdc, TRANSPARENT); return (BOOL)hBackgroundBrush; } } break; case WM_CTLCOLORDLG: if (hBackgroundBrush) return (BOOL)hBackgroundBrush; break; case WMU_SETFONTS: // fonts if (hWindowFont) SendMessage(hwndDlg, WM_SETFONT, (WPARAM)hWindowFont, TRUE); if (hTitleFont) SendDlgItemMessage(hwndDlg, IDC_TITLE, WM_SETFONT, (WPARAM)hTitleFont, TRUE); if (hBackgroundBrush) { SetClassLong(hwndDlg, GCLP_HBRBACKGROUND, (LONG)hBackgroundBrush); InvalidateRect(hwndDlg, 0, TRUE); } return TRUE; case WMU_SETOPT: { Options *opt; if (lParam) opt = (Options *)lParam; else opt = &options; // round corners if (opt->aw_roundcorners) { HRGN hRgn1; RECT r; int v,h; int w=10; GetWindowRect(hwndDlg,&r); h=(r.right-r.left)>(w*2)?w:(r.right-r.left); v=(r.bottom-r.top)>(w*2)?w:(r.bottom-r.top); h=(h<v)?h:v; hRgn1=CreateRoundRectRgn(0,0,(r.right-r.left+1),(r.bottom-r.top+1),h,h); SetWindowRgn(hwndDlg,hRgn1,1); } else { HRGN hRgn1; RECT r; int v,h; int w=10; GetWindowRect(hwndDlg,&r); h=(r.right-r.left)>(w*2)?w:(r.right-r.left); v=(r.bottom-r.top)>(w*2)?w:(r.bottom-r.top); h=(h<v)?h:v; hRgn1=CreateRectRgn(0,0,(r.right-r.left+1),(r.bottom-r.top+1)); SetWindowRgn(hwndDlg,hRgn1,1); } // transparency #ifdef WS_EX_LAYERED SetWindowLongPtr(hwndDlg, GWL_EXSTYLE, GetWindowLongPtr(hwndDlg, GWL_EXSTYLE) | WS_EX_LAYERED); #endif #ifdef LWA_ALPHA SetLayeredWindowAttributes(hwndDlg, RGB(0,0,0), (int)((100 - opt->aw_trans) / 100.0 * 255), LWA_ALPHA); #endif } return TRUE; case WMU_SETALARM: { ALARM *data = (ALARM *)lParam; SetWindowText(hwndDlg, data->szTitle); HWND hw = GetDlgItem(hwndDlg, IDC_TITLE); SetWindowText(hw, data->szTitle); SetDlgItemText(hwndDlg, IDC_ED_DESC, data->szDesc); ((WindowData *)GetWindowLongPtr(hwndDlg, GWLP_USERDATA))->alarm = data; if (data->action & AAF_SOUND && options.loop_sound) { if (data->sound_num <= 3) SetTimer(hwndDlg, ID_TIMER_SOUND, SOUND_REPEAT_PERIOD, 0); else if (data->sound_num == 4) SetTimer(hwndDlg, ID_TIMER_SOUND, SPEACH_REPEAT_PERIOD, 0); } hw = GetDlgItem(hwndDlg, IDC_SNOOZE); EnableWindow(hw, !(data->flags & ALF_NOSNOOZE)); ShowWindow(hw, (data->flags & ALF_NOSNOOZE) ? SW_HIDE : SW_SHOWNA); } return TRUE; case WMU_FAKEALARM: { SetWindowText(hwndDlg, TranslateT("Example alarm")); SetDlgItemText(hwndDlg, IDC_TITLE, TranslateT("Example alarm")); SetDlgItemText(hwndDlg, IDC_ED_DESC, TranslateT("Some example text. Example, example, example.")); } return TRUE; case WM_TIMER: if (wParam == ID_TIMER_SOUND) { WindowData *dw = (WindowData *)GetWindowLongPtr(hwndDlg, GWLP_USERDATA); if (dw) { ALARM *data = dw->alarm; if (data && data->action & AAF_SOUND) { if (data->sound_num <= 3) { char buff[128]; mir_snprintf(buff, SIZEOF(buff), "Triggered%d", data->sound_num); SkinPlaySound(buff); } else if (data->sound_num == 4) { if (data->szTitle != NULL && data->szTitle[0] != '\0') { if (ServiceExists("Speak/Say")) { CallService("Speak/Say", 0, (LPARAM)data->szTitle); } } } } } } return TRUE; case WM_MOVE: Utils_SaveWindowPosition(hwndDlg, 0, MODULE, "Notify"); break; case WMU_ADDSNOOZER: { WindowData *wd = (WindowData *)GetWindowLongPtr(hwndDlg, GWLP_USERDATA); if (wd) { ALARM *data = wd->alarm; if (data) { // add snooze minutes to current time FILETIME ft; GetLocalTime(&data->time); SystemTimeToFileTime(&data->time, &ft); ULARGE_INTEGER uli; uli.LowPart = ft.dwLowDateTime; uli.HighPart = ft.dwHighDateTime; // there are 10000000 100-nanosecond blocks in a second... uli.QuadPart += mult.QuadPart * (int)(wParam); ft.dwHighDateTime = uli.HighPart; ft.dwLowDateTime = uli.LowPart; FileTimeToSystemTime(&ft, &data->time); data->occurrence = OC_ONCE; data->snoozer = true; data->flags = data->flags & ~ALF_NOSTARTUP; data->id = next_alarm_id++; append_to_list(data); } } } return TRUE; case WM_COMMAND: if ( HIWORD( wParam ) == BN_CLICKED ) { switch( LOWORD( wParam )) { case IDCANCEL: // no button - esc pressed case IDOK: // space? case IDC_SNOOZE: SendMessage(hwndDlg, WMU_ADDSNOOZER, (WPARAM)options.snooze_minutes, 0); //drop through case IDC_DISMISS: { WindowData *window_data = (WindowData *)GetWindowLongPtr(hwndDlg, GWLP_USERDATA); KillTimer(hwndDlg, ID_TIMER_SOUND); if (window_data) { if (window_data->alarm) { free_alarm_data(window_data->alarm); delete window_data->alarm; } delete window_data; } SetWindowLongPtr(hwndDlg, GWLP_USERDATA, 0); win_num--; //EndDialog(hwndDlg, IDOK); // not modal! WindowList_Remove(hAlarmWindowList, hwndDlg); DestroyWindow(hwndDlg); } break; case IDC_SNOOZELIST: { POINT pt, pt_rel; GetCursorPos(&pt); pt_rel = pt; ScreenToClient(hwndDlg,&pt_rel); HMENU hMenu = CreatePopupMenu(); MENUITEMINFO mmi = {0}; mmi.cbSize = sizeof(mmi); mmi.fMask = MIIM_ID | MIIM_STRING; #define AddItem(x) \ mmi.wID++; \ mmi.dwTypeData = TranslateT(x); \ mmi.cch = ( UINT )mir_tstrlen(mmi.dwTypeData); \ InsertMenuItem(hMenu, mmi.wID, FALSE, &mmi); AddItem(LPGEN("5 mins")); AddItem(LPGEN("15 mins")); AddItem(LPGEN("30 mins")); AddItem(LPGEN("1 hour")); AddItem(LPGEN("1 day")); AddItem(LPGEN("1 week")); TPMPARAMS tpmp = {0}; tpmp.cbSize = sizeof(tpmp); LRESULT ret = (LRESULT)TrackPopupMenuEx(hMenu, TPM_RETURNCMD, pt.x, pt.y, hwndDlg, &tpmp); switch(ret) { case 0: DestroyMenu(hMenu); return 0; // dismis menu case 1: SendMessage(hwndDlg, WMU_ADDSNOOZER, (WPARAM)5, 0); break; case 2: SendMessage(hwndDlg, WMU_ADDSNOOZER, (WPARAM)15, 0); break; case 3: SendMessage(hwndDlg, WMU_ADDSNOOZER, (WPARAM)30, 0); break; case 4: SendMessage(hwndDlg, WMU_ADDSNOOZER, (WPARAM)60, 0); break; case 5: SendMessage(hwndDlg, WMU_ADDSNOOZER, (WPARAM)(60 * 24), 0); break; case 6: SendMessage(hwndDlg, WMU_ADDSNOOZER, (WPARAM)(60 * 24 * 7), 0); break; } DestroyMenu(hMenu); SendMessage(hwndDlg, WM_COMMAND, IDC_DISMISS, 0); } break; } } return TRUE; case WM_MOUSEMOVE: if (wParam & MK_LBUTTON) { SetCapture(hwndDlg); POINT newp; newp.x = (short)LOWORD(lParam); newp.y = (short)HIWORD(lParam); ClientToScreen(hwndDlg, &newp); WindowData *window_data = (WindowData *)GetWindowLongPtr(hwndDlg, GWLP_USERDATA); if (!window_data->moving) window_data->moving = true; else { RECT r; GetWindowRect(hwndDlg, &r); SetWindowPos(hwndDlg, 0, r.left + (newp.x - window_data->p.x), r.top + (newp.y - window_data->p.y), 0, 0, SWP_NOSIZE | SWP_NOZORDER); } window_data->p.x = newp.x; window_data->p.y = newp.y; } else { ReleaseCapture(); WindowData *window_data = (WindowData *)GetWindowLongPtr(hwndDlg, GWLP_USERDATA); window_data->moving = false; } return TRUE; } return FALSE; }
static HB_BOOL hb_fsFindNextLow( PHB_FFIND ffind ) { HB_BOOL bFound; int iYear = 0; int iMonth = 0; int iDay = 0; int iHour = 0; int iMin = 0; int iSec = 0; int iMSec = 0; HB_FATTR raw_attr = 0, nAttr = 0; /* Set the default values in case some platforms don't support some of these, or they may fail on them. */ ffind->szName[ 0 ] = '\0'; ffind->size = 0; /* Do platform dependant first/next search */ hb_vmUnlock(); #if defined( HB_OS_DOS ) { PHB_FFIND_INFO info = ( PHB_FFIND_INFO ) ffind->info; /* Handling HB_FA_LABEL doesn't need any special tricks under the MS-DOS platform. */ if( ffind->bFirst ) { ffind->bFirst = HB_FALSE; /* tzset(); */ #if defined( __WATCOMC__ ) bFound = ( _dos_findfirst( ffind->pszFileMask, ( HB_USHORT ) hb_fsAttrToRaw( ffind->attrmask ), &info->entry ) == 0 ); #else bFound = ( findfirst( ffind->pszFileMask, &info->entry, ( HB_USHORT ) hb_fsAttrToRaw( ffind->attrmask ) ) == 0 ); #endif } else { #if defined( __WATCOMC__ ) bFound = ( _dos_findnext( &info->entry ) == 0 ); #else bFound = ( findnext( &info->entry ) == 0 ); #endif } /* Fill Harbour found file info */ if( bFound ) { hb_strncpy( ffind->szName, info->entry.ff_name, sizeof( ffind->szName ) - 1 ); ffind->size = info->entry.ff_fsize; raw_attr = info->entry.ff_attrib; { time_t ftime; struct tm * ft; struct stat sStat; stat( info->entry.ff_name, &sStat ); ftime = sStat.st_mtime; ft = localtime( &ftime ); iYear = ft->tm_year + 1900; iMonth = ft->tm_mon + 1; iDay = ft->tm_mday; iHour = ft->tm_hour; iMin = ft->tm_min; iSec = ft->tm_sec; } } hb_fsSetIOError( bFound, 0 ); } #elif defined( HB_OS_OS2 ) { #define HB_OS2_DIRCNT 16 PHB_FFIND_INFO info = ( PHB_FFIND_INFO ) ffind->info; APIRET ret = NO_ERROR; /* TODO: HB_FA_LABEL handling */ if( ffind->bFirst ) { ffind->bFirst = HB_FALSE; info->isWSeB = hb_isWSeB(); info->findSize = sizeof( FILEFINDBUF3L ); if( info->findSize & 0x07 ) info->findSize += 0x08 - ( info->findSize & 0x07 ); info->findSize *= HB_OS2_DIRCNT; if( info->findSize > 0xF000 ) info->findSize = 0xF000; info->findInitCnt = ! info->isWSeB ? info->findSize / 32 : HB_OS2_DIRCNT; info->hFindFile = HDIR_CREATE; info->findCount = info->findInitCnt; ret = DosAllocMem( &info->entry, info->findSize, OBJ_TILE | PAG_COMMIT | PAG_WRITE ); if( ret == NO_ERROR ) { ret = DosFindFirst( ( PCSZ ) ffind->pszFileMask, &info->hFindFile, ( ULONG ) hb_fsAttrToRaw( ffind->attrmask ), info->entry, info->findSize, &info->findCount, FIL_STANDARDL ); bFound = ret == NO_ERROR && info->findCount > 0; if( bFound ) info->next = info->entry; } else { info->entry = NULL; bFound = HB_FALSE; } } else if( info->findCount == 0 ) { info->findCount = info->findInitCnt; ret = DosFindNext( info->hFindFile, info->entry, info->findSize, &info->findCount ); bFound = ret == NO_ERROR && info->findCount > 0; if( bFound ) info->next = info->entry; } else bFound = HB_TRUE; if( bFound ) { ULONG oNextEntryOffset; if( info->isWSeB ) { PFILEFINDBUF3L pFFB = ( PFILEFINDBUF3L ) info->next; hb_strncpy( ffind->szName, pFFB->achName, sizeof( ffind->szName ) - 1 ); ffind->size = ( HB_FOFFSET ) pFFB->cbFile; raw_attr = pFFB->attrFile; iYear = pFFB->fdateLastWrite.year + 1980; iMonth = pFFB->fdateLastWrite.month; iDay = pFFB->fdateLastWrite.day; iHour = pFFB->ftimeLastWrite.hours; iMin = pFFB->ftimeLastWrite.minutes; iSec = pFFB->ftimeLastWrite.twosecs * 2; oNextEntryOffset = pFFB->oNextEntryOffset; } else { PFILEFINDBUF3 pFFB = ( PFILEFINDBUF3 ) info->next; hb_strncpy( ffind->szName, pFFB->achName, sizeof( ffind->szName ) - 1 ); ffind->size = ( HB_FOFFSET ) pFFB->cbFile; raw_attr = pFFB->attrFile; iYear = pFFB->fdateLastWrite.year + 1980; iMonth = pFFB->fdateLastWrite.month; iDay = pFFB->fdateLastWrite.day; iHour = pFFB->ftimeLastWrite.hours; iMin = pFFB->ftimeLastWrite.minutes; iSec = pFFB->ftimeLastWrite.twosecs * 2; oNextEntryOffset = pFFB->oNextEntryOffset; } if( oNextEntryOffset > 0 ) { info->next = ( char * ) info->next + oNextEntryOffset; info->findCount--; } else info->findCount = 0; } hb_fsSetError( ( HB_ERRCODE ) ret ); } #elif defined( HB_OS_WIN ) { PHB_FFIND_INFO info = ( PHB_FFIND_INFO ) ffind->info; bFound = HB_FALSE; #if ! defined( HB_OS_WIN_CE ) if( ( ffind->attrmask & HB_FA_LABEL ) != 0 && ! info->fLabelDone ) { TCHAR lpVolName[ HB_PATH_MAX ]; LPTSTR lpFileMask = NULL; char * mask = NULL; info->fLabelDone = HB_TRUE; if( ffind->pszFileMask && *ffind->pszFileMask ) { PHB_FNAME pFileName = hb_fsFNameSplit( ffind->pszFileMask ); if( pFileName->szName && pFileName->szName[ 0 ] ) mask = hb_strdup( pFileName->szName ); if( pFileName->szPath && pFileName->szPath[ 0 ] && ( pFileName->szPath[ 1 ] || pFileName->szPath[ 0 ] != HB_OS_PATH_DELIM_CHR ) ) lpFileMask = HB_CHARDUP( pFileName->szPath ); hb_xfree( pFileName ); } bFound = GetVolumeInformation( lpFileMask, lpVolName, HB_SIZEOFARRAY( lpVolName ), NULL, NULL, NULL, NULL, 0 ) != 0; if( bFound ) { HB_OSSTRDUP2( lpVolName, ffind->szName, sizeof( ffind->szName ) - 1 ); if( mask && *mask && ! hb_strMatchFile( ffind->szName, mask ) ) { ffind->szName[ 0 ] = '\0'; bFound = HB_FALSE; } } if( lpFileMask ) hb_xfree( lpFileMask ); if( mask ) hb_xfree( mask ); } #endif if( ! bFound && ( ffind->attrmask & ( HB_FA_LABEL | HB_FA_HIDDEN | HB_FA_SYSTEM | HB_FA_DIRECTORY ) ) != HB_FA_LABEL ) { if( ffind->bFirst ) { LPTSTR lpFileMask = HB_CHARDUP( ffind->pszFileMask ); ffind->bFirst = HB_FALSE; info->dwAttr = ( DWORD ) hb_fsAttrToRaw( ffind->attrmask ); info->hFindFile = FindFirstFile( lpFileMask, &info->pFindFileData ); hb_xfree( lpFileMask ); if( ( info->hFindFile != INVALID_HANDLE_VALUE ) && _HB_WIN_MATCH() ) bFound = HB_TRUE; } if( ! bFound && info->hFindFile != INVALID_HANDLE_VALUE ) { while( FindNextFile( info->hFindFile, &info->pFindFileData ) ) { if( _HB_WIN_MATCH() ) { bFound = HB_TRUE; break; } } } /* Fill Harbour found file info */ if( bFound ) { HB_OSSTRDUP2( info->pFindFileData.cFileName, ffind->szName, sizeof( ffind->szName ) - 1 ); if( info->pFindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) ffind->size = 0; else { #if defined( __XCC__ ) || ( defined( __POCC__ ) && __POCC__ >= 500 ) /* NOTE: PellesC 5.00.1 will go into an infinite loop if we don't split this into two operations. [vszakats] */ ffind->size = ( HB_FOFFSET ) info->pFindFileData.nFileSizeLow; ffind->size += ( HB_FOFFSET ) info->pFindFileData.nFileSizeHigh << 32; #else ffind->size = ( HB_FOFFSET ) info->pFindFileData.nFileSizeLow + ( ( HB_FOFFSET ) info->pFindFileData.nFileSizeHigh << 32 ); #endif } raw_attr = ( HB_FATTR ) info->pFindFileData.dwFileAttributes; /* NOTE: One of these may fail when searching on an UNC path, I don't know yet what's the reason. [vszakats] */ { FILETIME ft; SYSTEMTIME time; if( FileTimeToLocalFileTime( &info->pFindFileData.ftLastWriteTime, &ft ) && FileTimeToSystemTime( &ft, &time ) ) { iYear = time.wYear; iMonth = time.wMonth; iDay = time.wDay; iHour = time.wHour; iMin = time.wMinute; iSec = time.wSecond; iMSec = time.wMilliseconds; } } } } hb_fsSetIOError( bFound, 0 ); } #elif defined( HB_OS_UNIX ) { PHB_FFIND_INFO info = ( PHB_FFIND_INFO ) ffind->info; char dirname[ HB_PATH_MAX ]; bFound = HB_FALSE; /* TODO: HB_FA_LABEL handling */ if( ffind->bFirst ) { char * pos; ffind->bFirst = HB_FALSE; hb_strncpy( dirname, ffind->pszFileMask, sizeof( dirname ) - 1 ); pos = strrchr( dirname, HB_OS_PATH_DELIM_CHR ); if( pos ) { hb_strncpy( info->pattern, pos + 1, sizeof( info->pattern ) - 1 ); *( pos + 1 ) = '\0'; } else { hb_strncpy( info->pattern, dirname, sizeof( info->pattern ) - 1 ); dirname[ 0 ] = '.'; dirname[ 1 ] = HB_OS_PATH_DELIM_CHR; dirname[ 2 ] = '\0'; } /* tzset(); */ info->dir = opendir( dirname ); hb_strncpy( info->path, dirname, sizeof( info->path ) - 1 ); } if( info->dir && info->pattern[ 0 ] != '\0' ) { while( ( info->entry = readdir( info->dir ) ) != NULL ) { if( hb_strMatchFile( info->entry->d_name, info->pattern ) ) { bFound = HB_TRUE; break; } } } /* Fill Harbour found file info */ if( bFound ) { hb_strncpy( dirname, info->path, sizeof( dirname ) - 1 ); hb_strncat( dirname, info->entry->d_name, sizeof( dirname ) - 1 ); { time_t ftime; struct tm lt; #if defined( HB_USE_LARGEFILE64 ) struct stat64 sStat, sStatL; if( lstat64( dirname, &sStat ) == 0 ) { if( S_ISLNK( sStat.st_mode ) && ( ffind->attrmask & HB_FA_LINK ) == 0 ) { if( stat64( dirname, &sStatL ) == 0 ) memcpy( &sStat, &sStatL, sizeof( sStat ) ); nAttr |= HB_FA_LINK; } #else struct stat sStat, sStatL; if( lstat( dirname, &sStat ) == 0 ) { if( S_ISLNK( sStat.st_mode ) && ( ffind->attrmask & HB_FA_LINK ) == 0 ) { if( stat( dirname, &sStatL ) == 0 ) memcpy( &sStat, &sStatL, sizeof( sStat ) ); nAttr |= HB_FA_LINK; } #endif hb_strncpy( ffind->szName, info->entry->d_name, sizeof( ffind->szName ) - 1 ); ffind->size = sStat.st_size; raw_attr = sStat.st_mode; ftime = sStat.st_mtime; # if defined( HB_HAS_LOCALTIME_R ) localtime_r( &ftime, < ); # else lt = *localtime( &ftime ); # endif iYear = lt.tm_year + 1900; iMonth = lt.tm_mon + 1; iDay = lt.tm_mday; iHour = lt.tm_hour; iMin = lt.tm_min; iSec = lt.tm_sec; # if defined( HB_OS_LINUX ) && \ defined( __GLIBC__ ) && defined( __GLIBC_MINOR__ ) && \ ( __GLIBC__ > 2 || ( __GLIBC__ == 2 && __GLIBC_MINOR__ >= 6 ) ) # if defined( _BSD_SOURCE ) || defined( _SVID_SOURCE ) || \ ( __GLIBC_MINOR__ >= 12 && \ ( ( defined( _POSIX_C_SOURCE ) || _POSIX_C_SOURCE >= 200809L ) || \ ( defined( _XOPEN_SOURCE ) || _XOPEN_SOURCE >= 700 ) ) ) iMSec = sStat.st_mtim.tv_nsec / 1000000; # else iMSec = sStat.st_mtimensec / 1000000; # endif # endif } else bFound = HB_FALSE; } } hb_fsSetIOError( bFound, 0 ); } #else { int iTODO; /* TODO: for given platform */ /* HB_SYMBOL_UNUSED( ffind ); */ HB_SYMBOL_UNUSED( iYear ); HB_SYMBOL_UNUSED( iMonth ); HB_SYMBOL_UNUSED( iDay ); HB_SYMBOL_UNUSED( iHour ); HB_SYMBOL_UNUSED( iMin ); HB_SYMBOL_UNUSED( iSec ); HB_SYMBOL_UNUSED( iMSec ); HB_SYMBOL_UNUSED( raw_attr ); bFound = HB_FALSE; hb_fsSetIOError( bFound, 0 ); } #endif /* Fill common Harbour found file info */ if( bFound ) { /* Do the conversions common for all platforms */ ffind->szName[ sizeof( ffind->szName ) - 1 ] = '\0'; #if ! defined( HB_OS_WIN ) /* Convert from OS codepage */ { char * pszFree = NULL; HB_SIZE nSize = sizeof( ffind->szName ); const char * pszResult = hb_osDecodeCP( ffind->szName, &pszFree, &nSize ); if( pszFree ) { hb_strncpy( ffind->szName, pszResult, sizeof( ffind->szName ) - 1 ); hb_xfree( pszFree ); } } #endif ffind->attr = hb_fsAttrFromRaw( raw_attr ) | nAttr; ffind->lDate = hb_dateEncode( iYear, iMonth, iDay ); ffind->lTime = hb_timeEncode( iHour, iMin, iSec, iMSec ); hb_dateStrPut( ffind->szDate, iYear, iMonth, iDay ); ffind->szDate[ 8 ] = '\0'; hb_snprintf( ffind->szTime, sizeof( ffind->szTime ), "%02d:%02d:%02d", iHour, iMin, iSec ); } hb_vmLock(); return bFound; } PHB_FFIND hb_fsFindFirst( const char * pszFileMask, HB_FATTR attrmask ) { PHB_FFIND ffind = ( PHB_FFIND ) hb_xgrabz( sizeof( HB_FFIND ) ); /* Allocate platform dependent file find info storage */ ffind->info = ( void * ) hb_xgrabz( sizeof( HB_FFIND_INFO ) ); /* Store search parameters */ #if defined( HB_OS_WIN ) ffind->pszFileMask = pszFileMask; #else /* Convert to OS codepage */ ffind->pszFileMask = hb_fsNameConv( pszFileMask, &ffind->pszFree ); #endif ffind->attrmask = attrmask; ffind->bFirst = HB_TRUE; /* Find first/next matching file */ if( hb_fsFindNext( ffind ) ) return ffind; /* If no file found at all, free stuff allocated so far and return NULL. */ hb_fsFindClose( ffind ); return NULL; }
int CzHttp::Exec( void ) { // 毎フレーム実行 // static char hdr[] = "Content-Type: application/x-www-form-urlencoded\r\n"; char req_name[1024]; char *name; BOOL res; switch( mode ) { case CZHTTP_MODE_REQUEST: // httpに接続 strcpy( req_name, req_url ); strcat( req_name, req_path ); hService = InternetOpenUrl( hSession, req_name, req_header, -1L, 0, INTERNET_FLAG_RELOAD ); if ( hService == NULL ) { SetError( "無効なURLが指定されました" ); break; } mode = CZHTTP_MODE_REQSEND; case CZHTTP_MODE_REQSEND: name = down_path; if ( name[0] == 0 ) name = req_path; fp = fopen( name, "wb"); if ( fp == NULL ) { SetError( "ダウンロードファイルが作成できません" ); break; } size = 0; mode = CZHTTP_MODE_DATAWAIT; case CZHTTP_MODE_DATAWAIT: { DWORD dwBytesRead = INETBUF_MAX; if ( InternetReadFile( hService, buf, INETBUF_MAX, &dwBytesRead ) == 0 ) { fclose( fp ); InternetCloseHandle( hService ); SetError( "ダウンロード中にエラーが発生しました" ); break; } if( dwBytesRead == 0 ) { mode = CZHTTP_MODE_DATAEND; break; } fwrite( buf, dwBytesRead, 1, fp ); size += dwBytesRead; break; } case CZHTTP_MODE_DATAEND: fclose( fp ); InternetCloseHandle( hService ); mode = CZHTTP_MODE_READY; break; case CZHTTP_MODE_VARREQUEST: strcpy( req_name, req_url2 ); strcat( req_name, req_path ); // HTTPに接続 hHttpSession = ::InternetConnectA( hSession, varserver, varport, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0 ); if ( hHttpSession == NULL ) { SetError( "無効なサーバーが指定されました" ); break; } // HTTP要求の作成 hHttpRequest = ::HttpOpenRequestA( hHttpSession, varstr, req_name, HTTP_VERSION, NULL, NULL, INTERNET_FLAG_RELOAD|INTERNET_FLAG_NO_UI, 0 ); if ( hHttpSession == NULL ) { SetError( "無効なURLが指定されました" ); break; } mode = CZHTTP_MODE_VARREQSEND; // FALL THROUGH case CZHTTP_MODE_VARREQSEND: // 作成したHTTP要求の発行 if ( postdata != NULL ) { char *additional_header = req_header != NULL ? req_header : ""; char *header = (char *)malloc( strlen(hdr) + strlen(additional_header) + 1 ); strcpy(header, hdr); strcat(header, additional_header); res = ::HttpSendRequestA( hHttpRequest, header, -1L, postdata, (int)strlen(postdata) ); free(header); } else { res = ::HttpSendRequestA( hHttpRequest, req_header, -1L, NULL, 0 ); } if ( res == false ) { InternetCloseHandle( hHttpSession ); SetError( "リクエストができませんでした" ); break; } /* { // 返されたコンテンツの長さを取得 DWORD dwSize = INETBUF_MAX; *buf = 0; res = HttpQueryInfo( hHttpRequest, HTTP_QUERY_CONTENT_LENGTH, buf, &dwSize, 0 ); if ( res == false ) { InternetCloseHandle( hHttpRequest ); InternetCloseHandle( hHttpSession ); SetError( "データサイズ取得ができませんでした" ); break; } varsize = atoi(buf); if ( varsize == 0 ) { InternetCloseHandle( hHttpRequest ); InternetCloseHandle( hHttpSession ); SetError( "ダウンロードできませんでした" ); break; } } */ varsize = 0x40000; ClearVarData(); vardata = (char *)malloc( varsize ); size = 0; mode = CZHTTP_MODE_VARDATAWAIT; // FALL THROUGH case CZHTTP_MODE_VARDATAWAIT: { DWORD dwBytesRead; int needed_size = size + INETBUF_MAX + 1; if ( needed_size > varsize ) { while ( needed_size > varsize ) { varsize *= 2; } vardata = (char *)realloc( vardata, varsize ); } if ( InternetReadFile( hHttpRequest, vardata+size, INETBUF_MAX, &dwBytesRead ) == 0 ) { InternetCloseHandle( hHttpRequest ); InternetCloseHandle( hHttpSession ); SetError( "ダウンロード中にエラーが発生しました" ); break; } size += dwBytesRead; if( dwBytesRead == 0 ) { mode = CZHTTP_MODE_VARDATAEND; vardata[size] = 0; break; } break; } case CZHTTP_MODE_VARDATAEND: InternetCloseHandle( hHttpRequest ); InternetCloseHandle( hHttpSession ); mode = CZHTTP_MODE_READY; break; case CZHTTP_MODE_INFOREQ: strcpy( req_name, req_url ); strcat( req_name, req_path ); hService = InternetOpenUrl( hSession, req_name, req_header, -1L, 0, 0 ); if ( hService == NULL ) { SetError( "無効なURLが指定されました" ); break; } mode = CZHTTP_MODE_INFORECV; case CZHTTP_MODE_INFORECV: { DWORD dwSize = INETBUF_MAX; buf[0] = 0; HttpQueryInfo( hService, HTTP_QUERY_RAW_HEADERS_CRLF, buf, &dwSize, 0 ); InternetCloseHandle( hService ); mode = CZHTTP_MODE_READY; break; } case CZHTTP_MODE_FTPREADY: return 2; case CZHTTP_MODE_FTPDIR: { char tx[512]; char dname[64]; char *fname; SYSTEMTIME t; fname = finddata.cFileName; if( finddata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { strcpy( dname, "<DIR>" ); } else { sprintf( dname, "%d", finddata.nFileSizeLow ); } FileTimeToSystemTime( &finddata.ftLastWriteTime,&t ); sprintf( tx, "\"%s\",%s,%4d/%02d/%02d,%02d:%02d:%02d\r\n", fname, dname, t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond ); AddFlexBuf( tx, (int)strlen(tx) ); if ( !InternetFindNextFile( hFtpEnum, &finddata ) ) { InternetCloseHandle( hFtpEnum ); mode = CZHTTP_MODE_FTPREADY; } break; } case CZHTTP_MODE_FTPREAD: break; case CZHTTP_MODE_FTPWRITE: break; case CZHTTP_MODE_FTPCMD: { char tx[1024]; DWORD dwBytesRead; if( InternetReadFile( hResponse, buf, 1024, &dwBytesRead ) ) { AddFlexBuf( tx, dwBytesRead ); } if ( dwBytesRead == 0 ) { InternetCloseHandle( hResponse ); mode = CZHTTP_MODE_FTPREADY; } break; } case CZHTTP_MODE_FTPRESULT: GetFtpResponse(); break; case CZHTTP_MODE_ERROR: return -1; default: return 1; } return 0; }
// This method compresses the files contained in the report and produces ZIP archive. BOOL CErrorReportSender::CompressReportFiles() { BOOL bStatus = FALSE; strconv_t strconv; zipFile hZip = NULL; CString sMsg; LONG64 lTotalSize = 0; LONG64 lTotalCompressed = 0; BYTE buff[1024]; DWORD dwBytesRead=0; HANDLE hFile = INVALID_HANDLE_VALUE; std::map<CString, FileItem>::iterator it; LARGE_INTEGER lFileSize; BOOL bGetSize = FALSE; if(m_bExport) m_Assync.SetProgress(_T("[exporting_report]"), 0, false); else m_Assync.SetProgress(_T("[compressing_files]"), 0, false); m_Assync.SetProgress(_T("Calculating total size of files to compress..."), 0, false); for(it=g_CrashInfo.m_FileItems.begin(); it!=g_CrashInfo.m_FileItems.end(); it++) { if(m_Assync.IsCancelled()) goto cleanup; CString sFileName = it->second.m_sSrcFile.GetBuffer(0); hFile = CreateFile(sFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL); if(hFile==INVALID_HANDLE_VALUE) { sMsg.Format(_T("Couldn't open file %s"), sFileName); m_Assync.SetProgress(sMsg, 0, false); continue; } bGetSize = GetFileSizeEx(hFile, &lFileSize); if(!bGetSize) { sMsg.Format(_T("Couldn't get file size of %s"), sFileName); m_Assync.SetProgress(sMsg, 0, false); CloseHandle(hFile); continue; } lTotalSize += lFileSize.QuadPart; CloseHandle(hFile); hFile = INVALID_HANDLE_VALUE; } sMsg.Format(_T("Total file size for compression is %I64d"), lTotalSize); m_Assync.SetProgress(sMsg, 0, false); if(m_bExport) m_sZipName = m_sExportFileName; else m_sZipName = g_CrashInfo.m_sErrorReportDirName + _T(".zip"); sMsg.Format(_T("Creating ZIP archive file %s"), m_sZipName); m_Assync.SetProgress(sMsg, 1, false); hZip = zipOpen(strconv.t2a(m_sZipName.GetBuffer(0)), APPEND_STATUS_CREATE); if(hZip==NULL) { m_Assync.SetProgress(_T("Failed to create ZIP file."), 100, true); goto cleanup; } for(it=g_CrashInfo.m_FileItems.begin(); it!=g_CrashInfo.m_FileItems.end(); it++) { if(m_Assync.IsCancelled()) goto cleanup; CString sDstFileName = it->second.m_sDestFile.GetBuffer(0); CString sFileName = it->second.m_sSrcFile.GetBuffer(0); CString sDesc = it->second.m_sDesc; sMsg.Format(_T("Compressing %s"), sDstFileName); m_Assync.SetProgress(sMsg, 0, false); HANDLE hFile = CreateFile(sFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL); if(hFile==INVALID_HANDLE_VALUE) { sMsg.Format(_T("Couldn't open file %s"), sFileName); m_Assync.SetProgress(sMsg, 0, false); continue; } BY_HANDLE_FILE_INFORMATION fi; GetFileInformationByHandle(hFile, &fi); SYSTEMTIME st; FileTimeToSystemTime(&fi.ftCreationTime, &st); zip_fileinfo info; info.dosDate = 0; info.tmz_date.tm_year = st.wYear; info.tmz_date.tm_mon = st.wMonth; info.tmz_date.tm_mday = st.wDay; info.tmz_date.tm_hour = st.wHour; info.tmz_date.tm_min = st.wMinute; info.tmz_date.tm_sec = st.wSecond; info.external_fa = FILE_ATTRIBUTE_NORMAL; info.internal_fa = FILE_ATTRIBUTE_NORMAL; int n = zipOpenNewFileInZip( hZip, strconv.t2a(sDstFileName), &info, NULL, 0, NULL, 0, strconv.t2a(sDesc), Z_DEFLATED, Z_DEFAULT_COMPRESSION); if(n!=0) { sMsg.Format(_T("Couldn't compress file %s"), sDstFileName); m_Assync.SetProgress(sMsg, 0, false); continue; } for(;;) { if(m_Assync.IsCancelled()) goto cleanup; BOOL bRead = ReadFile(hFile, buff, 1024, &dwBytesRead, NULL); if(!bRead || dwBytesRead==0) break; int res = zipWriteInFileInZip(hZip, buff, dwBytesRead); if(res!=0) { zipCloseFileInZip(hZip); sMsg.Format(_T("Couldn't write to compressed file %s"), sDstFileName); m_Assync.SetProgress(sMsg, 0, false); break; } lTotalCompressed += dwBytesRead; float fProgress = 100.0f*lTotalCompressed/lTotalSize; m_Assync.SetProgress((int)fProgress, false); } zipCloseFileInZip(hZip); CloseHandle(hFile); hFile = INVALID_HANDLE_VALUE; } if(lTotalSize==lTotalCompressed) bStatus = TRUE; cleanup: if(hZip!=NULL) zipClose(hZip, NULL); if(hFile!=INVALID_HANDLE_VALUE) CloseHandle(hFile); if(bStatus) m_Assync.SetProgress(_T("Finished compressing files...OK"), 100, true); else m_Assync.SetProgress(_T("File compression failed."), 100, true); if(m_bExport) { if(bStatus) m_Assync.SetProgress(_T("[end_exporting_report_ok]"), 100, false); else m_Assync.SetProgress(_T("[end_exporting_report_failed]"), 100, false); } else { m_Assync.SetProgress(_T("[end_compressing_files]"), 100, false); } return bStatus; }
static LRESULT CALLBACK PropProc( HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam ) { switch ( uMsg ) { case WM_INITDIALOG: { LPCLASSDATA lpcd = ( LPCLASSDATA )lParam; HDC hDC; RECT rcClient; HWND hControl; HFONT hFont, hOFont; TCHAR szBuffer[ MAX_PATH ]; int i; /* * Save data. */ nFileMode = Parser->nFileMode; nTabSize = Parser->nTabSize; /* * Setup class data pointer as * the dialog user data. */ SetWindowLong( hDlg, DWL_USER, ( LONG )lpcd ); /* * Get handle to the file name control. */ hControl = GetDlgItem( hDlg, IDC_PROP_FILENAME ); /* * Copy the file name into * a buffer. */ _tcsncpy_s( szBuffer, MAX_PATH, lpcd->szFileName, MAX_PATH ); /* * Get the client rectangle of * the file name control. */ GetClientRect( hControl, &rcClient ); /* * Get the device context. */ if (( hDC = GetDC( hControl )) != NULL ) { /* * Get the dialog font. */ if (( hFont = ( HFONT )SendMessage( hDlg, WM_GETFONT, 0, 0 )) != NULL ) { /* * Make sure we use the correct font. */ hOFont = SelectObject( hDC, hFont ); /* * Compact the path. */ PathCompactPath( hDC, szBuffer, rcClient.right ); /* * Reset the font. */ SelectObject( hDC, hOFont ); } /* * Release the device context. */ ReleaseDC( hControl, hDC ); } /* * Set the path. */ SetWindowText( hControl, szBuffer ); /* * Unicode? */ SetDlgItemText( hDlg, IDC_PROP_UNICODE, GetString( lpcd->bUnicode ? IDS_TRUE : IDS_FALSE )); /* * Setup the up/down range * and the tab stop. */ SendDlgItemMessage( hDlg, IDC_PROP_TABSPIN, UDM_SETRANGE, 0, MAKELPARAM( 24,2 )); /* * Setup file modes. */ for ( i = FMODE_MSDOS; i <= FMODE_MACINTOSH; i++ ) SendDlgItemMessage( hDlg, IDC_PROP_TYPE, CB_ADDSTRING, 0, ( LPARAM )lpszFileModes[ i ] ); /* * Setup the file size and the * tab size controls. */ SetSizeControls( hDlg ); /* * Valid file date? */ if ( lpcd->ftFileTime.dwHighDateTime == 0 && lpcd->ftFileTime.dwLowDateTime == 0 ) SetDlgItemText( hDlg, IDC_PROP_DATE, GetString( IDS_NOT_SAVED )); else { FILETIME ft; SYSTEMTIME st; /* * Convert file time to * system time. */ FileTimeToLocalFileTime( &lpcd->ftFileTime, &ft ); FileTimeToSystemTime( &ft, &st ); /* * Format time. */ GetTimeFormat( LOCALE_USER_DEFAULT, 0, //LOCALE_NOUSEROVERRIDE, &st, NULL, szBuffer, 256 ); /* * Add space. */ _tcscat_s( szBuffer, MAX_PATH, _T(" ")); /* * Format date. */ GetDateFormat( LOCALE_USER_DEFAULT, 0, //LOCALE_NOUSEROVERRIDE, &st, NULL, &szBuffer[ _tcslen( szBuffer ) ], 256 - _tcslen( szBuffer )); /* * Output result. */ SetDlgItemText( hDlg, IDC_PROP_DATE, szBuffer ); } /* * Focus the OK button. */ return TRUE; } case WM_CLOSE: /* * Bye... */ EndDialog( hDlg, 0 ); break; case WM_COMMAND: { LPCLASSDATA lpcd = ( LPCLASSDATA )GetWindowLong( hDlg, DWL_USER ); switch ( LOWORD( wParam )) { case IDC_PROP_TYPE: /* * Get file mode. */ Parser->nFileMode = SendDlgItemMessage( hDlg, IDC_PROP_TYPE, CB_GETCURSEL, 0, 0 ); /* * Send status message. */ SendStatusMessage( lpcd ); break; case IDC_PROP_TABSIZE: { /* * Lost focus on the edit control? */ if ( HIWORD( wParam ) == EN_KILLFOCUS ) { /* * Get value. */ int nTabStop = GetDlgItemInt( hDlg, IDC_PROP_TABSIZE, NULL, FALSE ); /* * Clamp entered value between 2 and 24. */ if ( nTabStop < 2 ) nTabStop = 2; else if ( nTabStop > 24 ) nTabStop = 24; /* * Set this value to the * edit control. */ SetDlgItemInt( hDlg, IDC_PROP_TABSIZE, ( UINT )nTabStop, FALSE ); /* * Save tab value. */ Parser->nTabSize = nTabStop; /* * Re-render if it changed... */ if ( nTabStop != nTabSize ) InvalidateRect( lpcd->hWnd, NULL, FALSE ); } break; } case IDCANCEL: /* * Reset tabsize. */ if ( Parser->nTabSize != nTabSize ) { Parser->nTabSize = nTabSize; InvalidateRect( lpcd->hWnd, NULL, FALSE ); } /* * And file mode. */ if ( Parser->nFileMode != nFileMode ) { Parser->nFileMode = nFileMode; SendStatusMessage( lpcd ); } /* * Fall through... */ case IDOK: /* * Bye... */ EndDialog( hDlg, 0 ); break; } } } return 0; }
local int FileTime2utime(FILETIME *pft, time_t *ut) { #ifndef NO_INT64 ULLNG64 NTtime; NTtime = ((ULLNG64)pft->dwLowDateTime + ((ULLNG64)pft->dwHighDateTime << 32)); /* underflow and overflow handling */ #ifdef CHECK_UTIME_SIGNED_UNSIGNED if ((time_t)0x80000000L < (time_t)0L) { if (NTtime < ((ULLNG64)UNIX_TIME_SMIN_LO + ((ULLNG64)UNIX_TIME_SMIN_HI << 32))) { *ut = (time_t)LONG_MIN; return FALSE; } if (NTtime > ((ULLNG64)UNIX_TIME_SMAX_LO + ((ULLNG64)UNIX_TIME_SMAX_HI << 32))) { *ut = (time_t)LONG_MAX; return FALSE; } } else #endif /* CHECK_UTIME_SIGNED_UNSIGNED */ { if (NTtime < ((ULLNG64)UNIX_TIME_ZERO_LO + ((ULLNG64)UNIX_TIME_ZERO_HI << 32))) { *ut = (time_t)0; return FALSE; } if (NTtime > ((ULLNG64)UNIX_TIME_UMAX_LO + ((ULLNG64)UNIX_TIME_UMAX_HI << 32))) { *ut = (time_t)ULONG_MAX; return FALSE; } } NTtime -= ((ULLNG64)UNIX_TIME_ZERO_LO + ((ULLNG64)UNIX_TIME_ZERO_HI << 32)); *ut = (time_t)(NTtime / (unsigned long)NT_QUANTA_PER_UNIX); return TRUE; #else /* NO_INT64 (64-bit integer arithmetics may not be supported) */ /* nonzero if `y' is a leap year, else zero */ # define leap(y) (((y)%4 == 0 && (y)%100 != 0) || (y)%400 == 0) /* number of leap years from 1970 to `y' (not including `y' itself) */ # define nleap(y) (((y)-1969)/4 - ((y)-1901)/100 + ((y)-1601)/400) /* daycount at the end of month[m-1] */ static ZCONST ush ydays[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; time_t days; SYSTEMTIME w32tm; /* underflow and overflow handling */ #ifdef CHECK_UTIME_SIGNED_UNSIGNED if ((time_t)0x80000000L < (time_t)0L) { if ((pft->dwHighDateTime < UNIX_TIME_SMIN_HI) || ((pft->dwHighDateTime == UNIX_TIME_SMIN_HI) && (pft->dwLowDateTime < UNIX_TIME_SMIN_LO))) { *ut = (time_t)LONG_MIN; return FALSE; if ((pft->dwHighDateTime > UNIX_TIME_SMAX_HI) || ((pft->dwHighDateTime == UNIX_TIME_SMAX_HI) && (pft->dwLowDateTime > UNIX_TIME_SMAX_LO))) { *ut = (time_t)LONG_MAX; return FALSE; } } else #endif /* CHECK_UTIME_SIGNED_UNSIGNED */ { if ((pft->dwHighDateTime < UNIX_TIME_ZERO_HI) || ((pft->dwHighDateTime == UNIX_TIME_ZERO_HI) && (pft->dwLowDateTime < UNIX_TIME_ZERO_LO))) { *ut = (time_t)0; return FALSE; } if ((pft->dwHighDateTime > UNIX_TIME_UMAX_HI) || ((pft->dwHighDateTime == UNIX_TIME_UMAX_HI) && (pft->dwLowDateTime > UNIX_TIME_UMAX_LO))) { *ut = (time_t)ULONG_MAX; return FALSE; } } FileTimeToSystemTime(pft, &w32tm); /* set `days' to the number of days into the year */ days = w32tm.wDay - 1 + ydays[w32tm.wMonth-1] + (w32tm.wMonth > 2 && leap (w32tm.wYear)); /* now set `days' to the number of days since 1 Jan 1970 */ days += 365 * (time_t)(w32tm.wYear - 1970) + (time_t)(nleap(w32tm.wYear)); *ut = (time_t)(86400L * days + 3600L * (time_t)w32tm.wHour + (time_t)(60 * w32tm.wMinute + w32tm.wSecond)); return TRUE; #endif /* ?NO_INT64 */ } /* end function FileTime2utime() */ #endif /* USE_EF_UT_TIME || NT_TZBUG_WORKAROUND */ #if (defined(NT_TZBUG_WORKAROUND) && defined(W32_STAT_BANDAID)) local int VFatFileTime2utime(const FILETIME *pft, time_t *ut) { FILETIME lft; SYSTEMTIME w32tm; struct tm ltm; FileTimeToLocalFileTime(pft, &lft); FileTimeToSystemTime(&lft, &w32tm); /* underflow and overflow handling */ /* TODO: The range checks are not accurate, the actual limits may * be off by one daylight-saving-time shift (typically 1 hour), * depending on the current state of "is_dst". */ #ifdef CHECK_UTIME_SIGNED_UNSIGNED if ((time_t)0x80000000L < (time_t)0L) { if ((pft->dwHighDateTime < UNIX_TIME_SMIN_HI) || ((pft->dwHighDateTime == UNIX_TIME_SMIN_HI) && (pft->dwLowDateTime < UNIX_TIME_SMIN_LO))) { *ut = (time_t)LONG_MIN; return FALSE; if ((pft->dwHighDateTime > UNIX_TIME_SMAX_HI) || ((pft->dwHighDateTime == UNIX_TIME_SMAX_HI) && (pft->dwLowDateTime > UNIX_TIME_SMAX_LO))) { *ut = (time_t)LONG_MAX; return FALSE; } } else #endif /* CHECK_UTIME_SIGNED_UNSIGNED */ { if ((pft->dwHighDateTime < UNIX_TIME_ZERO_HI) || ((pft->dwHighDateTime == UNIX_TIME_ZERO_HI) && (pft->dwLowDateTime < UNIX_TIME_ZERO_LO))) { *ut = (time_t)0; return FALSE; } if ((pft->dwHighDateTime > UNIX_TIME_UMAX_HI) || ((pft->dwHighDateTime == UNIX_TIME_UMAX_HI) && (pft->dwLowDateTime > UNIX_TIME_UMAX_LO))) { *ut = (time_t)ULONG_MAX; return FALSE; } } ltm.tm_year = w32tm.wYear - 1900; ltm.tm_mon = w32tm.wMonth - 1; ltm.tm_mday = w32tm.wDay; ltm.tm_hour = w32tm.wHour; ltm.tm_min = w32tm.wMinute; ltm.tm_sec = w32tm.wSecond; ltm.tm_isdst = -1; /* let mktime determine if DST is in effect */ *ut = mktime(<m); /* a cheap error check: mktime returns "(time_t)-1L" on conversion errors. * Normally, we would have to apply a consistency check because "-1" * could also be a valid time. But, it is quite unlikely to read back odd * time numbers from file systems that store time stamps in DOS format. * (The only known exception is creation time on VFAT partitions.) */ return (*ut != (time_t)-1L); } /* end function VFatFileTime2utime() */ #endif /* NT_TZBUG_WORKAROUND && W32_STAT_BANDAID */ #if 0 /* Currently, this is not used at all */ long GetTheFileTime(char *name, iztimes *z_ut) { HANDLE h; FILETIME Modft, Accft, Creft, lft; WORD dh, dl; #ifdef __RSXNT__ /* RSXNT/EMX C rtl uses OEM charset */ char *ansi_name = (char *)alloca(strlen(name) + 1); OemToAnsi(name, ansi_name); name = ansi_name; #endif h = CreateFile(name, FILE_READ_ATTRIBUTES, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); if ( h != INVALID_HANDLE_VALUE ) { BOOL ftOK = GetFileTime(h, &Creft, &Accft, &Modft); CloseHandle(h); #ifdef USE_EF_UT_TIME if (ftOK && (z_ut != NULL)) { FileTime2utime(&Modft, &(z_ut->mtime)); if (Accft.dwLowDateTime != 0 || Accft.dwHighDateTime != 0) FileTime2utime(&Accft, &(z_ut->atime)); else z_ut->atime = z_ut->mtime; if (Creft.dwLowDateTime != 0 || Creft.dwHighDateTime != 0) FileTime2utime(&Creft, &(z_ut->ctime)); else z_ut->ctime = z_ut->mtime; } #endif FileTimeToLocalFileTime(&ft, &lft); FileTimeToDosDateTime(&lft, &dh, &dl); return(dh<<16) | dl; } else return 0L; }
static void test_GetTimeZoneInformation(void) { char std_name[32], dlt_name[32]; TIME_ZONE_INFORMATION tzinfo, tzinfo1; BOOL res; DWORD tz_id; SYSTEMTIME st, current, utc, local; FILETIME l_ft, s_ft; LONGLONG l_time, s_time; LONG diff; GetSystemTime(&st); s_time = system_time_to_minutes(&st); SetLastError(0xdeadbeef); res = SystemTimeToFileTime(&st, &s_ft); ok(res, "SystemTimeToFileTime error %u\n", GetLastError()); SetLastError(0xdeadbeef); res = FileTimeToLocalFileTime(&s_ft, &l_ft); ok(res, "FileTimeToLocalFileTime error %u\n", GetLastError()); SetLastError(0xdeadbeef); res = FileTimeToSystemTime(&l_ft, &local); ok(res, "FileTimeToSystemTime error %u\n", GetLastError()); l_time = system_time_to_minutes(&local); tz_id = GetTimeZoneInformation(&tzinfo); ok(tz_id != TIME_ZONE_ID_INVALID, "GetTimeZoneInformation failed\n"); trace("tz_id %u (%s)\n", tz_id, tz_id == TIME_ZONE_ID_DAYLIGHT ? "TIME_ZONE_ID_DAYLIGHT" : (tz_id == TIME_ZONE_ID_STANDARD ? "TIME_ZONE_ID_STANDARD" : (tz_id == TIME_ZONE_ID_UNKNOWN ? "TIME_ZONE_ID_UNKNOWN" : "TIME_ZONE_ID_INVALID"))); WideCharToMultiByte(CP_ACP, 0, tzinfo.StandardName, -1, std_name, sizeof(std_name), NULL, NULL); WideCharToMultiByte(CP_ACP, 0, tzinfo.DaylightName, -1, dlt_name, sizeof(dlt_name), NULL, NULL); trace("bias %d, %s - %s\n", tzinfo.Bias, std_name, dlt_name); trace("standard (d/m/y): %u/%02u/%04u day of week %u %u:%02u:%02u.%03u bias %d\n", tzinfo.StandardDate.wDay, tzinfo.StandardDate.wMonth, tzinfo.StandardDate.wYear, tzinfo.StandardDate.wDayOfWeek, tzinfo.StandardDate.wHour, tzinfo.StandardDate.wMinute, tzinfo.StandardDate.wSecond, tzinfo.StandardDate.wMilliseconds, tzinfo.StandardBias); trace("daylight (d/m/y): %u/%02u/%04u day of week %u %u:%02u:%02u.%03u bias %d\n", tzinfo.DaylightDate.wDay, tzinfo.DaylightDate.wMonth, tzinfo.DaylightDate.wYear, tzinfo.DaylightDate.wDayOfWeek, tzinfo.DaylightDate.wHour, tzinfo.DaylightDate.wMinute, tzinfo.DaylightDate.wSecond, tzinfo.DaylightDate.wMilliseconds, tzinfo.DaylightBias); diff = (LONG)(s_time - l_time); ok(diff == tzinfo.Bias + get_tz_bias(&tzinfo, tz_id), "system/local diff %d != tz bias %d\n", diff, tzinfo.Bias + get_tz_bias(&tzinfo, tz_id)); ok(SetEnvironmentVariableA("TZ","GMT0") != 0, "SetEnvironmentVariableA failed\n"); res = GetTimeZoneInformation(&tzinfo1); ok(res != TIME_ZONE_ID_INVALID, "GetTimeZoneInformation failed\n"); ok(((tzinfo.Bias == tzinfo1.Bias) && (tzinfo.StandardBias == tzinfo1.StandardBias) && (tzinfo.DaylightBias == tzinfo1.DaylightBias)), "Bias influenced by TZ variable\n"); ok(SetEnvironmentVariableA("TZ",NULL) != 0, "SetEnvironmentVariableA failed\n"); if (!pSystemTimeToTzSpecificLocalTime) { win_skip("SystemTimeToTzSpecificLocalTime not available\n"); return; } diff = get_tz_bias(&tzinfo, tz_id); utc = st; SetLastError(0xdeadbeef); res = pSystemTimeToTzSpecificLocalTime(&tzinfo, &utc, ¤t); if (!res && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED) { win_skip("SystemTimeToTzSpecificLocalTime is not implemented\n"); return; } ok(res, "SystemTimeToTzSpecificLocalTime error %u\n", GetLastError()); s_time = system_time_to_minutes(¤t); tzinfo.StandardBias -= 123; tzinfo.DaylightBias += 456; res = pSystemTimeToTzSpecificLocalTime(&tzinfo, &utc, &local); ok(res, "SystemTimeToTzSpecificLocalTime error %u\n", GetLastError()); l_time = system_time_to_minutes(&local); ok(l_time - s_time == diff - get_tz_bias(&tzinfo, tz_id), "got %d, expected %d\n", (LONG)(l_time - s_time), diff - get_tz_bias(&tzinfo, tz_id)); /* pretend that there is no transition dates */ tzinfo.DaylightDate.wDay = 0; tzinfo.DaylightDate.wMonth = 0; tzinfo.DaylightDate.wYear = 0; tzinfo.StandardDate.wDay = 0; tzinfo.StandardDate.wMonth = 0; tzinfo.StandardDate.wYear = 0; res = pSystemTimeToTzSpecificLocalTime(&tzinfo, &utc, &local); ok(res, "SystemTimeToTzSpecificLocalTime error %u\n", GetLastError()); l_time = system_time_to_minutes(&local); ok(l_time - s_time == diff, "got %d, expected %d\n", (LONG)(l_time - s_time), diff); /* test 23:01, 31st of December date */ memset(&tzinfo, 0, sizeof(tzinfo)); tzinfo.StandardDate.wMonth = 10; tzinfo.StandardDate.wDay = 5; tzinfo.StandardDate.wHour = 2; tzinfo.StandardDate.wMinute = 0; tzinfo.DaylightDate.wMonth = 4; tzinfo.DaylightDate.wDay = 1; tzinfo.DaylightDate.wHour = 2; tzinfo.Bias = 0; tzinfo.StandardBias = 0; tzinfo.DaylightBias = -60; utc.wYear = 2012; utc.wMonth = 12; utc.wDay = 31; utc.wHour = 23; utc.wMinute = 1; res = pSystemTimeToTzSpecificLocalTime(&tzinfo, &utc, &local); ok(res, "SystemTimeToTzSpecificLocalTime error %u\n", GetLastError()); ok(local.wYear==2012 && local.wMonth==12 && local.wDay==31 && local.wHour==23 && local.wMinute==1, "got (%d-%d-%d %02d:%02d), expected (2012-12-31 23:01)\n", local.wYear, local.wMonth, local.wDay, local.wHour, local.wMinute); }
struct tm * ACE_OS::localtime_r (const time_t *t, struct tm *res) { ACE_OS_TRACE ("ACE_OS::localtime_r"); #if defined (ACE_HAS_REENTRANT_FUNCTIONS) # if defined (DIGITAL_UNIX) ACE_OSCALL_RETURN (::_Plocaltime_r (t, res), struct tm *, 0); # else ACE_OSCALL_RETURN (::localtime_r (t, res), struct tm *, 0); # endif /* DIGITAL_UNIX */ #elif defined (ACE_HAS_TR24731_2005_CRT) ACE_SECURECRTCALL (localtime_s (res, t), struct tm *, 0, res); return res; #elif !defined (ACE_HAS_WINCE) ACE_OS_GUARD ACE_UNUSED_ARG (res); struct tm * res_ptr = 0; ACE_OSCALL (::localtime (t), struct tm *, 0, res_ptr); if (res_ptr == 0) return 0; else { *res = *res_ptr; return res; } #elif defined (ACE_HAS_WINCE) // This is really stupid, converting FILETIME to timeval back and // forth. It assumes FILETIME and DWORDLONG are the same structure // internally. TIME_ZONE_INFORMATION pTz; const unsigned short int __mon_yday[2][13] = { /* Normal years. */ { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }, /* Leap years. */ { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 } }; ULARGE_INTEGER _100ns; ::GetTimeZoneInformation (&pTz); _100ns.QuadPart = (DWORDLONG) *t * 10000 * 1000 + ACE_Time_Value::FILETIME_to_timval_skew; FILETIME file_time; file_time.dwLowDateTime = _100ns.LowPart; file_time.dwHighDateTime = _100ns.HighPart; FILETIME localtime; SYSTEMTIME systime; FileTimeToLocalFileTime (&file_time, &localtime); FileTimeToSystemTime (&localtime, &systime); res->tm_hour = systime.wHour; if(pTz.DaylightBias!=0) res->tm_isdst = 1; else res->tm_isdst = 1; int iLeap; iLeap = (res->tm_year % 4 == 0 && (res->tm_year% 100 != 0 || res->tm_year % 400 == 0)); // based on leap select which group to use res->tm_mday = systime.wDay; res->tm_min = systime.wMinute; res->tm_mon = systime.wMonth - 1; res->tm_sec = systime.wSecond; res->tm_wday = systime.wDayOfWeek; res->tm_yday = __mon_yday[iLeap][systime.wMonth] + systime.wDay; res->tm_year = systime.wYear;// this the correct year but bias the value to start at the 1900 res->tm_year = res->tm_year - 1900; return res; #else // @@ Same as ACE_OS::localtime (), you need to implement it // yourself. ACE_UNUSED_ARG (t); ACE_UNUSED_ARG (res); ACE_NOTSUP_RETURN (0); #endif /* ACE_HAS_REENTRANT_FUNCTIONS */ }
/**************************************************************************** * WCMD_HandleTildaModifiers * * Handle the ~ modifiers when expanding %0-9 or (%a-z/A-Z in for command) * %~xxxxxV (V=0-9 or A-Z, a-z) * Where xxxx is any combination of: * ~ - Removes quotes * f - Fully qualified path (assumes current dir if not drive\dir) * d - drive letter * p - path * n - filename * x - file extension * s - path with shortnames * a - attributes * t - date/time * z - size * $ENVVAR: - Searches ENVVAR for (contents of V) and expands to fully * qualified path * * To work out the length of the modifier: * * Note: In the case of %0-9 knowing the end of the modifier is easy, * but in a for loop, the for end WCHARacter may also be a modifier * eg. for %a in (c:\a.a) do echo XXX * where XXX = %~a (just ~) * %~aa (~ and attributes) * %~aaxa (~, attributes and extension) * BUT %~aax (~ and attributes followed by 'x') * * Hence search forwards until find an invalid modifier, and then * backwards until find for variable or 0-9 */ void WCMD_HandleTildaModifiers(WCHAR **start, BOOL atExecute) { #define NUMMODIFIERS 11 static const WCHAR validmodifiers[NUMMODIFIERS] = { '~', 'f', 'd', 'p', 'n', 'x', 's', 'a', 't', 'z', '$' }; WIN32_FILE_ATTRIBUTE_DATA fileInfo; WCHAR outputparam[MAX_PATH]; WCHAR finaloutput[MAX_PATH]; WCHAR fullfilename[MAX_PATH]; WCHAR thisoutput[MAX_PATH]; WCHAR *pos = *start+1; WCHAR *firstModifier = pos; WCHAR *lastModifier = NULL; int modifierLen = 0; BOOL finished = FALSE; int i = 0; BOOL exists = TRUE; BOOL skipFileParsing = FALSE; BOOL doneModifier = FALSE; /* Search forwards until find invalid character modifier */ while (!finished) { /* Work on the previous character */ if (lastModifier != NULL) { for (i=0; i<NUMMODIFIERS; i++) { if (validmodifiers[i] == *lastModifier) { /* Special case '$' to skip until : found */ if (*lastModifier == '$') { while (*pos != ':' && *pos) pos++; if (*pos == 0x00) return; /* Invalid syntax */ pos++; /* Skip ':' */ } break; } } if (i==NUMMODIFIERS) { finished = TRUE; } } /* Save this one away */ if (!finished) { lastModifier = pos; pos++; } } while (lastModifier > firstModifier) { WINE_TRACE("Looking backwards for parameter id: %s\n", wine_dbgstr_w(lastModifier)); if (!atExecute && context && (*lastModifier >= '0' && *lastModifier <= '9')) { /* Its a valid parameter identifier - OK */ break; } else { int foridx = FOR_VAR_IDX(*lastModifier); /* Its a valid parameter identifier - OK */ if ((foridx >= 0) && (forloopcontext.variable[foridx] != NULL)) break; /* Its not a valid parameter identifier - step backwards */ lastModifier--; } } if (lastModifier == firstModifier) return; /* Invalid syntax */ /* Extract the parameter to play with */ if (*lastModifier == '0') { strcpyW(outputparam, context->batchfileW); } else if ((*lastModifier >= '1' && *lastModifier <= '9')) { strcpyW(outputparam, WCMD_parameter (context -> command, *lastModifier-'0' + context -> shift_count[*lastModifier-'0'], NULL, FALSE, TRUE)); } else { int foridx = FOR_VAR_IDX(*lastModifier); strcpyW(outputparam, forloopcontext.variable[foridx]); } /* So now, firstModifier points to beginning of modifiers, lastModifier points to the variable just after the modifiers. Process modifiers in a specific order, remembering there could be duplicates */ modifierLen = lastModifier - firstModifier; finaloutput[0] = 0x00; /* 1. Handle '~' : Strip surrounding quotes */ if (outputparam[0]=='"' && memchrW(firstModifier, '~', modifierLen) != NULL) { int len = strlenW(outputparam); if (outputparam[len-1] == '"') { outputparam[len-1]=0x00; len = len - 1; } memmove(outputparam, &outputparam[1], (len * sizeof(WCHAR))-1); } /* 2. Handle the special case of a $ */ if (memchrW(firstModifier, '$', modifierLen) != NULL) { /* Special Case: Search envar specified in $[envvar] for outputparam Note both $ and : are guaranteed otherwise check above would fail */ WCHAR *begin = strchrW(firstModifier, '$') + 1; WCHAR *end = strchrW(firstModifier, ':'); WCHAR env[MAX_PATH]; WCHAR fullpath[MAX_PATH]; /* Extract the env var */ memcpy(env, begin, (end-begin) * sizeof(WCHAR)); env[(end-begin)] = 0x00; /* If env var not found, return empty string */ if ((GetEnvironmentVariableW(env, fullpath, MAX_PATH) == 0) || (SearchPathW(fullpath, outputparam, NULL, MAX_PATH, outputparam, NULL) == 0)) { finaloutput[0] = 0x00; outputparam[0] = 0x00; skipFileParsing = TRUE; } } /* After this, we need full information on the file, which is valid not to exist. */ if (!skipFileParsing) { if (GetFullPathNameW(outputparam, MAX_PATH, fullfilename, NULL) == 0) { exists = FALSE; fullfilename[0] = 0x00; } else { exists = GetFileAttributesExW(fullfilename, GetFileExInfoStandard, &fileInfo); } /* 2. Handle 'a' : Output attributes (File doesn't have to exist) */ if (memchrW(firstModifier, 'a', modifierLen) != NULL) { WCHAR defaults[] = {'-','-','-','-','-','-','-','-','-','\0'}; doneModifier = TRUE; if (exists) { strcpyW(thisoutput, defaults); if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) thisoutput[0]='d'; if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_READONLY) thisoutput[1]='r'; if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE) thisoutput[2]='a'; if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) thisoutput[3]='h'; if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) thisoutput[4]='s'; if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED) thisoutput[5]='c'; /* FIXME: What are 6 and 7? */ if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) thisoutput[8]='l'; strcatW(finaloutput, thisoutput); } } /* 3. Handle 't' : Date+time (File doesn't have to exist) */ if (memchrW(firstModifier, 't', modifierLen) != NULL) { SYSTEMTIME systime; int datelen; doneModifier = TRUE; if (exists) { if (finaloutput[0] != 0x00) strcatW(finaloutput, spaceW); /* Format the time */ FileTimeToSystemTime(&fileInfo.ftLastWriteTime, &systime); GetDateFormatW(LOCALE_USER_DEFAULT, DATE_SHORTDATE, &systime, NULL, thisoutput, MAX_PATH); strcatW(thisoutput, spaceW); datelen = strlenW(thisoutput); GetTimeFormatW(LOCALE_USER_DEFAULT, TIME_NOSECONDS, &systime, NULL, (thisoutput+datelen), MAX_PATH-datelen); strcatW(finaloutput, thisoutput); } } /* 4. Handle 'z' : File length (File doesn't have to exist) */ if (memchrW(firstModifier, 'z', modifierLen) != NULL) { /* FIXME: Output full 64 bit size (sprintf does not support I64 here) */ ULONG/*64*/ fullsize = /*(fileInfo.nFileSizeHigh << 32) +*/ fileInfo.nFileSizeLow; static const WCHAR fmt[] = {'%','u','\0'}; doneModifier = TRUE; if (exists) { if (finaloutput[0] != 0x00) strcatW(finaloutput, spaceW); wsprintfW(thisoutput, fmt, fullsize); strcatW(finaloutput, thisoutput); } } /* 4. Handle 's' : Use short paths (File doesn't have to exist) */ if (memchrW(firstModifier, 's', modifierLen) != NULL) { if (finaloutput[0] != 0x00) strcatW(finaloutput, spaceW); /* Don't flag as doneModifier - %~s on its own is processed later */ GetShortPathNameW(outputparam, outputparam, sizeof(outputparam)/sizeof(outputparam[0])); } /* 5. Handle 'f' : Fully qualified path (File doesn't have to exist) */ /* Note this overrides d,p,n,x */ if (memchrW(firstModifier, 'f', modifierLen) != NULL) { doneModifier = TRUE; if (finaloutput[0] != 0x00) strcatW(finaloutput, spaceW); strcatW(finaloutput, fullfilename); } else { WCHAR drive[10]; WCHAR dir[MAX_PATH]; WCHAR fname[MAX_PATH]; WCHAR ext[MAX_PATH]; BOOL doneFileModifier = FALSE; BOOL addSpace = (finaloutput[0] != 0x00); /* Split into components */ WCMD_splitpath(fullfilename, drive, dir, fname, ext); /* 5. Handle 'd' : Drive Letter */ if (memchrW(firstModifier, 'd', modifierLen) != NULL) { if (addSpace) { strcatW(finaloutput, spaceW); addSpace = FALSE; } strcatW(finaloutput, drive); doneModifier = TRUE; doneFileModifier = TRUE; } /* 6. Handle 'p' : Path */ if (memchrW(firstModifier, 'p', modifierLen) != NULL) { if (addSpace) { strcatW(finaloutput, spaceW); addSpace = FALSE; } strcatW(finaloutput, dir); doneModifier = TRUE; doneFileModifier = TRUE; } /* 7. Handle 'n' : Name */ if (memchrW(firstModifier, 'n', modifierLen) != NULL) { if (addSpace) { strcatW(finaloutput, spaceW); addSpace = FALSE; } strcatW(finaloutput, fname); doneModifier = TRUE; doneFileModifier = TRUE; } /* 8. Handle 'x' : Ext */ if (memchrW(firstModifier, 'x', modifierLen) != NULL) { if (addSpace) { strcatW(finaloutput, spaceW); addSpace = FALSE; } strcatW(finaloutput, ext); doneModifier = TRUE; doneFileModifier = TRUE; } /* If 's' but no other parameter, dump the whole thing */ if (!doneFileModifier && memchrW(firstModifier, 's', modifierLen) != NULL) { doneModifier = TRUE; if (finaloutput[0] != 0x00) strcatW(finaloutput, spaceW); strcatW(finaloutput, outputparam); } } } /* If No other modifier processed, just add in parameter */ if (!doneModifier) strcpyW(finaloutput, outputparam); /* Finish by inserting the replacement into the string */ WCMD_strsubstW(*start, lastModifier+1, finaloutput, -1); }
// Return the current time as an OsTime value void OsDateTimeWnt::getCurTime(OsTime& rTime) { #if WINCE typedef union { FILETIME ft; uint64_t int64; } g_FILETIME; uint64_t ticks ; uint64_t freq ; static bool sbInitialized = false ; static g_FILETIME sOsFileTime ; static uint64_t sLastTicks = 0 ; static uint64_t sResetTime = 0 ; QueryPerformanceCounter((LARGE_INTEGER*) &ticks) ; QueryPerformanceFrequency((LARGE_INTEGER*) &freq) ; if (!sbInitialized || sOsFileTime.int64 > sResetTime) { sbInitialized = true ; GetSystemTimeAsFileTime(&sOsFileTime.ft); sResetTime = -1 ; // sOsFileTime.int64 + (freq - 1) ; sLastTicks = ticks ; } else { uint64_t delta = ticks - sLastTicks ; sLastTicks = ticks ; sOsFileTime.int64 = sOsFileTime.int64 + (((uint64_t) 10000000) * (delta / freq)) + (((uint64_t) 10000000) * (delta % freq)) / freq ; SYSTEMTIME si ; FileTimeToSystemTime(&sOsFileTime.ft, &si) ; } OsTime curTime((long) ((sOsFileTime.int64 - ((uint64_t) 116444736000000000)) / ((uint64_t) 10000000)), (long) ((sOsFileTime.int64 / ((uint64_t) 10)) % ((uint64_t) 1000000))); rTime = curTime; #else typedef union { FILETIME ft; uint64_t int64; } g_FILETIME; static bool sbInitialized = false ; static g_FILETIME sOsFileTime ; static DWORD sLastSystemMSecs = 0 ; DWORD systemMSecs = timeGetTime(); if (!sbInitialized) { sbInitialized = true ; // Set the precision of timings got from timeGetTime. timeBeginPeriod(1); // Resample time, since we changed the precision. systemMSecs = timeGetTime(); FILETIME sft; GetSystemTimeAsFileTime(&sft); // Store in a temp and copy over to prevent data type misalignment issues. sOsFileTime.ft = sft; sLastSystemMSecs = systemMSecs ; } else { DWORD delta = systemMSecs - sLastSystemMSecs ; sLastSystemMSecs = systemMSecs; sOsFileTime.int64 = sOsFileTime.int64 + 10000 * delta; // convert delta msec to 100ns units SYSTEMTIME si ; FileTimeToSystemTime(&sOsFileTime.ft, &si) ; } OsTime curTime((long) ((sOsFileTime.int64 - ((uint64_t) WINDOWSTIME2UNIXTIME * 10000000)) / ((uint64_t) 10000000)), (long) ((sOsFileTime.int64 / ((uint64_t) 10)) % ((uint64_t) 1000000))); rTime = curTime; #endif }
void __gnat_localtime_tzoff (const time_t *timer, long *off) { union { FILETIME ft_time; unsigned long long ull_time; } utc_time, local_time; SYSTEMTIME utc_sys_time, local_sys_time; TIME_ZONE_INFORMATION tzi; BOOL status = 1; DWORD tzi_status; (*Lock_Task) (); #ifdef RTX tzi_status = GetTimeZoneInformation (&tzi); *off = tzi.Bias; if (tzi_status == TIME_ZONE_ID_STANDARD) /* The system is operating in the range covered by the StandardDate member. */ *off = *off + tzi.StandardBias; else if (tzi_status == TIME_ZONE_ID_DAYLIGHT) /* The system is operating in the range covered by the DaylightDate member. */ *off = *off + tzi.DaylightBias; *off = *off * -60; #else /* First convert unix time_t structure to windows FILETIME format. */ utc_time.ull_time = ((unsigned long long) *timer + w32_epoch_offset) * 10000000ULL; tzi_status = GetTimeZoneInformation (&tzi); /* If GetTimeZoneInformation does not return a value between 0 and 2 then it means that we were not able to retrieve timezone informations. Note that we cannot use here FileTimeToLocalFileTime as Windows will use in always in this case the current timezone setting. As suggested on MSDN we use the following three system calls to get the right information. Note also that starting with Windows Vista new functions are provided to get timezone settings that depend on the year. We cannot use them as we still support Windows XP and Windows 2003. */ status = (tzi_status >= 0 && tzi_status <= 2) && FileTimeToSystemTime (&utc_time.ft_time, &utc_sys_time) && SystemTimeToTzSpecificLocalTime (&tzi, &utc_sys_time, &local_sys_time) && SystemTimeToFileTime (&local_sys_time, &local_time.ft_time); if (!status) /* An error occurs so return invalid_tzoff. */ *off = __gnat_invalid_tzoff; else if (local_time.ull_time > utc_time.ull_time) *off = (long) ((local_time.ull_time - utc_time.ull_time) / 10000000ULL); else *off = - (long) ((utc_time.ull_time - local_time.ull_time) / 10000000ULL); #endif (*Unlock_Task) (); }
DWORD WINAPI ExeclThreadPROC(LPVOID lpParameter) { char path[260]; strcpy(path,(char *)lpParameter); unsigned short fontsize=256; workbook w; worksheet **sheet; long sheetTotal=0; long long *filenum; xf_t *xf = NULL; int i=0; long j,k,m; SYSTEMTIME systime; FILETIME temptime; ULARGE_INTEGER uli; int ret; char str[2048]; wchar_t wbuff[2048]; list<struct HDD_ST> MyhddList; SQLDB.Hdd_SetNonsert(); CDLGHdd::Add27HDDid(); MyhddList.clear(); SQLDB.Hdd_Read(MyhddList); if(MyhddList.size()<=0) { MessageBox(NULL,"没有硬盘","导出EXECL",MB_OK); return 0; } //导出硬盘 sheetTotal=1; sheet=(worksheet **)calloc(sheetTotal,sizeof(worksheet *)); filenum=(long long *)calloc(MyhddList.size(),sizeof(long long)); xf= w.xformat(); //xf->SetLocked(true) ;无效代码 sheet[0]=w.sheet(L"硬盘目录"); sheet[0]->colwidth(0,10*fontsize); sheet[0]->label(0,0,L"磁盘序列号"); sheet[0]->colwidth(1,10*fontsize); sheet[0]->label(0,1,L"分区"); sheet[0]->colwidth(2,30*fontsize); sheet[0]->label(0,2,L"标签"); sheet[0]->colwidth(3,20*fontsize); sheet[0]->label(0,3,L"总空间"); sheet[0]->colwidth(4,20*fontsize); sheet[0]->label(0,4,L"剩余空间"); list<struct HDD_ST>::iterator beglist; for(i=1,beglist=MyhddList.begin();beglist!=MyhddList.end();i++,beglist++) { MultiByteToWideChar(CP_ACP, 0, beglist->serno, -1, wbuff, 2048); sheet[0]->label(i,0,wbuff); MultiByteToWideChar(CP_ACP, 0, beglist->area, -1, wbuff, 2048); sheet[0]->label(i,1,wbuff); MultiByteToWideChar(CP_ACP, 0, beglist->mark, -1, wbuff, 2048); sheet[0]->label(i,2,wbuff); sprintf(str,"%I64u",beglist->TotalBytes); MultiByteToWideChar(CP_ACP, 0, str, -1, wbuff, 2048); sheet[0]->label(i,3,wbuff); sprintf(str,"%I64u",beglist->FreeBytes); MultiByteToWideChar(CP_ACP, 0, str, -1, wbuff, 2048); sheet[0]->label(i,4,wbuff); filenum[i-1]=SQLDB.File_NumberForHDD(beglist->hdd_nid); sheetTotal += (long)(filenum[i-1]/10000) +1; } //导出文件 sheet=(worksheet **)realloc(sheet,sheetTotal*sizeof(worksheet *)); outputList.clear(); list<struct FILE_VIEW_ST>::iterator filebeglist; k=1; for(i=0,beglist=MyhddList.begin();beglist!=MyhddList.end();i++,beglist++) { if(filenum[i] <= 0) continue; for(j=0;j< (long)(filenum[i]/10000) +1;j++) { sprintf(str,"%s %s %d",beglist->serno,beglist->mark,j); MultiByteToWideChar(CP_ACP, 0, str, -1, wbuff, 2048); sheet[k]=w.sheet(wbuff); sheet[k]->colwidth(0,10*fontsize); sheet[k]->label(0,0,L"序号"); sheet[k]->colwidth(1,150*fontsize); sheet[k]->label(0,1,L"文件路径"); sheet[k]->colwidth(2,5*fontsize); sheet[k]->label(0,2,L"类型"); sheet[k]->colwidth(3,5*fontsize); sheet[k]->label(0,3,L"后缀"); sheet[k]->colwidth(4,20*fontsize); sheet[k]->label(0,4,L"创建时间"); sheet[k]->colwidth(5,20*fontsize); sheet[k]->label(0,5,L"修改时间"); sheet[k]->colwidth(6,15*fontsize); sheet[k]->label(0,6,L"文件大小"); sheet[k]->colwidth(7,10*fontsize); sheet[k]->label(0,7,L"分辨率"); sheet[k]->colwidth(8,5*fontsize); sheet[k]->label(0,8,L"3D"); outputList.clear(); SQLDB.File_ReadHddPage(outputList,beglist->hdd_nid,true,j*10000,10000); if(outputList.size() <= 0) continue; for(m=1,filebeglist=outputList.begin();filebeglist!=outputList.end();m++,filebeglist++) { sprintf(str,"%I64u",filebeglist->file_data.file_nid); MultiByteToWideChar(CP_ACP, 0, str, -1, wbuff, 2048); sheet[k]->label(m,0,wbuff); sprintf(str,"%s%s",filebeglist->file_data.path,filebeglist->file_data.name); MultiByteToWideChar(CP_ACP, 0, str, -1, wbuff, 2048); sheet[k]->label(m,1,wbuff); sprintf(str,"%s",MainType2Str(filebeglist->file_data.maintype)); MultiByteToWideChar(CP_ACP, 0, str, -1, wbuff, 2048); sheet[k]->label(m,2,wbuff); MultiByteToWideChar(CP_ACP, 0, filebeglist->file_data.type, -1, wbuff, 2048); sheet[k]->label(m,3,wbuff); if(filebeglist->file_data.CreationTime) { uli.QuadPart=filebeglist->file_data.CreationTime; temptime.dwLowDateTime=uli.LowPart; temptime.dwHighDateTime=uli.HighPart; FileTimeToSystemTime(&temptime,&systime); sprintf(str,"%04d-%02d-%02d %02d:%02d:%02d", systime.wYear,systime.wMonth,systime.wDay, systime.wHour,systime.wMinute,systime.wSecond); MultiByteToWideChar(CP_ACP, 0, str, -1, wbuff, 2048); sheet[k]->label(m,4,wbuff); } if(filebeglist->file_data.LastWriteTime) { uli.QuadPart=filebeglist->file_data.LastWriteTime; temptime.dwLowDateTime=uli.LowPart; temptime.dwHighDateTime=uli.HighPart; FileTimeToSystemTime(&temptime,&systime); sprintf(str,"%04d-%02d-%02d %02d:%02d:%02d", systime.wYear,systime.wMonth,systime.wDay, systime.wHour,systime.wMinute,systime.wSecond); MultiByteToWideChar(CP_ACP, 0, str, -1, wbuff, 2048); sheet[k]->label(m,5,wbuff); } sprintf(str,"%I64u",filebeglist->file_data.filesize); MultiByteToWideChar(CP_ACP, 0, str, -1, wbuff, 2048); sheet[k]->label(m,6,wbuff); MultiByteToWideChar(CP_ACP, 0, filebeglist->file_data.zidian_fenbianlv , -1, wbuff, 2048); sheet[k]->label(m,7,wbuff); MultiByteToWideChar(CP_ACP, 0, filebeglist->file_data.zidian_3d, -1, wbuff, 2048); sheet[k]->label(m,8,wbuff); } k++; } } MyhddList.clear(); outputList.clear(); MultiByteToWideChar(CP_ACP, 0, path, -1, wbuff, 2048); ret = w.Dump(wbuff); free(filenum); free(sheet); pZogvmDlg->GetDlgItem(IDC_BUTTON_OUTPUTEXECL)->EnableWindow(TRUE); if (ret != 0) { MessageBox(NULL,"导出失败","导出EXECL",MB_OK); return 0; } MessageBox(NULL,"导出完成","导出EXECL",MB_OK); return 0; }
refalrts::FnResult CoreP_MFileSystemP_GetFileAttributes(refalrts::Iter arg_begin, refalrts::Iter arg_end) { refalrts::Iter bb_0 = arg_begin; refalrts::Iter be_0 = arg_end; refalrts::move_left( bb_0, be_0 ); refalrts::move_left( bb_0, be_0 ); refalrts::move_right( bb_0, be_0 ); refalrts::Iter eFileName_b_1; refalrts::Iter eFileName_e_1; // e.FileName eFileName_b_1 = bb_0; refalrts::use( eFileName_b_1 ); eFileName_e_1 = be_0; refalrts::use( eFileName_e_1 ); std::vector<char> filename; refalrts::FnResult res = string_from_seq(filename, eFileName_b_1, eFileName_e_1); if( res == refalrts::cRecognitionImpossible ) { return refalrts::cRecognitionImpossible; } WIN32_FIND_DATA find_file_data; HANDLE hFind = FindFirstFile( & filename[0], & find_file_data ); if( hFind == INVALID_HANDLE_VALUE ) { refalrts::reset_allocator(); refalrts::Iter res = arg_begin; refalrts::Iter nSF = 0; if( ! refalrts::alloc_ident( nSF, & FailsL_<int>::name ) ) return refalrts::cNoMemory; res = refalrts::splice_elem( res, nSF ); refalrts::use( res ); refalrts::splice_to_freelist( arg_begin, arg_end ); return refalrts::cSuccess; } else { std::string full_name( find_file_data.cFileName ); if( ! get_full_name( full_name ) ) { refalrts::reset_allocator(); refalrts::Iter res = arg_begin; refalrts::Iter nSF = 0; if( ! refalrts::alloc_ident( nSF, & FailsL_<int>::name ) ) return refalrts::cNoMemory; res = refalrts::splice_elem( res, nSF ); refalrts::use( res ); refalrts::splice_to_freelist( arg_begin, arg_end ); return refalrts::cSuccess; } else { bool is_directory = ((find_file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0); SYSTEMTIME file_system_time = { 0 }; FileTimeToSystemTime( & find_file_data.ftLastWriteTime, & file_system_time ); refalrts::reset_allocator(); refalrts::Iter res = arg_begin; refalrts::Iter nSF = 0; if( ! refalrts::alloc_ident( nSF, & SuccessL_<int>::name ) ) return refalrts::cNoMemory; refalrts::Iter n0 = 0; if( ! refalrts::alloc_open_bracket( n0 ) ) return refalrts::cNoMemory; refalrts::Iter n1 = 0; if( ! refalrts::alloc_ident( n1, & DateTimeL_<int>::name ) ) return refalrts::cNoMemory; refalrts::Iter n2 = 0; if( ! refalrts::alloc_number( n2, file_system_time.wYear ) ) return refalrts::cNoMemory; refalrts::Iter n3 = 0; if( ! refalrts::alloc_number( n3, file_system_time.wMonth ) ) return refalrts::cNoMemory; refalrts::Iter n4 = 0; if( ! refalrts::alloc_number( n4, file_system_time.wDay ) ) return refalrts::cNoMemory; refalrts::Iter n5 = 0; if( ! refalrts::alloc_number( n5, file_system_time.wHour ) ) return refalrts::cNoMemory; refalrts::Iter n6 = 0; if( ! refalrts::alloc_number( n6, file_system_time.wMinute ) ) return refalrts::cNoMemory; refalrts::Iter n7 = 0; if( ! refalrts::alloc_number( n7, file_system_time.wSecond ) ) return refalrts::cNoMemory; refalrts::Iter n8 = 0; if( ! refalrts::alloc_number( n8, file_system_time.wMilliseconds ) ) return refalrts::cNoMemory; refalrts::Iter n9 = 0; if( ! refalrts::alloc_close_bracket( n9 ) ) return refalrts::cNoMemory; refalrts::Iter n10 = 0; if( ! refalrts::alloc_open_bracket( n10 ) ) return refalrts::cNoMemory; refalrts::Iter n11 = 0; if( ! refalrts::alloc_ident( n11, & SizeL_<int>::name ) ) return refalrts::cNoMemory; refalrts::Iter n12 = 0; if( is_directory ) { if( ! refalrts::alloc_ident( n12, & DirL_<int>::name ) ) return refalrts::cNoMemory; } else { if( ! refalrts::alloc_number( n12, 1000UL ) ) return refalrts::cNoMemory; } refalrts::Iter n14 = 0; if( ! refalrts::alloc_close_bracket( n14 ) ) return refalrts::cNoMemory; refalrts::Iter n15 = 0; if( ! refalrts::alloc_open_bracket( n15 ) ) return refalrts::cNoMemory; refalrts::Iter n16 = 0; if( ! refalrts::alloc_ident( n16, & LongNameL_<int>::name ) ) return refalrts::cNoMemory; refalrts::Iter fullname_b = 0; refalrts::Iter fullname_e = 0; bool name_allocated = refalrts::alloc_string( fullname_b, fullname_e, full_name.c_str() ); if( ! name_allocated ) return refalrts::cNoMemory; refalrts::Iter n26 = 0; if( ! refalrts::alloc_close_bracket( n26 ) ) return refalrts::cNoMemory; refalrts::link_brackets( n15, n26 ); res = refalrts::splice_elem( res, n26 ); res = refalrts::splice_evar( res, fullname_b, fullname_e ); res = refalrts::splice_elem( res, n16 ); res = refalrts::splice_elem( res, n15 ); refalrts::link_brackets( n10, n14 ); res = refalrts::splice_elem( res, n14 ); res = refalrts::splice_elem( res, n12 ); res = refalrts::splice_elem( res, n11 ); res = refalrts::splice_elem( res, n10 ); refalrts::link_brackets( n0, n9 ); res = refalrts::splice_elem( res, n9 ); res = refalrts::splice_elem( res, n8 ); res = refalrts::splice_elem( res, n7 ); res = refalrts::splice_elem( res, n6 ); res = refalrts::splice_elem( res, n5 ); res = refalrts::splice_elem( res, n4 ); res = refalrts::splice_elem( res, n3 ); res = refalrts::splice_elem( res, n2 ); res = refalrts::splice_elem( res, n1 ); res = refalrts::splice_elem( res, n0 ); res = refalrts::splice_elem( res, nSF ); refalrts::use( res ); refalrts::splice_to_freelist( arg_begin, arg_end ); return refalrts::cSuccess; } } }
void CZogvmDlg::DisplayerList() { m_list.DeleteAllItems(); WinfileviewList.clear(); if(0==ListTotal) { GetDlgItem(IDC_STATIC_INFO)->SetWindowText("共0条 1/1页"); InvalidateRect(printf_Rect, TRUE); return ; } unsigned long int si,ei; si=ListNow+1; if((ListNow+PAGE_MAX_NUM) < ListTotal) ei=ListNow+PAGE_MAX_NUM ; else ei=ListTotal; switch(ModeFlag) { case MODE_DOUBLE: SQLDB.File_ReadDouble(WinfileviewList,si-1,ei-(si-1)); break; case MODE_FIND: if(m_sreach.IsEmpty()) SQLDB.File_Read(SQLstr,WinfileviewList,si-1,ei-(si-1)); else SQLDB.File_ReadForSearch(SQLstr,m_sreach.GetBuffer(0),WinfileviewList,si-1,ei-(si-1)); break; case MODE_TRASH: SQLDB.File_ReadTrash(WinfileviewList,si-1,ei-(si-1)); break; default:return ; } if(WinfileviewList.size()<=0) return ; list<struct FILE_VIEW_ST>::iterator beglist; char str[128]; int i=0; SYSTEMTIME systime; FILETIME temptime; ULARGE_INTEGER uli; for(beglist=WinfileviewList.begin();beglist!=WinfileviewList.end();beglist++) { //带复选框 LVS_EX_CHECKBOXES if(MAINTYPE_OTHER == beglist->file_data.maintype ) { m_list.InsertItem( i,beglist->hdd_data.serno,5); } else if( MAINTYPE_SUB == beglist->file_data.maintype) { m_list.InsertItem( i,beglist->hdd_data.serno,4); } else if(MAINTYPE_VIDEO == beglist->file_data.maintype ) { m_list.InsertItem( i,beglist->hdd_data.serno,2); } else if(MAINTYPE_MUSIC == beglist->file_data.maintype ) { m_list.InsertItem( i,beglist->hdd_data.serno,3); } m_list.SetItemText(i,1,beglist->hdd_data.mark); m_list.SetItemText(i,2,beglist->hdd_data.area); sprintf(str,"%I64u",beglist->file_data.file_nid); m_list.SetItemText(i,3,str); m_list.SetItemText(i,4,beglist->file_data.path); m_list.SetItemText(i,5,beglist->file_data.name); m_list.SetItemText(i,6, MainType2Str(beglist->file_data.maintype)); m_list.SetItemText(i,7,beglist->file_data.type); if(beglist->file_data.CreationTime) { uli.QuadPart=beglist->file_data.CreationTime; temptime.dwLowDateTime=uli.LowPart; temptime.dwHighDateTime=uli.HighPart; FileTimeToSystemTime(&temptime,&systime); sprintf(str,"%04d-%02d-%02d %02d:%02d:%02d", systime.wYear,systime.wMonth,systime.wDay, systime.wHour,systime.wMinute,systime.wSecond); m_list.SetItemText(i,8,str); } if(beglist->file_data.LastWriteTime) { uli.QuadPart=beglist->file_data.LastWriteTime; temptime.dwLowDateTime=uli.LowPart; temptime.dwHighDateTime=uli.HighPart; FileTimeToSystemTime(&temptime,&systime); sprintf(str,"%04d-%02d-%02d %02d:%02d:%02d", systime.wYear,systime.wMonth,systime.wDay, systime.wHour,systime.wMinute,systime.wSecond); m_list.SetItemText(i,9,str); } //sprintf(str,"%I64u",); DisplaySize(beglist->file_data.filesize,str); m_list.SetItemText(i,10,str); if(beglist->file_data.resolutionW && beglist->file_data.resolutionH) { sprintf(str,"%d*%d",beglist->file_data.resolutionW,beglist->file_data.resolutionH); m_list.SetItemText(i,11,str); } else m_list.SetItemText(i,11,""); if(beglist->file_data.filetime) { sprintf(str,"%d:%02d:%02d", beglist->file_data.filetime / 3600, (beglist->file_data.filetime % 3600) / 60, beglist->file_data.filetime % 60); m_list.SetItemText(i,12,str); } else m_list.SetItemText(i,12,""); if(beglist->hdd_data.insertflag) { m_list.SetItemText(i,13,"接入"); m_list.SetItem(i, 13, LVIF_IMAGE, NULL, 0, 0, 0, 0); } else { m_list.SetItemText(i,13,"脱机"); m_list.SetItem(i, 13, LVIF_IMAGE, NULL, 1, 0, 0, 0); } /* //名称 LV_ITEM lvitem; memset ((char *) &lvitem, 0, sizeof (LV_ITEM)); lvitem.mask = LVIF_TEXT | LVIF_IMAGE | LVIF_STATE; lvitem.iItem = i; lvitem.iSubItem = 12; lvitem.stateMask = 0; lvitem.iImage =1; //显示不同的图标时,可以把一个int 变量赋给这个属性值 lvitem.pszText = "a"; m_list.SetItem (&lvitem); m_list.SetItem(i, 12, LVIF_IMAGE, NULL, 0, 0, 0, 0); */ m_list.SetItemText(i,14,beglist->file_data.zidian_3d); m_list.SetItemText(i,15,beglist->file_data.zidian_huazhi); m_list.SetItemText(i,16,beglist->file_data.zidian_fenbianlv); m_list.SetItemText(i,17,beglist->file_data.zidian_yazhi); m_list.SetItemText(i,18,beglist->file_data.zidian_year); m_list.SetItemText(i,19,beglist->file_data.md5); if(MODE_DOUBLE == ModeFlag) { sprintf(str,"%I64u",beglist->file_data.double_nid); m_list.SetItemText(i,20,str); } else m_list.SetItemText(i,20,"0"); i++; } if(ListTotal%PAGE_MAX_NUM) { sprintf(str,"共%d条 %d/%d页 每页%d条", ListTotal, ListNow/PAGE_MAX_NUM+1,ListTotal/PAGE_MAX_NUM+1,PAGE_MAX_NUM); } else { sprintf(str,"共%d条 %d/%d页 每页%d条", ListTotal, ListNow/PAGE_MAX_NUM+1,ListTotal/PAGE_MAX_NUM,PAGE_MAX_NUM); } GetDlgItem(IDC_STATIC_INFO)->SetWindowText(str); InvalidateRect(printf_Rect, TRUE); m_c_delete_trash=FALSE; UpdateData(FALSE); }
std::string GpuCapabilitiesWindows::getFileDate(std::string filename) { LDEBUG("Retrieving file date (last write date) of system file '" << filename << "' ..."); // add system path to filename LPTSTR lpBuffer = static_cast<LPTSTR>(new char[1024]); int len = GetSystemDirectory( lpBuffer, 1024 ); if (len == 0) { LWARNING("Failed to detect system directory."); delete lpBuffer; return ""; } std::string systemPath = std::string( static_cast<char*>(lpBuffer), len); delete lpBuffer; systemPath.append("\\"); systemPath.append(filename); filename = systemPath; // create file handle for reading attributes LDEBUG("Acquiring handle for file '" << filename << "' ..."); HANDLE filehandle = CreateFile( filename.c_str(), FILE_READ_ATTRIBUTES, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0 ); if ( filehandle == INVALID_HANDLE_VALUE ) { LDEBUG("Failed to acquire handle for file '" << filename << "'."); return ""; } // read file information LDEBUG("Reading file information ..."); LPBY_HANDLE_FILE_INFORMATION fileInformation = static_cast<LPBY_HANDLE_FILE_INFORMATION>(new BY_HANDLE_FILE_INFORMATION); BOOL success = GetFileInformationByHandle(filehandle, fileInformation); if (success == 0) { LDEBUG("Failed to read file information of file '" << filename << "'."); delete fileInformation; return ""; } // convert file time to local time SYSTEMTIME stUTC, stLocal; DWORD dwRet; FileTimeToSystemTime(&(fileInformation->ftLastWriteTime), &stUTC); SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal); // build a string showing the date LPTSTR lpszString = static_cast<LPTSTR>(new char[1024]); dwRet = StringCchPrintf(lpszString, 1024, TEXT("%d-%02d-%02d"), stLocal.wYear, stLocal.wMonth, stLocal.wDay); std::string result = std::string( static_cast<char*>(lpszString)); delete lpszString; LDEBUG("Reading file date successful."); return result; }
void LoadDIBFromFile(HBITMAP * hBitmap, LPTSTR name, LPSYSTEMTIME time, int *size, int *hRes, int *vRes) { BITMAPFILEHEADER bfh; BITMAPINFO *bi; PVOID pvBits; DWORD dwBytesRead; HANDLE hFile; if (!hBitmap) { ShowFileLoadError(name); return; } hFile = CreateFile(name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL); if (hFile == INVALID_HANDLE_VALUE) { ShowFileLoadError(name); return; } /* read header and check for 'BM' magic */ ReadFile(hFile, &bfh, sizeof(BITMAPFILEHEADER), &dwBytesRead, NULL); if (bfh.bfType != 0x4d42) { CloseHandle(hFile); ShowFileLoadError(name); return; } if (time) { FILETIME ft; GetFileTime(hFile, NULL, NULL, &ft); FileTimeToSystemTime(&ft, time); } if (size) *size = GetFileSize(hFile, NULL); bi = HeapAlloc(GetProcessHeap(), 0, bfh.bfOffBits - sizeof(BITMAPFILEHEADER)); if (!bi) { CloseHandle(hFile); ShowFileLoadError(name); return; } ReadFile(hFile, bi, bfh.bfOffBits - sizeof(BITMAPFILEHEADER), &dwBytesRead, NULL); *hBitmap = CreateDIBSection(NULL, bi, DIB_RGB_COLORS, &pvBits, NULL, 0); ReadFile(hFile, pvBits, bfh.bfSize - bfh.bfOffBits, &dwBytesRead, NULL); if (hRes) *hRes = (*bi).bmiHeader.biXPelsPerMeter; if (vRes) *vRes = (*bi).bmiHeader.biYPelsPerMeter; CloseHandle(hFile); HeapFree(GetProcessHeap(), 0, bi); }
/** * Returns the amount of CPU time used by the current process, * in second , or -1.0 if an error occurred. */ double getCPUTime() { #if defined(_WIN32) /* Windows -------------------------------------------------- */ FILETIME createTime; FILETIME exitTime; FILETIME kernelTime; FILETIME userTime; if (GetProcessTimes(GetCurrentProcess(),&createTime, &exitTime, &kernelTime, &userTime) != -1) { SYSTEMTIME userSystemTime; if (FileTimeToSystemTime(&userTime, &userSystemTime) != -1) return (double)userSystemTime.wHour * 3600.0 + (double)userSystemTime.wMinute * 60.0 + (double)userSystemTime.wSecond + (double)userSystemTime.wMilliseconds / 1000.0; } #elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__)) /* AIX, BSD, Cygwin, HP-UX, Linux, OSX, and Solaris --------- */ #if defined(_POSIX_TIMERS) && (_POSIX_TIMERS > 0) /* Prefer high-res POSIX timers, when available. */ { clockid_t id; struct timespec ts; #if _POSIX_CPUTIME > 0 /* Clock ids vary by OS. Query the id, if possible. */ if (clock_getcpuclockid(0, &id) == -1) #endif #if defined(CLOCK_PROCESS_CPUTIME_ID) /* Use known clock id for AIX, Linux, or Solaris. */ id = CLOCK_PROCESS_CPUTIME_ID; #elif defined(CLOCK_VIRTUAL) /* Use known clock id for BSD or HP-UX. */ id = CLOCK_VIRTUAL; #else id = (clockid_t)-1; #endif if (id != (clockid_t)-1 && clock_gettime(id, &ts) != -1) return (double)ts.tv_sec + (double)ts.tv_nsec / 1000000000.0; } #endif #if defined(RUSAGE_SELF) { struct rusage rusage; if (getrusage(RUSAGE_SELF, &rusage) != -1) return (double)rusage.ru_utime.tv_sec + (double)rusage.ru_utime.tv_usec / 1000000.0; } #endif #if defined(_SC_CLK_TCK) { const double ticks = (double)sysconf(_SC_CLK_TCK); struct tms tms; if (times(&tms) != (clock_t)-1) return (double)tms.tms_utime / ticks; } #endif #if defined(CLOCKS_PER_SEC) { clock_t cl = clock(); if (cl != (clock_t)-1) return (double)cl / (double)CLOCKS_PER_SEC; } #endif #endif return -1; /* Failed. */ }
BOOL LASreaderQFIT::open(const char* file_name) { if (file_name == 0) { fprintf(stderr,"ERROR: fine name pointer is zero\n"); return FALSE; } // open file file = fopen(file_name, "rb"); if (file == 0) { fprintf(stderr, "ERROR: cannot open file '%s'\n", file_name); return FALSE; } // create input stream ByteStreamIn* in; if (IS_LITTLE_ENDIAN()) in = new ByteStreamInFileLE(file); else in = new ByteStreamInFileBE(file); // clean the header header.clean(); // set projection LASvlr_key_entry geo_keys[4]; // projected coordinates geo_keys[0].key_id = 1024; // GTModelTypeGeoKey geo_keys[0].tiff_tag_location = 0; geo_keys[0].count = 1; geo_keys[0].value_offset = 2; // ModelTypeGeographic // ellipsoid used with latitude/longitude coordinates geo_keys[1].key_id = 2048; // GeographicTypeGeoKey geo_keys[1].tiff_tag_location = 0; geo_keys[1].count = 1; geo_keys[1].value_offset = 4326; // GCS_WGS_84 // vertical units geo_keys[2].key_id = 4099; // VerticalUnitsGeoKey geo_keys[2].tiff_tag_location = 0; geo_keys[2].count = 1; geo_keys[2].value_offset = 9001; // meter // vertical datum geo_keys[3].key_id = 4096; // VerticalCSTypeGeoKey geo_keys[3].tiff_tag_location = 0; geo_keys[3].count = 1; geo_keys[3].value_offset = 5030; // VertCS_WGS_84_ellipsoid header.set_geo_keys(4, geo_keys); // maybe set creation date #ifdef _WIN32 WIN32_FILE_ATTRIBUTE_DATA attr; SYSTEMTIME creation; GetFileAttributesEx(file_name, GetFileExInfoStandard, &attr); FileTimeToSystemTime(&attr.ftCreationTime, &creation); int startday[13] = {-1, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334}; header.file_creation_day = startday[creation.wMonth] + creation.wDay; header.file_creation_year = creation.wYear; // leap year handling if ((((creation.wYear)%4) == 0) && (creation.wMonth > 2)) header.file_creation_day++; #else header.file_creation_day = 333; header.file_creation_year = 2011; #endif return open(in); }