Exemplo n.º 1
0
 inline std::wstring wcs_format_time_l(wchar_t const *format,SYSTEMTIME const *tm,winlocale const &l)
 {
     int len = GetTimeFormatW(l.lcid,0,tm,format,0,0);
     std::vector<wchar_t> buf(len+1);
     GetTimeFormatW(l.lcid,0,tm,format,&buf.front(),len);
     return &buf.front(); 
 }
Exemplo n.º 2
0
static
VOID
PrintDateTime(DWORD dwSeconds)
{
    LARGE_INTEGER Time;
    FILETIME FileTime;
    SYSTEMTIME SystemTime;
    WCHAR DateBuffer[80];
    WCHAR TimeBuffer[80];

    RtlSecondsSince1970ToTime(dwSeconds, &Time);
    FileTime.dwLowDateTime = Time.u.LowPart;
    FileTime.dwHighDateTime = Time.u.HighPart;
    FileTimeToLocalFileTime(&FileTime, &FileTime);
    FileTimeToSystemTime(&FileTime, &SystemTime);

    GetDateFormatW(LOCALE_USER_DEFAULT,
                   DATE_SHORTDATE,
                   &SystemTime,
                   NULL,
                   DateBuffer,
                   80);

    GetTimeFormatW(LOCALE_USER_DEFAULT,
                   TIME_NOSECONDS,
                   &SystemTime,
                   NULL,
                   TimeBuffer,
                   80);

    ConPrintf(StdOut, L"%s %s", DateBuffer, TimeBuffer);
}
Exemplo n.º 3
0
/*------------------------------------------------
  GetTimeFormat() for 95/NT
--------------------------------------------------*/
int MyGetTimeFormatW(int ilang, int codepage,
	DWORD dwFlags, CONST SYSTEMTIME *t,
	wchar_t* fmt, wchar_t* dst, int n)
{
	int r;
	LCID Locale;
	
	*dst = 0;
	Locale = MAKELCID((WORD)ilang, SORT_DEFAULT);
	if(GetVersion() & 0x80000000) // 95
	{
		char buf[80], afmt[40];
		if(fmt)
			WideCharToMultiByte(codepage, 0, fmt, -1,
				afmt, 39, NULL, NULL);
		r = GetTimeFormatA(Locale, dwFlags, t, fmt ? afmt : NULL, buf, 79);
		if(r)
			r = MultiByteToWideChar(codepage, 0, buf, -1, dst, n);
	}
	else  // NT
	{
		r = GetTimeFormatW(Locale, dwFlags, t, fmt, dst, n);
	}
	return r;
}
Exemplo n.º 4
0
static VOID
OnInitSecurityDlg(HWND hwnd,
                  PGINA_CONTEXT pgContext)
{
    WCHAR Buffer1[256];
    WCHAR Buffer2[256];
    WCHAR Buffer3[256];
    WCHAR Buffer4[512];

    LoadStringW(pgContext->hDllInstance, IDS_LOGONMSG, Buffer1, 256);

    wsprintfW(Buffer2, L"%s\\%s", pgContext->Domain, pgContext->UserName);
    wsprintfW(Buffer4, Buffer1, Buffer2);

    SetDlgItemTextW(hwnd, IDC_LOGONMSG, Buffer4);

    LoadStringW(pgContext->hDllInstance, IDS_LOGONDATE, Buffer1, 256);

    GetDateFormatW(LOCALE_USER_DEFAULT, DATE_SHORTDATE,
                   (SYSTEMTIME*)&pgContext->LogonTime, NULL, Buffer2, 256);

    GetTimeFormatW(LOCALE_USER_DEFAULT, 0,
                   (SYSTEMTIME*)&pgContext->LogonTime, NULL, Buffer3, 256);

    wsprintfW(Buffer4, Buffer1, Buffer2, Buffer3);

    SetDlgItemTextW(hwnd, IDC_LOGONDATE, Buffer4);

    if (pgContext->bAutoAdminLogon == TRUE)
        EnableWindow(GetDlgItem(hwnd, IDC_LOGOFF), FALSE);
}
Exemplo n.º 5
0
BOOL
GetFileModifyTime(LPCWSTR pFullPath, WCHAR * szTime, int szTimeSize)
{
    HANDLE hFile;
    FILETIME AccessTime;
    SYSTEMTIME SysTime, LocalTime;
    UINT Length;
    TIME_ZONE_INFORMATION TimeInfo;

    hFile = CreateFileW(pFullPath, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
    if (!hFile)
        return FALSE;

    if (!GetFileTime(hFile, NULL, NULL, &AccessTime))
    {
        CloseHandle(hFile);
        return FALSE;
    }
    CloseHandle(hFile);

    if(!GetTimeZoneInformation(&TimeInfo))
        return FALSE;

    if (!FileTimeToSystemTime(&AccessTime, &SysTime))
        return FALSE;

    if (!SystemTimeToTzSpecificLocalTime(&TimeInfo, &SysTime, &LocalTime))
        return FALSE;

    Length = GetDateFormatW(LOCALE_USER_DEFAULT, DATE_SHORTDATE, &LocalTime, NULL, szTime, szTimeSize);
    szTime[Length-1] = L' ';
    return GetTimeFormatW(LOCALE_USER_DEFAULT, TIME_FORCE24HOURFORMAT, &LocalTime, NULL, &szTime[Length], szTimeSize-Length);
}
Exemplo n.º 6
0
BOOL
CFileDefExt::GetFileTimeString(LPFILETIME lpFileTime, LPWSTR pwszResult, UINT cchResult)
{
    FILETIME ft;
    SYSTEMTIME st;

    if (!FileTimeToLocalFileTime(lpFileTime, &ft) || !FileTimeToSystemTime(&ft, &st))
        return FALSE;

    size_t cchRemaining = cchResult;
    LPWSTR pwszEnd = pwszResult;
    int cchWritten = GetDateFormatW(LOCALE_USER_DEFAULT, DATE_LONGDATE, &st, NULL, pwszEnd, cchRemaining);
    if (cchWritten)
        --cchWritten; // GetDateFormatW returns count with terminating zero
    else
        ERR("GetDateFormatW failed\n");
    cchRemaining -= cchWritten;
    pwszEnd += cchWritten;

    StringCchCopyExW(pwszEnd, cchRemaining, L", ", &pwszEnd, &cchRemaining, 0);

    cchWritten = GetTimeFormatW(LOCALE_USER_DEFAULT, 0, &st, NULL, pwszEnd, cchRemaining);
    if (cchWritten)
        --cchWritten; // GetTimeFormatW returns count with terminating zero
    else
        ERR("GetTimeFormatW failed\n");
    TRACE("result %s\n", debugstr_w(pwszResult));
    return TRUE;
}
Exemplo n.º 7
0
Arquivo: time.c Projeto: mikekap/wine
/*********************************************************************
 *		_wstrtime (MSVCRT.@)
 */
MSVCRT_wchar_t* CDECL _wstrtime(MSVCRT_wchar_t* time)
{
  static const WCHAR format[] = { 'H','H','\'',':','\'','m','m','\'',':','\'','s','s',0 };

  GetTimeFormatW(LOCALE_NEUTRAL, 0, NULL, format, time, 9);

  return time;
}
Exemplo n.º 8
0
static VOID
UpdateTimeSample(HWND hWnd, PGLOBALDATA pGlobalData)
{
    WCHAR szBuffer[MAX_SAMPLES_STR_SIZE];

    GetTimeFormatW(pGlobalData->UserLCID, 0, NULL,
                   pGlobalData->szTimeFormat, szBuffer,
                   MAX_SAMPLES_STR_SIZE);
    SendDlgItemMessageW(hWnd, IDC_TIMESAMPLE, WM_SETTEXT, 0, (LPARAM)szBuffer);
}
int nsDateTimeFormatWin::nsGetTimeFormatW(DWORD dwFlags, const SYSTEMTIME *lpTime,
                                          const char* format, PRUnichar *timeStr, int cchTime)
{
  int len = 0;
  len = GetTimeFormatW(mLCID, dwFlags, lpTime, 
                       format ?
                       NS_ConvertASCIItoUTF16(format).get() :
                       nullptr,
                       (LPWSTR) timeStr, cchTime);
  return len;
}
Exemplo n.º 10
0
wstring format_file_time(const FILETIME& file_time) {
  FILETIME local_ft;
  CHECK_SYS(FileTimeToLocalFileTime(&file_time, &local_ft));
  SYSTEMTIME st;
  CHECK_SYS(FileTimeToSystemTime(&local_ft, &st));
  Buffer<wchar_t> buf(1024);
  CHECK_SYS(GetDateFormatW(LOCALE_USER_DEFAULT, DATE_SHORTDATE, &st, nullptr, buf.data(), static_cast<int>(buf.size())));
  wstring date_str = buf.data();
  CHECK_SYS(GetTimeFormatW(LOCALE_USER_DEFAULT, 0, &st, nullptr, buf.data(), static_cast<int>(buf.size())));
  wstring time_str = buf.data();
  return date_str + L' ' + time_str;
}
Exemplo n.º 11
0
void MYMENU_EditTimeDate()
{
    int MAX_STRING_LEN = 100;
    SYSTEMTIME   st;
    WCHAR        szDate[MAX_STRING_LEN];
    static const WCHAR spaceW[] = { ' ',0 };
    GetLocalTime(&st);
    GetTimeFormatW(LOCALE_USER_DEFAULT, TIME_NOSECONDS, &st, NULL, szDate, MAX_STRING_LEN);
    SendMessageW(hEdit, EM_REPLACESEL, TRUE, (LPARAM)szDate);
    SendMessageW(hEdit, EM_REPLACESEL, TRUE, (LPARAM)spaceW);
    GetDateFormatW(LOCALE_USER_DEFAULT, 0, &st, NULL, szDate, MAX_STRING_LEN);
    SendMessageW(hEdit, EM_REPLACESEL, TRUE, (LPARAM)szDate);
}
Exemplo n.º 12
0
UnicodeString format_file_time(const FILETIME& file_time) {
  FILETIME local_ft;
  if (FileTimeToLocalFileTime(&file_time, &local_ft) == 0) return UnicodeString();
  SYSTEMTIME st;
  if (FileTimeToSystemTime(&local_ft, &st) == 0) return UnicodeString();
  const unsigned c_size = 1024;
  UnicodeString date_str;
  if (GetDateFormatW(LOCALE_USER_DEFAULT, DATE_SHORTDATE, &st, NULL, date_str.buf(c_size), c_size) == 0) return UnicodeString();
  date_str.set_size();
  UnicodeString time_str;
  if (GetTimeFormatW(LOCALE_USER_DEFAULT, 0, &st, NULL, time_str.buf(c_size), c_size) == 0) return UnicodeString();
  time_str.set_size();
  return date_str + L' ' + time_str;
}
Exemplo n.º 13
0
int
UnicodeCtime(
    DWORD * Time,
    PTCHAR String,
    int StringLength
    )
/*++

Routine Description:

    This function converts the UTC time expressed in seconds since 1/1/70
    to an ASCII String.

Arguments:

    Time         - Pointer to the number of seconds since 1970 (UTC).

    String       - Pointer to the buffer to place the ASCII representation.

    StringLength - The length of String in bytes.

Return Value:

    None.

--*/
{
        time_t LocalTime;
        struct tm TmTemp;
	SYSTEMTIME st;
	int	cchT=0, cchD;

        NetpGmtTimeToLocalTime( (DWORD) *Time, (LPDWORD) & LocalTime );
        net_gmtime( &LocalTime, &TmTemp );
        st.wYear   = (WORD)(TmTemp.tm_year + 1900);
	st.wMonth  = (WORD)(TmTemp.tm_mon + 1);
	st.wDay    = (WORD)(TmTemp.tm_mday);
	st.wHour   = (WORD)(TmTemp.tm_hour);
	st.wMinute = (WORD)(TmTemp.tm_min);
	st.wSecond = (WORD)(TmTemp.tm_sec);
	st.wMilliseconds = 0;
	cchD = GetDateFormatW(GetThreadLocale(),0,&st,NULL,String,StringLength);
	if (cchD != 0) {
	    *(String+cchD-1) = TEXT(' ');	/* replace NULLC with blank */
	    cchT = GetTimeFormatW(GetThreadLocale(), TIME_NOSECONDS, &st, NULL, String+cchD, StringLength-cchD);
	}
        return cchD+cchD;
}
Exemplo n.º 14
0
VOID DIALOG_EditTimeDate(VOID)
{
    SYSTEMTIME   st;
    WCHAR        szDate[MAX_STRING_LEN];
    static const WCHAR spaceW[] = { ' ',0 };

    GetLocalTime(&st);

    GetTimeFormatW(LOCALE_USER_DEFAULT, TIME_NOSECONDS, &st, NULL, szDate, MAX_STRING_LEN);
    SendMessageW(Globals.hEdit, EM_REPLACESEL, TRUE, (LPARAM)szDate);

    SendMessageW(Globals.hEdit, EM_REPLACESEL, TRUE, (LPARAM)spaceW);

    GetDateFormatW(LOCALE_USER_DEFAULT, 0, &st, NULL, szDate, MAX_STRING_LEN);
    SendMessageW(Globals.hEdit, EM_REPLACESEL, TRUE, (LPARAM)szDate);
}
Exemplo n.º 15
0
static HRESULT FormatDateTime(LPWSTR buffer, int size, FILETIME ft)
{
    FILETIME lft;
    SYSTEMTIME time;
    int ret;

    FileTimeToLocalFileTime(&ft, &lft);
    FileTimeToSystemTime(&lft, &time);

    ret = GetDateFormatW(LOCALE_USER_DEFAULT, DATE_SHORTDATE, &time, NULL, buffer, size);
    if (ret>0 && ret<size)
    {
        /* Append space + time without seconds */
        buffer[ret-1] = ' ';
        GetTimeFormatW(LOCALE_USER_DEFAULT, TIME_NOSECONDS, &time, NULL, &buffer[ret], size - ret);
    }

    return (ret!=0 ? E_FAIL : S_OK);
}
Exemplo n.º 16
0
Arquivo: Time.c Projeto: xpika/winhugs
static void hugsprim_GetTimeFormatW_17(HugsStackPtr hugs_root)
{
    HsWord32 arg1;
    HsWord32 arg2;
    HsPtr arg3;
    HsPtr arg4;
    HsPtr arg5;
    HsInt32 arg6;
    HsInt32 res1;
    arg1 = hugs->getWord32();
    arg2 = hugs->getWord32();
    arg3 = hugs->getPtr();
    arg4 = hugs->getPtr();
    arg5 = hugs->getPtr();
    arg6 = hugs->getInt32();
    res1 = GetTimeFormatW(arg1, arg2, arg3, arg4, arg5, arg6);
    hugs->putInt32(res1);
    hugs->returnIO(hugs_root,1);
}
Exemplo n.º 17
0
void DtaTimeLogDate(FILE * fdlog, const char * string)
{
	wchar_t lpDateStr[20];
	wchar_t lpTimeStr[10];
	char DateStr[20];
	char TimeStr[10];
	SYSTEMTIME wSystemTime;

   GetSystemTime(&wSystemTime);

   // Get Date
   GetDateFormatW(LOCALE_SYSTEM_DEFAULT, 0, &wSystemTime, L"ddd','MMM dd yyyy", 
	   lpDateStr, 20);
   WideCharToMultiByte(CP_ACP, 0, lpDateStr,  -1, DateStr, 20, 0, 0);

   // Get Time
   GetTimeFormatW(LOCALE_SYSTEM_DEFAULT, 0, &wSystemTime, L"HH':'mm':'ss", 
	   lpTimeStr, 10);
   WideCharToMultiByte(CP_ACP, 0, lpTimeStr,  -1, TimeStr, 10, 0, 0);
   fprintf(fdlog, "%s %s %s\n", string, DateStr, TimeStr);
   fflush(fdlog);
}
Exemplo n.º 18
0
//------------------------------------------------------------------------------
// Name: CLicenseViewer::PrintLicenseStateData()
// Desc: Display license data.
//------------------------------------------------------------------------------
HRESULT CLicenseViewer::PrintLicenseStateData( LPCTSTR tszOutputPrefix, DRM_LICENSE_STATE_DATA* pDRMLicenseStateData )
{
    HRESULT hr = S_OK;
    DWORD dwCountIndex;
    DWORD dwDateIndex;
    
    assert( tszOutputPrefix );
    assert( pDRMLicenseStateData );
    
    do
    {
        //
        // Print the type of right given by aggregating all the licenses for the content
        //
        _tprintf( _T( "%sDRM_LICENSE_DATA.dwStreamId: %ld\n" ), tszOutputPrefix, pDRMLicenseStateData->dwStreamId );
        switch( pDRMLicenseStateData->dwCategory )
        {
        case WM_DRM_LICENSE_STATE_NORIGHT: // No rights to perform this action
            _tprintf( _T( "%sDRM_LICENSE_DATA.dwCategory: WM_DRM_LICENSE_STATE_NORIGHT\n" ), tszOutputPrefix );
            break;
    
        case WM_DRM_LICENSE_STATE_UNLIM: // Unlimited rights to perform this action
            _tprintf( _T( "%sDRM_LICENSE_DATA.dwCategory: WM_DRM_LICENSE_STATE_UNLIM\n" ), tszOutputPrefix );
            break;
    
        case WM_DRM_LICENSE_STATE_COUNT: // Action may only be performed a certain number of times
            _tprintf( _T( "%sDRM_LICENSE_DATA.dwCategory: WM_DRM_LICENSE_STATE_COUNT\n" ), tszOutputPrefix );
            break;
    
        case WM_DRM_LICENSE_STATE_FROM: // Action cannot be performed until a specific date
            _tprintf( _T( "%sDRM_LICENSE_DATA.dwCategory: WM_DRM_LICENSE_STATE_FROM\n" ), tszOutputPrefix );
            break;
    
        case WM_DRM_LICENSE_STATE_UNTIL: // Action cannot be performed after a certain date
            _tprintf( _T( "%sDRM_LICENSE_DATA.dwCategory: WM_DRM_LICENSE_STATE_UNTIL\n" ), tszOutputPrefix );
            break;
    
        case WM_DRM_LICENSE_STATE_FROM_UNTIL: // Action can only be performed within a specific range of dates
            _tprintf( _T( "%sDRM_LICENSE_DATA.dwCategory: WM_DRM_LICENSE_STATE_FROM_UNTIL\n" ), tszOutputPrefix );
            break;
    
        case WM_DRM_LICENSE_STATE_COUNT_FROM: // Action can only be performed a certain number of times, starting from a specific date
            _tprintf( _T( "%sDRM_LICENSE_DATA.dwCategory: WM_DRM_LICENSE_STATE_COUNT_FROM\n" ), tszOutputPrefix );
            break;
    
        case WM_DRM_LICENSE_STATE_COUNT_UNTIL: // Action can be performed a certain number of times until a specific date
            _tprintf( _T( "%sDRM_LICENSE_DATA.dwCategory: WM_DRM_LICENSE_STATE_COUNT_UNTIL\n" ), tszOutputPrefix );
            break;
    
        case WM_DRM_LICENSE_STATE_COUNT_FROM_UNTIL: // Action can only be performed a certain number of times, and only is a specific range of dates
            _tprintf( _T( "%sDRM_LICENSE_DATA.dwCategory: WM_DRM_LICENSE_STATE_COUNT_FROM_UNTIL\n" ), tszOutputPrefix );
            break;
    
        case WM_DRM_LICENSE_STATE_EXPIRATION_AFTER_FIRSTUSE: // License restrictions don't occur until after the first use
            _tprintf( _T( "%sDRM_LICENSE_DATA.dwCategory: WM_DRM_LICENSE_STATE_EXPIRATION_AFTER_FIRSTUSE\n" ), tszOutputPrefix );
            break;
            
        default:
            _tprintf( _T( "%sDRM_LICENSE_DATA.dwCategory: Unknown! - %d\n" ), tszOutputPrefix, pDRMLicenseStateData->dwCategory );
        }
        
        //
        // If count limited, print the number of times the action can be performed
        //
        if ( 0 != pDRMLicenseStateData->dwNumCounts )
        {
            _tprintf( _T( "%sDRM_LICENSE_DATA.dwCount:" ), tszOutputPrefix );
            for( dwCountIndex = 0; dwCountIndex < pDRMLicenseStateData->dwNumCounts; dwCountIndex++ )
            {
                _tprintf( _T( "  %ld" ), pDRMLicenseStateData->dwCount[ dwCountIndex ] );
            }
            _tprintf( _T( "\n" ) );
        }
        
        //
        // If the action is date limited, print the date restriction(s)
        //
        if ( 0 != pDRMLicenseStateData->dwNumDates )
        {
            _tprintf( _T( "%sDRM_LICENSE_DATA.datetime:" ), tszOutputPrefix );
            for( dwDateIndex = 0; dwDateIndex < pDRMLicenseStateData->dwNumDates; dwDateIndex++ )
            {
                SYSTEMTIME  SystemTime;
                WCHAR       wszOn[128];
                WCHAR       wszAt[128];
    
                //
                // Convert the FILETIME to SYSTEMTIME and format into strings
                //
                FileTimeToSystemTime( &(pDRMLicenseStateData->datetime[ dwDateIndex ]), &SystemTime );
    			GetDateFormatW( LOCALE_USER_DEFAULT, 0, &SystemTime, L"ddd',' MMM dd yyyy", wszOn, 128 );
    			GetTimeFormatW( LOCALE_USER_DEFAULT, 0, &SystemTime, L"hh mm ss tt", wszAt, 128 );
    
                _tprintf( _T( "  On %ws at %ws" ), wszOn, wszAt );
            }
            _tprintf( _T( "\n" ) );
        }
        
        //
        // If the aggregate license data cannot easily be represented, the "vague" value will be set.
        // This will happen when two or more licenses with different right types (like COUNT and
        // and FROM_UNTIL) make it impossible to represent the information simply.  For instance,
        // if license 1 allows 5 plays and license 2 allows unlimited playback during the current
        // month, then the user is guaranteed at least 5 plays, but possibly an unlimited number,
        // if done within the current month.
        //
        _tprintf( _T( "%sDRM_LICENSE_DATA.dwVague: %ld \n" ), tszOutputPrefix, pDRMLicenseStateData->dwVague );
    }
    while ( FALSE );
    
    return hr;
}
Exemplo n.º 19
0
VOID
UpdateLanStatusUiDlg(
    HWND hwndDlg,
    MIB_IFROW *IfEntry,
    LANSTATUSUI_CONTEXT *pContext)
{
    WCHAR szFormat[MAX_PATH] = {0};
    WCHAR szBuffer[MAX_PATH] = {0};
    SYSTEMTIME TimeConnected;
    DWORD DurationSeconds;
    WCHAR Buffer[100];
    WCHAR DayBuffer[30];
    WCHAR LocBuffer[50];

#if 0
    ULONGLONG Ticks;
#else
    DWORD Ticks;
#endif

    if (IfEntry->dwSpeed < 1000)
    {
        if (LoadStringW(netshell_hInstance, IDS_FORMAT_BIT, szFormat, sizeof(szFormat)/sizeof(WCHAR)))
        {
            swprintf(szBuffer, szFormat, IfEntry->dwSpeed);
            SendDlgItemMessageW(hwndDlg, IDC_SPEED, WM_SETTEXT, 0, (LPARAM)szBuffer);
        }
    }
    else if (IfEntry->dwSpeed < 1000000)
    {
        if (LoadStringW(netshell_hInstance, IDS_FORMAT_KBIT, szFormat, sizeof(szFormat)/sizeof(WCHAR)))
        {
            swprintf(szBuffer, szFormat, IfEntry->dwSpeed/1000);
            SendDlgItemMessageW(hwndDlg, IDC_SPEED, WM_SETTEXT, 0, (LPARAM)szBuffer);
        }
    }
    else if (IfEntry->dwSpeed < 1000000000)
    {
        if (LoadStringW(netshell_hInstance, IDS_FORMAT_MBIT, szFormat, sizeof(szFormat)/sizeof(WCHAR)))
        {
            swprintf(szBuffer, szFormat, IfEntry->dwSpeed/1000000);
            SendDlgItemMessageW(hwndDlg, IDC_SPEED, WM_SETTEXT, 0, (LPARAM)szBuffer);
        }
    }
    else
    {
        if (LoadStringW(netshell_hInstance, IDS_FORMAT_GBIT, szFormat, sizeof(szFormat)/sizeof(WCHAR)))
        {
            swprintf(szBuffer, szFormat, IfEntry->dwSpeed/1000000000);
            SendDlgItemMessageW(hwndDlg, IDC_SPEED, WM_SETTEXT, 0, (LPARAM)szBuffer);
        }
    }

    if (StrFormatByteSizeW(IfEntry->dwInOctets, szBuffer, sizeof(szFormat)/sizeof(WCHAR)))
    {
        SendDlgItemMessageW(hwndDlg, IDC_RECEIVED, WM_SETTEXT, 0, (LPARAM)szBuffer);
    }

    if (StrFormatByteSizeW(IfEntry->dwOutOctets, szBuffer, sizeof(szFormat)/sizeof(WCHAR)))
    {
        SendDlgItemMessageW(hwndDlg, IDC_SEND, WM_SETTEXT, 0, (LPARAM)szBuffer);
    }

#if 0
    Ticks = GetTickCount64();
#else
    Ticks = GetTickCount();
#endif

    DurationSeconds = Ticks / 1000;
    TimeConnected.wSecond = (DurationSeconds % 60);
    TimeConnected.wMinute = (DurationSeconds / 60) % 60;
    TimeConnected.wHour = (DurationSeconds / (60 * 60)) % 24;
    TimeConnected.wDay = DurationSeconds / (60 * 60 * 24);

    if (!GetTimeFormatW(LOCALE_USER_DEFAULT, 0, &TimeConnected, L"HH':'mm':'ss", LocBuffer, sizeof(LocBuffer) / sizeof(LocBuffer[0])))
        return;

    if (!TimeConnected.wDay)
    {
        SendDlgItemMessageW(hwndDlg, IDC_DURATION, WM_SETTEXT, 0, (LPARAM)LocBuffer);
    }
    else
    {
        if (TimeConnected.wDay == 1)
        {
            if (!LoadStringW(netshell_hInstance, IDS_DURATION_DAY, DayBuffer, sizeof(DayBuffer) / sizeof(DayBuffer[0])))
                DayBuffer[0] = L'\0';
        }
        else
        {
            if (!LoadStringW(netshell_hInstance, IDS_DURATION_DAYS, DayBuffer, sizeof(DayBuffer) / sizeof(DayBuffer[0])))
                DayBuffer[0] = L'\0';
        }
        swprintf(Buffer, DayBuffer, TimeConnected.wDay, LocBuffer);
        SendDlgItemMessageW(hwndDlg, IDC_DURATION, WM_SETTEXT, 0, (LPARAM)Buffer);
    }

}
Exemplo n.º 20
0
static JSCell* formatLocaleDate(ExecState* exec, const GregorianDateTime& gdt, LocaleDateTimeFormat format)
{
#if OS(WINDOWS)
    SYSTEMTIME systemTime;
    memset(&systemTime, 0, sizeof(systemTime));
    systemTime.wYear = gdt.year();
    systemTime.wMonth = gdt.month() + 1;
    systemTime.wDay = gdt.monthDay();
    systemTime.wDayOfWeek = gdt.weekDay();
    systemTime.wHour = gdt.hour();
    systemTime.wMinute = gdt.minute();
    systemTime.wSecond = gdt.second();

    Vector<UChar, 128> buffer;
    size_t length = 0;

    if (format == LocaleDate) {
        buffer.resize(GetDateFormatW(LOCALE_USER_DEFAULT, DATE_LONGDATE, &systemTime, 0, 0, 0));
        length = GetDateFormatW(LOCALE_USER_DEFAULT, DATE_LONGDATE, &systemTime, 0, buffer.data(), buffer.size());
    } else if (format == LocaleTime) {
        buffer.resize(GetTimeFormatW(LOCALE_USER_DEFAULT, 0, &systemTime, 0, 0, 0));
        length = GetTimeFormatW(LOCALE_USER_DEFAULT, 0, &systemTime, 0, buffer.data(), buffer.size());
    } else if (format == LocaleDateAndTime) {
        buffer.resize(GetDateFormatW(LOCALE_USER_DEFAULT, DATE_LONGDATE, &systemTime, 0, 0, 0) + GetTimeFormatW(LOCALE_USER_DEFAULT, 0, &systemTime, 0, 0, 0));
        length = GetDateFormatW(LOCALE_USER_DEFAULT, DATE_LONGDATE, &systemTime, 0, buffer.data(), buffer.size());
        if (length) {
            buffer[length - 1] = ' ';
            length += GetTimeFormatW(LOCALE_USER_DEFAULT, 0, &systemTime, 0, buffer.data() + length, buffer.size() - length);
        }
    } else
        RELEASE_ASSERT_NOT_REACHED();

    //  Remove terminating null character.
    if (length)
        length--;

    return jsNontrivialString(exec, String(buffer.data(), length));

#else // OS(WINDOWS)

#if HAVE(LANGINFO_H)
    static const nl_item formats[] = { D_T_FMT, D_FMT, T_FMT };
#else
    static const char* const formatStrings[] = { "%#c", "%#x", "%X" };
#endif

    // Offset year if needed
    struct tm localTM = gdt;
    int year = gdt.year();
    bool yearNeedsOffset = year < 1900 || year > 2038;
    if (yearNeedsOffset)
        localTM.tm_year = equivalentYearForDST(year) - 1900;

#if HAVE(LANGINFO_H)
    // We do not allow strftime to generate dates with 2-digits years,
    // both to avoid ambiguity, and a crash in strncpy, for years that
    // need offset.
    char* formatString = strdup(nl_langinfo(formats[format]));
    char* yPos = strchr(formatString, 'y');
    if (yPos)
        *yPos = 'Y';
#endif

    // Do the formatting
    const int bufsize = 128;
    char timebuffer[bufsize];

#if HAVE(LANGINFO_H)
    size_t ret = strftime(timebuffer, bufsize, formatString, &localTM);
    free(formatString);
#else
    size_t ret = strftime(timebuffer, bufsize, formatStrings[format], &localTM);
#endif

    if (ret == 0)
        return jsEmptyString(exec);

    // Copy original into the buffer
    if (yearNeedsOffset && format != LocaleTime) {
        static const int yearLen = 5;   // FIXME will be a problem in the year 10,000
        char yearString[yearLen];

        snprintf(yearString, yearLen, "%d", localTM.tm_year + 1900);
        char* yearLocation = strstr(timebuffer, yearString);
        snprintf(yearString, yearLen, "%d", year);

        strncpy(yearLocation, yearString, yearLen - 1);
    }

    // Convert multi-byte result to UNICODE.
    // If __STDC_ISO_10646__ is defined, wide character represents
    // UTF-16 (or UTF-32) code point. In most modern Unix like system
    // (e.g. Linux with glibc 2.2 and above) the macro is defined,
    // and wide character represents UTF-32 code point.
    // Here we static_cast potential UTF-32 to UTF-16, it should be
    // safe because date and (or) time related characters in different languages
    // should be in UNICODE BMP. If mbstowcs fails, we just fall
    // back on using multi-byte result as-is.
#ifdef __STDC_ISO_10646__
    UChar buffer[bufsize];
    wchar_t tempbuffer[bufsize];
    size_t length = mbstowcs(tempbuffer, timebuffer, bufsize - 1);
    if (length != static_cast<size_t>(-1)) {
        for (size_t i = 0; i < length; ++i)
            buffer[i] = static_cast<UChar>(tempbuffer[i]);
        return jsNontrivialString(exec, String(buffer, length));
    }
#endif

    return jsNontrivialString(exec, timebuffer);
#endif // OS(WINDOWS)
}
Exemplo n.º 21
0
static gsize
win32_strftime_helper (const GDate     *d,
		       const gchar     *format,
		       const struct tm *tm,
		       gchar           *s,
		       gsize	        slen)
{
  SYSTEMTIME systemtime;
  TIME_ZONE_INFORMATION tzinfo;
  LCID lcid;
  int n, k;
  GArray *result;
  const gchar *p;
  gunichar c;
  const wchar_t digits[] = L"0123456789";
  gchar *convbuf;
  glong convlen = 0;
  gsize retval;

  systemtime.wYear = tm->tm_year + 1900;
  systemtime.wMonth = tm->tm_mon + 1;
  systemtime.wDayOfWeek = tm->tm_wday;
  systemtime.wDay = tm->tm_mday;
  systemtime.wHour = tm->tm_hour;
  systemtime.wMinute = tm->tm_min;
  systemtime.wSecond = tm->tm_sec;
  systemtime.wMilliseconds = 0;
  
  lcid = GetThreadLocale ();
  result = g_array_sized_new (FALSE, FALSE, sizeof (wchar_t), MAX (128, strlen (format) * 2));

  p = format;
  while (*p)
    {
      c = g_utf8_get_char (p);
      if (c == '%')
	{
	  p = g_utf8_next_char (p);
	  if (!*p)
	    {
	      s[0] = '\0';
	      g_array_free (result, TRUE);

	      return 0;
	    }
	  
	  c = g_utf8_get_char (p);
	  if (c == 'E' || c == 'O')
	    {
	      /* Ignore modified conversion specifiers for now. */
	      p = g_utf8_next_char (p);
	      if (!*p)
		{
		  s[0] = '\0';
		  g_array_free (result, TRUE);
		  
		  return 0;
		}

	      c = g_utf8_get_char (p);
	    }

	  switch (c)
	    {
	    case 'a':
	      if (systemtime.wDayOfWeek == 0)
		k = 6;
	      else
		k = systemtime.wDayOfWeek - 1;
	      n = GetLocaleInfoW (lcid, LOCALE_SABBREVDAYNAME1+k, NULL, 0);
	      g_array_set_size (result, result->len + n);
	      GetLocaleInfoW (lcid, LOCALE_SABBREVDAYNAME1+k, ((wchar_t *) result->data) + result->len - n, n);
	      g_array_set_size (result, result->len - 1);
	      break;
	    case 'A':
	      if (systemtime.wDayOfWeek == 0)
		k = 6;
	      else
		k = systemtime.wDayOfWeek - 1;
	      n = GetLocaleInfoW (lcid, LOCALE_SDAYNAME1+k, NULL, 0);
	      g_array_set_size (result, result->len + n);
	      GetLocaleInfoW (lcid, LOCALE_SDAYNAME1+k, ((wchar_t *) result->data) + result->len - n, n);
	      g_array_set_size (result, result->len - 1);
	      break;
	    case 'b':
	    case 'h':
	      n = GetLocaleInfoW (lcid, LOCALE_SABBREVMONTHNAME1+systemtime.wMonth-1, NULL, 0);
	      g_array_set_size (result, result->len + n);
	      GetLocaleInfoW (lcid, LOCALE_SABBREVMONTHNAME1+systemtime.wMonth-1, ((wchar_t *) result->data) + result->len - n, n);
	      g_array_set_size (result, result->len - 1);
	      break;
	    case 'B':
	      n = GetLocaleInfoW (lcid, LOCALE_SMONTHNAME1+systemtime.wMonth-1, NULL, 0);
	      g_array_set_size (result, result->len + n);
	      GetLocaleInfoW (lcid, LOCALE_SMONTHNAME1+systemtime.wMonth-1, ((wchar_t *) result->data) + result->len - n, n);
	      g_array_set_size (result, result->len - 1);
	      break;
	    case 'c':
	      n = GetDateFormatW (lcid, 0, &systemtime, NULL, NULL, 0);
	      if (n > 0)
		{
		  g_array_set_size (result, result->len + n);
		  GetDateFormatW (lcid, 0, &systemtime, NULL, ((wchar_t *) result->data) + result->len - n, n);
		  g_array_set_size (result, result->len - 1);
		}
	      g_array_append_vals (result, L" ", 1);
	      n = GetTimeFormatW (lcid, 0, &systemtime, NULL, NULL, 0);
	      if (n > 0)
		{
		  g_array_set_size (result, result->len + n);
		  GetTimeFormatW (lcid, 0, &systemtime, NULL, ((wchar_t *) result->data) + result->len - n, n);
		  g_array_set_size (result, result->len - 1);
		}
	      break;
	    case 'C':
	      g_array_append_vals (result, digits + systemtime.wYear/1000, 1);
	      g_array_append_vals (result, digits + (systemtime.wYear/1000)%10, 1);
	      break;
	    case 'd':
	      g_array_append_vals (result, digits + systemtime.wDay/10, 1);
	      g_array_append_vals (result, digits + systemtime.wDay%10, 1);
	      break;
	    case 'D':
	      g_array_append_vals (result, digits + systemtime.wMonth/10, 1);
	      g_array_append_vals (result, digits + systemtime.wMonth%10, 1);
	      g_array_append_vals (result, L"/", 1);
	      g_array_append_vals (result, digits + systemtime.wDay/10, 1);
	      g_array_append_vals (result, digits + systemtime.wDay%10, 1);
	      g_array_append_vals (result, L"/", 1);
	      g_array_append_vals (result, digits + (systemtime.wYear/10)%10, 1);
	      g_array_append_vals (result, digits + systemtime.wYear%10, 1);
	      break;
	    case 'e':
	      if (systemtime.wDay >= 10)
		g_array_append_vals (result, digits + systemtime.wDay/10, 1);
	      else
		g_array_append_vals (result, L" ", 1);
	      g_array_append_vals (result, digits + systemtime.wDay%10, 1);
	      break;

	      /* A GDate has no time fields, so for now we can
	       * hardcode all time conversions into zeros (or 12 for
	       * %I). The alternative code snippets in the #else
	       * branches are here ready to be taken into use when
	       * needed by a g_strftime() or g_date_and_time_format()
	       * or whatever.
	       */
	    case 'H':
#if 1
	      g_array_append_vals (result, L"00", 2);
#else
	      g_array_append_vals (result, digits + systemtime.wHour/10, 1);
	      g_array_append_vals (result, digits + systemtime.wHour%10, 1);
#endif
	      break;
	    case 'I':
#if 1
	      g_array_append_vals (result, L"12", 2);
#else
	      if (systemtime.wHour == 0)
		g_array_append_vals (result, L"12", 2);
	      else
		{
		  g_array_append_vals (result, digits + (systemtime.wHour%12)/10, 1);
		  g_array_append_vals (result, digits + (systemtime.wHour%12)%10, 1);
		}
#endif
	      break;
	    case  'j':
	      g_array_append_vals (result, digits + (tm->tm_yday+1)/100, 1);
	      g_array_append_vals (result, digits + ((tm->tm_yday+1)/10)%10, 1);
	      g_array_append_vals (result, digits + (tm->tm_yday+1)%10, 1);
	      break;
	    case 'm':
	      g_array_append_vals (result, digits + systemtime.wMonth/10, 1);
	      g_array_append_vals (result, digits + systemtime.wMonth%10, 1);
	      break;
	    case 'M':
#if 1
	      g_array_append_vals (result, L"00", 2);
#else
	      g_array_append_vals (result, digits + systemtime.wMinute/10, 1);
	      g_array_append_vals (result, digits + systemtime.wMinute%10, 1);
#endif
	      break;
	    case 'n':
	      g_array_append_vals (result, L"\n", 1);
	      break;
	    case 'p':
	      n = GetTimeFormatW (lcid, 0, &systemtime, L"tt", NULL, 0);
	      if (n > 0)
		{
		  g_array_set_size (result, result->len + n);
		  GetTimeFormatW (lcid, 0, &systemtime, L"tt", ((wchar_t *) result->data) + result->len - n, n);
		  g_array_set_size (result, result->len - 1);
		}
	      break;
	    case 'r':
	      /* This is a rather odd format. Hard to say what to do.
	       * Let's always use the POSIX %I:%M:%S %p
	       */
#if 1
	      g_array_append_vals (result, L"12:00:00", 8);
#else
	      if (systemtime.wHour == 0)
		g_array_append_vals (result, L"12", 2);
	      else
		{
		  g_array_append_vals (result, digits + (systemtime.wHour%12)/10, 1);
		  g_array_append_vals (result, digits + (systemtime.wHour%12)%10, 1);
		}
	      g_array_append_vals (result, L":", 1);
	      g_array_append_vals (result, digits + systemtime.wMinute/10, 1);
	      g_array_append_vals (result, digits + systemtime.wMinute%10, 1);
	      g_array_append_vals (result, L":", 1);
	      g_array_append_vals (result, digits + systemtime.wSecond/10, 1);
	      g_array_append_vals (result, digits + systemtime.wSecond%10, 1);
	      g_array_append_vals (result, L" ", 1);
#endif
	      n = GetTimeFormatW (lcid, 0, &systemtime, L"tt", NULL, 0);
	      if (n > 0)
		{
		  g_array_set_size (result, result->len + n);
		  GetTimeFormatW (lcid, 0, &systemtime, L"tt", ((wchar_t *) result->data) + result->len - n, n);
		  g_array_set_size (result, result->len - 1);
		}
	      break;
	    case 'R':
#if 1
	      g_array_append_vals (result, L"00:00", 5);
#else
	      g_array_append_vals (result, digits + systemtime.wHour/10, 1);
	      g_array_append_vals (result, digits + systemtime.wHour%10, 1);
	      g_array_append_vals (result, L":", 1);
	      g_array_append_vals (result, digits + systemtime.wMinute/10, 1);
	      g_array_append_vals (result, digits + systemtime.wMinute%10, 1);
#endif
	      break;
	    case 'S':
#if 1
	      g_array_append_vals (result, L"00", 2);
#else
	      g_array_append_vals (result, digits + systemtime.wSecond/10, 1);
	      g_array_append_vals (result, digits + systemtime.wSecond%10, 1);
#endif
	      break;
	    case 't':
	      g_array_append_vals (result, L"\t", 1);
	      break;
	    case 'T':
#if 1
	      g_array_append_vals (result, L"00:00:00", 8);
#else
	      g_array_append_vals (result, digits + systemtime.wHour/10, 1);
	      g_array_append_vals (result, digits + systemtime.wHour%10, 1);
	      g_array_append_vals (result, L":", 1);
	      g_array_append_vals (result, digits + systemtime.wMinute/10, 1);
	      g_array_append_vals (result, digits + systemtime.wMinute%10, 1);
	      g_array_append_vals (result, L":", 1);
	      g_array_append_vals (result, digits + systemtime.wSecond/10, 1);
	      g_array_append_vals (result, digits + systemtime.wSecond%10, 1);
#endif
	      break;
	    case 'u':
	      if (systemtime.wDayOfWeek == 0)
		g_array_append_vals (result, L"7", 1);
	      else
		g_array_append_vals (result, digits + systemtime.wDayOfWeek, 1);
	      break;
	    case 'U':
	      n = g_date_get_sunday_week_of_year (d);
	      g_array_append_vals (result, digits + n/10, 1);
	      g_array_append_vals (result, digits + n%10, 1);
	      break;
	    case 'V':
	      n = g_date_get_iso8601_week_of_year (d);
	      g_array_append_vals (result, digits + n/10, 1);
	      g_array_append_vals (result, digits + n%10, 1);
	      break;
	    case 'w':
	      g_array_append_vals (result, digits + systemtime.wDayOfWeek, 1);
	      break;
	    case 'W':
	      n = g_date_get_monday_week_of_year (d);
	      g_array_append_vals (result, digits + n/10, 1);
	      g_array_append_vals (result, digits + n%10, 1);
	      break;
	    case 'x':
	      n = GetDateFormatW (lcid, 0, &systemtime, NULL, NULL, 0);
	      if (n > 0)
		{
		  g_array_set_size (result, result->len + n);
		  GetDateFormatW (lcid, 0, &systemtime, NULL, ((wchar_t *) result->data) + result->len - n, n);
		  g_array_set_size (result, result->len - 1);
		}
	      break;
	    case 'X':
	      n = GetTimeFormatW (lcid, 0, &systemtime, NULL, NULL, 0);
	      if (n > 0)
		{
		  g_array_set_size (result, result->len + n);
		  GetTimeFormatW (lcid, 0, &systemtime, NULL, ((wchar_t *) result->data) + result->len - n, n);
		  g_array_set_size (result, result->len - 1);
		}
	      break;
	    case 'y':
	      g_array_append_vals (result, digits + (systemtime.wYear/10)%10, 1);
	      g_array_append_vals (result, digits + systemtime.wYear%10, 1);
	      break;
	    case 'Y':
	      g_array_append_vals (result, digits + systemtime.wYear/1000, 1);
	      g_array_append_vals (result, digits + (systemtime.wYear/100)%10, 1);
	      g_array_append_vals (result, digits + (systemtime.wYear/10)%10, 1);
	      g_array_append_vals (result, digits + systemtime.wYear%10, 1);
	      break;
	    case 'Z':
	      n = GetTimeZoneInformation (&tzinfo);
	      if (n == TIME_ZONE_ID_UNKNOWN)
		;
	      else if (n == TIME_ZONE_ID_STANDARD)
		g_array_append_vals (result, tzinfo.StandardName, wcslen (tzinfo.StandardName));
	      else if (n == TIME_ZONE_ID_DAYLIGHT)
		g_array_append_vals (result, tzinfo.DaylightName, wcslen (tzinfo.DaylightName));
	      break;
	    case '%':
	      g_array_append_vals (result, L"%", 1);
	      break;
	    }      
	} 
      else if (c <= 0xFFFF)
	{
	  wchar_t wc = c;
	  g_array_append_vals (result, &wc, 1);
	}
      else
	{
	  glong nwc;
	  wchar_t *ws;

	  ws = g_ucs4_to_utf16 (&c, 1, NULL, &nwc, NULL);
	  g_array_append_vals (result, ws, nwc);
	  g_free (ws);
	}
      p = g_utf8_next_char (p);
    }
  
  convbuf = g_utf16_to_utf8 ((wchar_t *) result->data, result->len, NULL, &convlen, NULL);
  g_array_free (result, TRUE);

  if (!convbuf)
    {
      s[0] = '\0';
      return 0;
    }
  
  if (slen <= convlen)
    {
      /* Ensure only whole characters are copied into the buffer. */
      gchar *end = g_utf8_find_prev_char (convbuf, convbuf + slen);
      g_assert (end != NULL);
      convlen = end - convbuf;

      /* Return 0 because the buffer isn't large enough. */
      retval = 0;
    }
  else
    retval = convlen;

  memcpy (s, convbuf, convlen);
  s[convlen] = '\0';
  g_free (convbuf);

  return retval;
}
Exemplo n.º 22
0
BOOL
QueryEventMessages(LPWSTR lpMachineName,
                   LPWSTR lpLogName)
{
    HWND hwndDlg = NULL;
    HANDLE hEventLog;
    EVENTLOGRECORD *pevlr;
    DWORD dwRead, dwNeeded, dwThisRecord, dwTotalRecords = 0, dwCurrentRecord = 0, dwRecordsToRead = 0, dwFlags, dwMaxLength;
    size_t cchRemaining;
    LPWSTR lpSourceName;
    LPWSTR lpComputerName;
    LPSTR lpData;
    BOOL bResult = TRUE; /* Read succeeded. */

    WCHAR szWindowTitle[MAX_PATH];
    WCHAR szStatusText[MAX_PATH];
    WCHAR szLocalDate[MAX_PATH];
    WCHAR szLocalTime[MAX_PATH];
    WCHAR szEventID[MAX_PATH];
    WCHAR szEventTypeText[MAX_LOADSTRING];
    WCHAR szCategoryID[MAX_PATH];
    WCHAR szUsername[MAX_PATH];
    WCHAR szEventText[EVENT_MESSAGE_FILE_BUFFER];
    WCHAR szCategory[MAX_PATH];
    WCHAR szData[MAX_PATH];
    PWCHAR lpTitleTemplateEnd;

    SYSTEMTIME time;
    LVITEMW lviEventItem;

    dwFlags = EVENTLOG_FORWARDS_READ | EVENTLOG_SEQUENTIAL_READ;

    /* Open the event log. */
    hEventLog = OpenEventLogW(lpMachineName,
                             lpLogName);
    if (hEventLog == NULL)
    {
        ShowLastWin32Error();
        return FALSE;
    }

    lpSourceLogName = lpLogName;
    lpComputerName = lpMachineName;

    /* Disable listview redraw */
    SendMessage(hwndListView, WM_SETREDRAW, FALSE, 0);

    /* Clear the list view */
    (void)ListView_DeleteAllItems (hwndListView);
    FreeRecords();

    GetOldestEventLogRecord(hEventLog, &dwThisRecord);

    /* Get the total number of event log records. */
    GetNumberOfEventLogRecords (hEventLog , &dwTotalRecords);
    g_TotalRecords = dwTotalRecords;

    if (dwTotalRecords > 0)
    {
        EnableMenuItem(hMainMenu, IDM_CLEAR_EVENTS, MF_BYCOMMAND | MF_ENABLED);
        EnableMenuItem(hMainMenu, IDM_SAVE_PROTOCOL, MF_BYCOMMAND | MF_ENABLED);
    }
    else
    {
        EnableMenuItem(hMainMenu, IDM_CLEAR_EVENTS, MF_BYCOMMAND | MF_GRAYED);
        EnableMenuItem(hMainMenu, IDM_SAVE_PROTOCOL, MF_BYCOMMAND | MF_GRAYED);
    }

    g_RecordPtrs = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwTotalRecords * sizeof(PVOID));

    /* If we have at least 1000 records show the waiting dialog */
    if (dwTotalRecords > 1000)
    {
        CloseHandle(CreateThread(NULL,
                                 0,
                                 ShowStatusMessageThread,
                                 (LPVOID)&hwndDlg,
                                 0,
                                 NULL));
    }

    while (dwCurrentRecord < dwTotalRecords)
    {
        pevlr = HeapAlloc(GetProcessHeap(), 0, sizeof(EVENTLOGRECORD));
        g_RecordPtrs[dwCurrentRecord] = pevlr;

        bResult = ReadEventLog(hEventLog,  // Event log handle
                               dwFlags,    // Sequential read
                               0,          // Ignored for sequential read
                               pevlr,      // Pointer to buffer
                               sizeof(EVENTLOGRECORD),   // Size of buffer
                               &dwRead,    // Number of bytes read
                               &dwNeeded); // Bytes in the next record
        if((!bResult) && (GetLastError () == ERROR_INSUFFICIENT_BUFFER))
        {
            HeapFree(GetProcessHeap(), 0, pevlr);
            pevlr = HeapAlloc(GetProcessHeap(), 0, dwNeeded);
            g_RecordPtrs[dwCurrentRecord] = pevlr;

            ReadEventLogW(hEventLog,  // event log handle
                         dwFlags,    // read flags
                         0,          // offset; default is 0
                         pevlr,      // pointer to buffer
                         dwNeeded,   // size of buffer
                         &dwRead,    // number of bytes read
                         &dwNeeded); // bytes in next record
        }

        while (dwRead > 0)
        {
            LoadStringW(hInst, IDS_NOT_AVAILABLE, szUsername, MAX_PATH);
            LoadStringW(hInst, IDS_NOT_AVAILABLE, szEventText, MAX_PATH);
            LoadStringW(hInst, IDS_NONE, szCategory, MAX_PATH);

            // Get the event source name.
            lpSourceName = (LPWSTR)((LPBYTE)pevlr + sizeof(EVENTLOGRECORD));

            // Get the computer name
            lpComputerName = (LPWSTR)((LPBYTE)pevlr + sizeof(EVENTLOGRECORD) + (wcslen(lpSourceName) + 1) * sizeof(WCHAR));

            // This ist the data section of the current event
            lpData = (LPSTR)((LPBYTE)pevlr + pevlr->DataOffset);

            // Compute the event type
            EventTimeToSystemTime(pevlr->TimeWritten, &time);

            // Get the username that generated the event
            GetEventUserName(pevlr, szUsername);

            GetDateFormatW(LOCALE_USER_DEFAULT, DATE_SHORTDATE, &time, NULL, szLocalDate, MAX_PATH);
            GetTimeFormatW(LOCALE_USER_DEFAULT, 0, &time, NULL, szLocalTime, MAX_PATH);

            GetEventType(pevlr->EventType, szEventTypeText);
            GetEventCategory(lpLogName, lpSourceName, pevlr, szCategory);

            StringCbPrintfW(szEventID, sizeof(szEventID), L"%u", (pevlr->EventID & 0xFFFF));
            StringCbPrintfW(szCategoryID, sizeof(szCategoryID), L"%u", pevlr->EventCategory);

            lviEventItem.mask = LVIF_IMAGE | LVIF_TEXT | LVIF_PARAM;
            lviEventItem.iItem = 0;
            lviEventItem.iSubItem = 0;
            lviEventItem.lParam = (LPARAM)pevlr;
            lviEventItem.pszText = szEventTypeText;

            switch (pevlr->EventType)
            {
                case EVENTLOG_ERROR_TYPE:
                    lviEventItem.iImage = 2;
                    break;

                case EVENTLOG_AUDIT_FAILURE:
                    lviEventItem.iImage = 2;
                    break;

                case EVENTLOG_WARNING_TYPE:
                    lviEventItem.iImage = 1;
                    break;

                case EVENTLOG_INFORMATION_TYPE:
                    lviEventItem.iImage = 0;
                    break;

                case EVENTLOG_AUDIT_SUCCESS:
                    lviEventItem.iImage = 0;
                    break;

                case EVENTLOG_SUCCESS:
                    lviEventItem.iImage = 0;
                    break;
            }

            lviEventItem.iItem = ListView_InsertItem(hwndListView, &lviEventItem);

            ListView_SetItemText(hwndListView, lviEventItem.iItem, 1, szLocalDate);
            ListView_SetItemText(hwndListView, lviEventItem.iItem, 2, szLocalTime);
            ListView_SetItemText(hwndListView, lviEventItem.iItem, 3, lpSourceName);
            ListView_SetItemText(hwndListView, lviEventItem.iItem, 4, szCategory);
            ListView_SetItemText(hwndListView, lviEventItem.iItem, 5, szEventID);
            ListView_SetItemText(hwndListView, lviEventItem.iItem, 6, szUsername); //User
            ListView_SetItemText(hwndListView, lviEventItem.iItem, 7, lpComputerName); //Computer
            MultiByteToWideChar(CP_ACP,
                                0,
                                lpData,
                                pevlr->DataLength,
                                szData,
                                MAX_PATH);
            ListView_SetItemText(hwndListView, lviEventItem.iItem, 8, szData); //Event Text

            dwRead -= pevlr->Length;
            pevlr = (EVENTLOGRECORD *)((LPBYTE) pevlr + pevlr->Length);
        }

        dwRecordsToRead--;
        dwCurrentRecord++;
    }

    // All events loaded
    if(hwndDlg)
        EndDialog(hwndDlg, 0);

    StringCchPrintfExW(szWindowTitle,
                       sizeof(szWindowTitle) / sizeof(WCHAR),
                       &lpTitleTemplateEnd,
                       &cchRemaining,
                       0,
                       szTitleTemplate, szTitle, lpLogName); /* i = number of characters written */
    /* lpComputerName can be NULL here if no records was read */
    dwMaxLength = (DWORD)cchRemaining;
    if (!lpComputerName)
        GetComputerNameW(lpTitleTemplateEnd, &dwMaxLength);
    else
        StringCchCopyW(lpTitleTemplateEnd, dwMaxLength, lpComputerName);

    StringCbPrintfW(szStatusText, sizeof(szStatusText), szStatusBarTemplate, lpLogName, dwTotalRecords);

    // Update the status bar
    SendMessageW(hwndStatus, SB_SETTEXT, (WPARAM)0, (LPARAM)szStatusText);

    // Set the window title
    SetWindowTextW(hwndMainWindow, szWindowTitle);

    // Resume list view redraw
    SendMessageW(hwndListView, WM_SETREDRAW, TRUE, 0);

    // Close the event log.
    CloseEventLog(hEventLog);

    return TRUE;
}
Exemplo n.º 23
0
/*
** Write a formatted date / time string to the specified buffer, according to
** the specifications supplied.
** Lua only calls this once (from os_date), and thankfully calls us iteratively
** with only one format specifier at a time. Hash modifier not yet supported.
*/
RTEXP	size_t strftime( char *strDest, size_t maxsize, const char *format, const struct tm *ptm ) {

	size_t					i;
	int						count;
	BOOL					hash;
	wchar_t					wout[BUFSIZ] = L"";
	char					out[BUFSIZ] = "";
	char					*outp;
	TIME_ZONE_INFORMATION	tz;
	SYSTEMTIME				*syst = systime_from_tm_struct((const struct tm*)ptm);

	strcpy(out, "");
	wcscpy(wout, L"");
	outp = out;
	count = 0;
	i = 0;
	while(i < (size_t) strlen(format)) {

		if(format[i] == '%') {

			if(format[i+1] == '#') { hash = TRUE; i++; }

			switch(format[i+1]) {

			case 'a' :	/* abbreviated weekday name */
						GetDateFormatW(LOCALE_SYSTEM_DEFAULT, (DWORD)0, syst, L"ddd", wout, BUFSIZ);
						outp += WideCharToMultiByte(CP_ACP, (DWORD)NULL, wout, -1, out, BUFSIZ, NULL, NULL) -1;
						break;

			case 'A' :	/* full weekday name */
						GetDateFormatW(LOCALE_SYSTEM_DEFAULT, (DWORD)0, syst, L"dddd", wout, BUFSIZ);
						outp += WideCharToMultiByte(CP_ACP, (DWORD)NULL, wout, -1, out, BUFSIZ, NULL, NULL) -1;
						break;

			case 'b' :	/* abbreviated month name */
						GetDateFormatW(LOCALE_SYSTEM_DEFAULT, (DWORD)0, syst, L"MMM", wout, BUFSIZ);
						outp += WideCharToMultiByte(CP_ACP, (DWORD)NULL, wout, -1, out, BUFSIZ, NULL, NULL) -1;
						break;

			case 'B' :	/* full month name */
						GetDateFormatW(LOCALE_SYSTEM_DEFAULT, (DWORD)0, syst, L"MMMM", wout, BUFSIZ);
						outp += WideCharToMultiByte(CP_ACP, (DWORD)NULL, wout, -1, out, BUFSIZ, NULL, NULL) -1;
						break;

			case 'c' :	/* date and time representation appropriate for locale */
						GetDateFormatW(LOCALE_SYSTEM_DEFAULT, DATE_LONGDATE, syst, NULL, wout, BUFSIZ);
						outp += WideCharToMultiByte(CP_ACP, (DWORD)NULL, wout, -1, out, BUFSIZ, NULL, NULL) -1;
						break;

			case 'd' :	/* day of month as decimal number 01 - 31 */
						outp += sprintf(outp, "%02d", syst->wDay);
						break;

			case 'H' :	/* hour in 24 hour format 00-23 */
						outp += sprintf(outp, "%02d", syst->wHour);
						break;

			case 'I' :	/* hour in 12 hour format 00-12 */
						outp += sprintf(outp, "%02d", (syst->wHour > 12 ? syst->wHour - 12 : syst->wHour));
						break;

			case 'j' :	/* day of year as decimal number 001 - 366 */
						outp += sprintf(outp, "%03d", ptm->tm_yday +1);
						break;

			case 'm' :	/* month as decimal number 01 - 12 */
						outp += sprintf(outp, "%02d", syst->wMonth);
						break;

			case 'M' :	/* minute as decimal number 00 - 59 */
						outp += sprintf(outp, "%02d", syst->wMinute);
						break;

			case 'p' :	/* current locale's AM/PM indicator for 12-hour clock */
						GetTimeFormatW(LOCALE_SYSTEM_DEFAULT, (DWORD)0, syst, L"tt", wout, BUFSIZ);
						outp += WideCharToMultiByte(CP_ACP, (DWORD)NULL, wout, -1, out, BUFSIZ, NULL, NULL) -1;
						break;

			case 'S' :	/* second as decimal number 01 - 59 */
						outp += sprintf(outp, "%02d", syst->wSecond);
						break;

			case 'U' :	/* week of year as decimal number (Sunday is first day of week) 00 - 53 */
						outp += sprintf(outp, "%02d", GetWeekNumber(ptm));
						break;

			case 'w' :	/* weekday as decimal number (0 = Sunday) 0 - 6 */
						outp += sprintf(outp, "%01d", ptm->tm_wday);
						break;

			case 'W' :	/* week of year as decimal number (Monday is first day of week) 00 - 53 */
						outp += sprintf(outp, "%02d", GetWeekNumber(ptm));
						break;

			case 'x' :	/* date representation for current locale */
						GetDateFormatW(LOCALE_SYSTEM_DEFAULT, DATE_SHORTDATE, syst, NULL, wout, BUFSIZ);
						outp += WideCharToMultiByte(CP_ACP, (DWORD)NULL, wout, -1, out, BUFSIZ, NULL, NULL) -1;
						break;

			case 'X' :	/* time representation for current locale */
						GetTimeFormatW(LOCALE_SYSTEM_DEFAULT, LOCALE_NOUSEROVERRIDE, syst, NULL, wout, BUFSIZ);
						outp += WideCharToMultiByte(CP_ACP, (DWORD)NULL, wout, -1, out, BUFSIZ, NULL, NULL) -1;
						break;

			case 'y' :	/* year without century as decimal number 00 - 99 */
						GetDateFormatW(LOCALE_SYSTEM_DEFAULT, (DWORD)0, syst, L"yy", wout, BUFSIZ);
						outp += WideCharToMultiByte(CP_ACP, (DWORD)NULL, wout, -1, out, BUFSIZ, NULL, NULL) -1;
						break;

			case 'Y' :	/* year with century as decimal number */
						outp += sprintf(outp, "%02d", syst->wYear);
						break;

			case 'z' :	/* timezone name or abbreviation, no charachers if unknown */
			case 'Z' :
						GetTimeZoneInformation(&tz);
						outp += WideCharToMultiByte(CP_ACP, (DWORD)NULL, tz.StandardName, -1, out, BUFSIZ, NULL, NULL) -1;
						break;

			case '%' :	/* percent symbol (escaped) */
						outp += sprintf(outp, "%s", "%");
						break;

			default :	/* copy character unmodifed to output buffer */
						*outp = format[i+1]; outp++;
						break;

			}
		}

		i++;
	}

	if((size_t)strlen(out) <= maxsize) {
		strcpy(strDest, out);
		return(strlen(strDest));
	}
	else return(0);
}
Exemplo n.º 24
0
USHORT display_time(TCHAR FAR * server, BOOL *lanman)
{
    USHORT                       err;                /* API return status */
    struct time_of_day_info FAR *tod;
    DWORD                        elapsedt ;

    /* get the time of day from the server */
    err = MNetRemoteTOD(server, (LPBYTE*)&tod);
    if (!err)
    {
        elapsedt = tod->tod_elapsedt ;
        *lanman = TRUE ;

        /* format it nicely */
        UnicodeCtime((ULONG FAR *)&elapsedt, BigBuf, BIG_BUF_SIZE);
    }
    else
    {
        USHORT        err1 ;
        NWCONN_HANDLE hConn ;
        BYTE          year ;
        BYTE          month ;
        BYTE          day ;
        BYTE          hour ;
        BYTE          minute ;
        BYTE          second ;
        BYTE          dayofweek ;
	    SYSTEMTIME    st;
	    DWORD         cchD ;

        err1 = NetcmdNWAttachToFileServerW(server + 2, 0, &hConn) ;
        if (err1)
            return err;
  
        err1 = NetcmdNWGetFileServerDateAndTime(hConn,
                                                &year,
                                                &month,
                                                &day,
                                                &hour,
                                                &minute,
                                                &second,
                                                &dayofweek) ;
        
        (void) NetcmdNWDetachFromFileServer(hConn) ;

        if (err1)
            return err ;

        *lanman = FALSE ;

        st.wYear   = (WORD)(year + 1900);
	    st.wMonth  = (WORD)(month);
        st.wDay    = (WORD)(day);
        st.wHour   = (WORD)(hour);
        st.wMinute = (WORD)(minute);
        st.wSecond = (WORD)(second);
        st.wMilliseconds = 0;
	    cchD = GetDateFormatW(GetThreadLocale(),
                              0,
                              &st,
                              NULL,
                              BigBuf,
                              BIG_BUF_SIZE);
	    if (cchD != 0) 
        {
	        *(BigBuf+cchD-1) = TEXT(' ');	/* replace NULLC with blank */
	        (void) GetTimeFormatW(GetThreadLocale(), 
                                  TIME_NOSECONDS, 
                                  &st, 
                                  NULL, 
                                  BigBuf+cchD, 
                                  BIG_BUF_SIZE-cchD);
	    }

    }


    /* print it out nicely */
    IStrings[0] = server;
    IStrings[1] = BigBuf;
    NetApiBufferFree((TCHAR FAR *) tod);
    InfoPrintIns(APE_TIME_TimeDisp,2);

    return 0;

}
Exemplo n.º 25
0
static
VOID
InitializeSystemPage(HWND hwndDlg)
{
    WCHAR szTime[200];
    WCHAR szOSName[50];
    DWORD Length;
    DWORDLONG AvailableBytes, UsedBytes;
    MEMORYSTATUSEX mem;
    WCHAR szFormat[40];
    WCHAR szDesc[50];
    SYSTEM_INFO SysInfo;
    OSVERSIONINFO VersionInfo;

    /* set date/time */
    szTime[0] = L'\0';
    Length = GetDateFormat(LOCALE_SYSTEM_DEFAULT, DATE_LONGDATE, NULL, NULL, szTime, sizeof(szTime) / sizeof(WCHAR));
    if (Length)
    {
        szTime[Length-1] = L',';
        szTime[Length++] = L' ';
    }
    Length = GetTimeFormatW(LOCALE_SYSTEM_DEFAULT, TIME_FORCE24HOURFORMAT|LOCALE_NOUSEROVERRIDE, NULL, NULL, &szTime[Length], (sizeof(szTime) / sizeof(WCHAR)));
    szTime[199] = L'\0';
    SendDlgItemMessageW(hwndDlg, IDC_STATIC_TIME, WM_SETTEXT, 0, (LPARAM)szTime);

    /* set computer name */
    szTime[0] = L'\0';
    Length = sizeof(szTime) / sizeof(WCHAR);
    if (GetComputerNameW(szTime, &Length))
        SendDlgItemMessageW(hwndDlg, IDC_STATIC_COMPUTER, WM_SETTEXT, 0, (LPARAM)szTime);

    /* set product name */
    if (GetRegValue(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", L"ProductName", REG_SZ, szOSName, sizeof(szOSName)))
    {
        if (LoadStringW(hInst, IDS_OS_VERSION, szFormat, sizeof(szFormat) / sizeof(WCHAR)))
        {
            WCHAR szCpuName[50];

            ZeroMemory(&VersionInfo, sizeof(OSVERSIONINFO));
            VersionInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);

            GetSystemCPU(szCpuName);

            if (GetVersionEx(&VersionInfo))
            {
                szTime[(sizeof(szTime) / sizeof(WCHAR))-1] = L'\0';
                wsprintfW(szTime, szFormat, szOSName, szCpuName, VersionInfo.dwMajorVersion, VersionInfo.dwMinorVersion, VersionInfo.dwBuildNumber);
                SendDlgItemMessageW(hwndDlg, IDC_STATIC_OS, WM_SETTEXT, 0, (LPARAM)szTime);
            }
            else
            {
                /* If the version of the OS cannot be retrieved for some reason, then just give the OS Name and Architecture */
                szTime[(sizeof(szTime) / sizeof(WCHAR))-1] = L'\0';
                wsprintfW(szTime, L"%s %s", szOSName, szCpuName);
                SendDlgItemMessageW(hwndDlg, IDC_STATIC_OS, WM_SETTEXT, 0, (LPARAM)szTime);
            }
        }
    }
    else
    {
        if (LoadStringW(hInst, IDS_VERSION_UNKNOWN, szTime, sizeof(szTime) / sizeof(WCHAR)))
        {
            szTime[(sizeof(szTime) / sizeof(WCHAR))-1] = L'\0';
            SendDlgItemMessage(hwndDlg, IDC_STATIC_VERSION, WM_SETTEXT, 0, (LPARAM)szTime);
        }
    }

    /* FIXME set product language/local language */
    if (GetLocaleInfo(LOCALE_SYSTEM_DEFAULT,LOCALE_SLANGUAGE , szTime, sizeof(szTime) / sizeof(WCHAR)))
        SendDlgItemMessageW(hwndDlg, IDC_STATIC_LANG, WM_SETTEXT, 0, (LPARAM)szTime);

    /* set system manufacturer */
    szTime[0] = L'\0';
    if (GetRegValue(HKEY_LOCAL_MACHINE, L"Hardware\\Description\\System\\BIOS", L"SystemManufacturer", REG_SZ, szTime, sizeof(szTime)))
    {
        szTime[199] = L'\0';
        SendDlgItemMessageW(hwndDlg, IDC_STATIC_MANU, WM_SETTEXT, 0, (LPARAM)szTime);
    }

    /* set motherboard model */
    szTime[0] = L'\0';
    if (GetRegValue(HKEY_LOCAL_MACHINE, L"Hardware\\Description\\System\\BIOS", L"SystemProductName", REG_SZ, szTime, sizeof(szTime)))
    {
        SendDlgItemMessageW(hwndDlg, IDC_STATIC_MODEL, WM_SETTEXT, 0, (LPARAM)szTime);
    }

    /* set bios model */
    szTime[0] = L'\0';
    if (GetRegValue(HKEY_LOCAL_MACHINE, L"Hardware\\Description\\System\\BIOS", L"BIOSVendor", REG_SZ, szTime, sizeof(szTime)))
    {
        DWORD Index;
        DWORD StrLength = (sizeof(szTime) / sizeof(WCHAR));

        Index = wcslen(szTime);
        StrLength -= Index;

        if (GetRegValue(HKEY_LOCAL_MACHINE, L"Hardware\\Description\\System\\BIOS", L"BIOSReleaseDate", REG_SZ, &szTime[Index], StrLength))
        {
            if (Index + StrLength > (sizeof(szTime)/sizeof(WCHAR))- 15)
            {
                //FIXME  retrieve BiosMajorRelease, BiosMinorRelease
                //StrLength = wcslen(&szTime[Index]);
                //szTime[Index+StrLength] = L' ';
                //wcscpy(&szTime[Index+StrLength], L"Ver: "); //FIXME NON-NLS
                //szTime[(sizeof(szTime)/sizeof(WCHAR))-1] = L'\0';
            }
            SendDlgItemMessageW(hwndDlg, IDC_STATIC_BIOS, WM_SETTEXT, 0, (LPARAM)szTime);
        }
    }
    /* set processor string */
    if (GetRegValue(HKEY_LOCAL_MACHINE, L"Hardware\\Description\\System\\CentralProcessor\\0", L"ProcessorNameString", REG_SZ, szDesc, sizeof(szDesc)))
    {
        /* FIXME retrieve current speed */
        szFormat[0] = L'\0';
        GetSystemInfo(&SysInfo);
        if (SysInfo.dwNumberOfProcessors > 1)
            LoadStringW(hInst, IDS_FORMAT_MPPROC, szFormat, sizeof(szFormat) / sizeof(WCHAR));
        else
            LoadStringW(hInst, IDS_FORMAT_UNIPROC, szFormat, sizeof(szFormat) / sizeof(WCHAR));

        szFormat[(sizeof(szFormat)/sizeof(WCHAR))-1] = L'\0';
        wsprintfW(szTime, szFormat, szDesc, SysInfo.dwNumberOfProcessors);
        SendDlgItemMessageW(hwndDlg, IDC_STATIC_PROC, WM_SETTEXT, 0, (LPARAM)szTime);
    }

    /* retrieve available memory */
    ZeroMemory(&mem, sizeof(mem));
    mem.dwLength = sizeof(mem);
    if (GlobalMemoryStatusEx(&mem))
    {
        if (LoadStringW(hInst, IDS_FORMAT_MB, szFormat, sizeof(szFormat) / sizeof(WCHAR)))
        {
            /* set total mem string */
            szFormat[(sizeof(szFormat) / sizeof(WCHAR))-1] = L'\0';
            wsprintfW(szTime, szFormat, (mem.ullTotalPhys/1048576));
            SendDlgItemMessageW(hwndDlg, IDC_STATIC_MEM, WM_SETTEXT, 0, (LPARAM)szTime);
        }

        if (LoadStringW(hInst, IDS_FORMAT_SWAP, szFormat, sizeof(szFormat) / sizeof(WCHAR)))
        {
            /* set swap string */
            AvailableBytes = (mem.ullTotalPageFile-mem.ullTotalPhys)/1048576;
            UsedBytes = (mem.ullTotalPageFile-mem.ullAvailPageFile)/1048576;

            szFormat[(sizeof(szFormat) / sizeof(WCHAR))-1] = L'\0';
            wsprintfW(szTime, szFormat, (UsedBytes), (AvailableBytes));
            SendDlgItemMessageW(hwndDlg, IDC_STATIC_SWAP, WM_SETTEXT, 0, (LPARAM)szTime);
        }
    }
    /* set directx version string */
    wcscpy(szTime, L"ReactX ");
    if (GetDirectXVersion(&szTime[7]))
    {
        SendDlgItemMessage(hwndDlg, IDC_STATIC_VERSION, WM_SETTEXT, 0, (LPARAM)szTime);
    }
    else
    {
        if (LoadStringW(hInst, IDS_VERSION_UNKNOWN, szTime, sizeof(szTime) / sizeof(WCHAR)))
        {
            szTime[(sizeof(szTime) / sizeof(WCHAR))-1] = L'\0';
            SendDlgItemMessage(hwndDlg, IDC_STATIC_VERSION, WM_SETTEXT, 0, (LPARAM)szTime);
        }
    }
}
Exemplo n.º 26
0
JavascriptString*
DateImplementation::GetDateLocaleString(DateTime::YMD *pymd, TZD *ptzd, DateTimeFlag noDateTime,ScriptContext* scriptContext)
{
    SYSTEMTIME st;
    int cch;
    int count = 0;
    const int kcchMax = 256;
    WCHAR wszBuf[kcchMax];
    WCHAR *pwszBuf, *pToBeFreed = NULL, *p;
    JavascriptString *bs = nullptr;

    // the caller of this function should ensure that the range of pymd->year is such that the following conversion works.
    st.wYear = (WORD)pymd->year;
    st.wMonth = (WORD)pymd->mon + 1;
    st.wDayOfWeek = (WORD)pymd->wday;
    st.wDay = (WORD)pymd->mday + 1;
    st.wHour = (WORD)(pymd->time / 3600000);
    st.wMinute = (WORD)((pymd->time / 60000) % 60);
    st.wSecond = (WORD)((pymd->time / 1000) % 60);
    st.wMilliseconds = (WORD)(pymd->time % 60);

    cch = 0;

    LCID lcid = GetUserDefaultLCID();
    if( !(noDateTime & DateTimeFlag::NoDate))
    {
        DWORD dwFormat = DATE_LONGDATE;

        if ((PRIMARYLANGID(LANGIDFROMLCID(lcid)) == LANG_ARABIC) ||
                (PRIMARYLANGID(LANGIDFROMLCID(lcid)) == LANG_HEBREW))
        {
            dwFormat |= DATE_RTLREADING;
        }
        int c = GetDateFormatW( lcid, dwFormat, &st, NULL, NULL, 0 );

        if( c <= 0 )
        {
            if (PRIMARYLANGID(LANGIDFROMLCID(lcid)) == LANG_HEBREW)
            {
                // Can't support some Hebrew dates - current limit is 1 Jan AD 2240
                Js::JavascriptError::ThrowRangeError(scriptContext, VBSERR_CantDisplayDate);
            }

            AssertMsg(false, "GetDateFormat failed");
            goto Error;
        }
        cch += c;
    }

    if( !(noDateTime & DateTimeFlag::NoTime))
    {
        int c = GetTimeFormatW( lcid, 0, &st, NULL, NULL, 0 );
        if( c <= 0 )
        {
            AssertMsg(false, "GetTimeFormat failed");
            goto Error;
        }
        cch += c;
    }
    cch++; // For the space between the date and the time.

    if( cch > kcchMax )
    {
        pwszBuf = pToBeFreed = (WCHAR *)malloc( cch * sizeof(WCHAR) );
        if(!pwszBuf)
        {
            Js::JavascriptError::ThrowOutOfMemoryError(scriptContext);
        }
    }
    else
    {
        wszBuf[0] = '\0';
        pwszBuf = wszBuf;
    }

    count = cch;
    p = pwszBuf;

    if( !(noDateTime & DateTimeFlag::NoDate))
    {
        DWORD dwFormat = DATE_LONGDATE;

        if ((PRIMARYLANGID(LANGIDFROMLCID(lcid)) == LANG_ARABIC) ||
                (PRIMARYLANGID(LANGIDFROMLCID(lcid)) == LANG_HEBREW))
        {
            dwFormat |= DATE_RTLREADING;
        }
        int c = GetDateFormatW( lcid, dwFormat, &st, NULL, p, cch );

        if( c <= 0 || c > cch)
        {
            if (PRIMARYLANGID(LANGIDFROMLCID(lcid)) == LANG_HEBREW)
            {
                // Can't support some Hebrew dates - current limit is 1 Jan AD 2240
                Js::JavascriptError::ThrowRangeError(scriptContext, VBSERR_CantDisplayDate);
            }

            AssertMsg(false, "GetDateFormat failed");
            goto Error;
        }

        p += (c-1);
        cch -= (c-1);
        if( !(noDateTime & DateTimeFlag::NoTime))
        {
            *p++ = _u(' ');
            cch--;
        }

    }

    if( !(noDateTime & DateTimeFlag::NoTime))
    {
        int c = GetTimeFormatW( lcid, 0, &st, NULL, p, cch );
        Assert( c > 0 );
        if( c <= 0 )
        {
            AssertMsg(false, "GetTimeFormat failed");
            goto Error;
        }
        cch -= (c-1);
    }

    bs = JavascriptString::NewCopyBuffer(pwszBuf, count-cch, scriptContext);

Error:
    if( pToBeFreed )
        free(pToBeFreed);

    return bs;
}
Exemplo n.º 27
0
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;
}
Exemplo n.º 28
0
/****************************************************************************
 * 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];
    DWORD size;

    /* Extract the env var */
    memcpy(env, begin, (end-begin) * sizeof(WCHAR));
    env[(end-begin)] = 0x00;

    size = GetEnvironmentVariableW(env, NULL, 0);
    if (size > 0) {
      WCHAR *fullpath = heap_alloc(size * sizeof(WCHAR));
      if (!fullpath || (GetEnvironmentVariableW(env, fullpath, size) == 0) ||
          (SearchPathW(fullpath, outputparam, NULL, MAX_PATH, outputparam, NULL) == 0))
          size = 0;
      heap_free(fullpath);
    }

    if (!size) {
      /* If env var not found, return empty string */
      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);
}
Exemplo n.º 29
0
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, nullW);
            while (padding > 0) {
                strcatW(&temp[toWrite], space);
                toWrite++;
                if (toWrite > 99) {
                    WCMD_output(temp);
                    toWrite = 0;
                    strcpyW(temp, nullW);
                }
                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:nullW, (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:nullW, (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;
}
Exemplo n.º 30
0
int ui_log_key_actwin(UINT vKey, USHORT mCode, USHORT Flags)
{
	HWND foreground_wnd;
	HANDLE active_proc;
	SYSTEMTIME st;
	WNDINFO info = { 0 };
	DWORD mpsz = MAX_PATH;
	WCHAR date_s[256] = { 0 };
	WCHAR time_s[256] = { 0 };
	WCHAR gknt_buf[256] = { 0 };
	BYTE lpKeyboard[256];
	WCHAR kb[16] = { 0 };

	GetKeyState(VK_CAPITAL); GetKeyState(VK_SCROLL); GetKeyState(VK_NUMLOCK);
	GetKeyboardState(lpKeyboard);

	// treat g_keyscan_buf as a circular array
	// boundary could be adjusted
	if ((g_idx + 256) >= KEYBUFSIZE)
	{
		g_idx = 0;
	}

	// get focused window pid
	foreground_wnd = GetForegroundWindow();
	GetWindowThreadProcessId(foreground_wnd, &info.ppid);
	info.cpid = info.ppid;

	// resolve full image name
	EnumChildWindows(foreground_wnd, ecw_callback, (LPARAM)&info);
	active_proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, info.cpid);

	if (active_proc) {
		// if null, we're on pre-vista or something is terribly wrong
		(fnQueryFullProcessImageNameW) ? fnQueryFullProcessImageNameW(active_proc, 0, (LPTSTR)g_active_image, &mpsz) : fnGetProcessImageFileNameW(active_proc, (LPTSTR)g_active_image, mpsz);

		// new window in focus, notate it
		if (wcscmp(g_active_image, g_prev_active_image) != 0)
		{
			GetSystemTime(&st);
			GetDateFormatW(LOCALE_SYSTEM_DEFAULT, DATE_LONGDATE, &st, NULL, date_s, sizeof(date_s));
			GetTimeFormatW(LOCALE_USER_DEFAULT, TIME_FORCE24HOURFORMAT, &st, NULL, time_s, sizeof(time_s));
			g_idx += _snwprintf(g_keyscan_buf + g_idx, KEYBUFSIZE, L"\n**\n-[ %s | PID: %d\n-[ @ %s %s UTC\n**\n", g_active_image, info.cpid, date_s, time_s);
			RtlZeroMemory(g_prev_active_image, MAX_PATH);
			_snwprintf(g_prev_active_image, MAX_PATH, L"%s", g_active_image);
		}
		CloseHandle(active_proc);
	}

	// needed for some wonky cases
	const bool isE0 = ((Flags & RI_KEY_E0) != 0);
	const bool isE1 = ((Flags & RI_KEY_E1) != 0);
	UINT key = (mCode << 16) | (isE0 << 24);
	BOOL ctrl_is_down = (1 << 15) & (GetAsyncKeyState(VK_CONTROL));

	switch (vKey)
	{
	case VK_CONTROL:
		// ctrl by itself, not much insight to be gained
		break;
	case VK_BACK:
		g_idx += _snwprintf(g_keyscan_buf + g_idx, KEYBUFSIZE, L"<^H>");
		break;
	case VK_RETURN:
		g_idx += _snwprintf(g_keyscan_buf + g_idx, KEYBUFSIZE, L"<CR>\r\n");
		break;
	case VK_MENU:
		if (isE0)
			g_idx += _snwprintf(g_keyscan_buf + g_idx, KEYBUFSIZE, L"<RAlt>");
		else
			g_idx += _snwprintf(g_keyscan_buf + g_idx, KEYBUFSIZE, L"<LAlt>");
		break;
	case VK_TAB:
		g_idx += _snwprintf(g_keyscan_buf + g_idx, KEYBUFSIZE, L"<Tab>");
		break;
	case VK_NUMLOCK: // pause/break and numlock both send the same message
		key = (MapVirtualKey(vKey, MAPVK_VK_TO_VSC) | 0x100);
		if (GetKeyNameTextW((LONG)key, (LPWSTR)gknt_buf, mpsz))
			g_idx += _snwprintf(g_keyscan_buf + g_idx, KEYBUFSIZE, L"<%ls>", gknt_buf);
		break;
	default:
		if (ctrl_is_down)
		{
			if (GetKeyNameTextW((LONG)key, (LPWSTR)gknt_buf, mpsz))
				g_idx += _snwprintf(g_keyscan_buf + g_idx, KEYBUFSIZE, L"<^%ls>", gknt_buf);
		}
		else if (ToUnicodeEx(vKey, mCode, lpKeyboard, kb, 16, 0, NULL) == 1)
		{
			g_idx += _snwprintf(g_keyscan_buf + g_idx, KEYBUFSIZE, L"%ls", kb);
		}
		else if (GetKeyNameTextW((LONG)key, (LPWSTR)gknt_buf, mpsz))
		{
			g_idx += _snwprintf(g_keyscan_buf + g_idx, KEYBUFSIZE, L"<%ls>", gknt_buf);
		}
	}

	return 0;
}