Exemplo n.º 1
0
VOID
WriteDebugLog(LPSTR lpFile, UINT iLine, LPSTR lpFunc, LPWSTR lpMsg, ...)
{
    LARGE_INTEGER FileSize, MoveTo, NewPos;
    WCHAR szMsg[MAX_STR_LEN * 3];
    WCHAR szText[MAX_STR_LEN * 4], szTime[MAX_STR_LEN];
    DWORD dwBytesWritten;
    va_list args;

    if (!hDebugLog || hDebugLog == INVALID_HANDLE_VALUE)
        return;

    MoveTo.QuadPart = 0;
    if (!SetFilePointerEx(hDebugLog, MoveTo, &NewPos, FILE_END))
        return;

    if (!GetFileSizeEx(hDebugLog, &FileSize))
        return;

    LockFile(hDebugLog, (DWORD_PTR)NewPos.QuadPart, 0, (DWORD_PTR)FileSize.QuadPart, 0);

    GetTimeFormat(LOCALE_USER_DEFAULT,
                  0, NULL, NULL, szTime,
                  MAX_STR_LEN);

    va_start(args, lpMsg);
    StringCbVPrintf(szMsg, sizeof(szMsg), lpMsg, args);
    va_end(args);

    StringCbPrintf(szText, sizeof(szText),
                   L"[%s] %S:%ld %S(): \"%s\"\r\n",
                   szTime, lpFile, iLine, lpFunc, szMsg);

    WriteFile(hDebugLog, szText,
              wcslen(szText) * sizeof(WCHAR),
              &dwBytesWritten, NULL);

    UnlockFile(hDebugLog, (DWORD_PTR)NewPos.QuadPart, 0, (DWORD_PTR)FileSize.QuadPart, 0);
}
Exemplo n.º 2
0
void Add2LogWithTime(TCHAR *txt)
{
	BOOL bLogTime = TRUE;
	TCHAR str[512];
	TCHAR lpTimeStr[128];
	TCHAR lpDateStr[128];
	LONG res;
	wsprintf(str,L"");
	//Read the system time
	res = GetTimeFormat(LOCALE_SYSTEM_DEFAULT,
							TIME_FORCE24HOURFORMAT,
							NULL,
							L"hh:mm:ss",
							lpTimeStr,
							sizeof (lpTimeStr ) * sizeof(TCHAR));
	if (res == 0)
	{
		wcscpy(lpTimeStr, L"err");
	}

	//Read the system date
	res = GetDateFormat(  LOCALE_SYSTEM_DEFAULT,
						  NULL,
						  NULL,
						  L"dd.MM.yyyy",
						  lpDateStr,
						  sizeof (lpDateStr) * sizeof(TCHAR));
	if (res == 0)
	{
		wcscpy(lpDateStr, L"err");
	}

	if (bLogTime == TRUE)
		wsprintf(str, L"%s %s\t%s", lpDateStr, lpTimeStr , txt);
	else
		wsprintf(str, L"%s", txt);
	writefile(str);

}
Exemplo n.º 3
0
void DateTime::toString(StringStorage *target) const
{
  SYSTEMTIME systemTime;

  toLocalSystemTime(&systemTime);

  const size_t dateStringMaxLength = 255;

  TCHAR dateString[dateStringMaxLength + 1];

  if (GetDateFormat(LOCALE_USER_DEFAULT,
        DATE_SHORTDATE,
        &systemTime,
        0,
        dateString,
        dateStringMaxLength) == 0) {
    // TODO: Process this error.
  }

  target->setString(dateString);
  target->appendChar(_T(' '));

  const size_t timeStringMaxLength = 255;

  TCHAR timeString[timeStringMaxLength + 1];

  if (GetTimeFormat(
        LOCALE_USER_DEFAULT,
        0,
        &systemTime,
        0,
        timeString,
        timeStringMaxLength) == 0) {
    // TODO: Process this error.
  }

  target->appendString(timeString);
}
Exemplo n.º 4
0
void Log::ReallyPrint(LPCTSTR format, va_list ap) 
{

	SYSTEMTIME current;
	GetLocalTime(&current);
	if (memcmp(&m_lastLogT, &current, sizeof(SYSTEMTIME)) != 0)
	{
		m_lastLogT = current;
		char time_str[50] = {0};
		char date_str[50] = {0};

		int nRet = GetDateFormat(LOCALE_USER_DEFAULT, NULL, &current, "ddd yyyy-MM-dd",  date_str, sizeof(date_str));
		nRet = GetTimeFormat(LOCALE_USER_DEFAULT,NULL, &current,"hh:mm:ss",time_str,sizeof(time_str));
		
		char time_buf[50];
		sprintf(time_buf, "%s %s\r\n",date_str, time_str);		
		ReallyPrintLine(time_buf);
	}


	// Prepare the complete log message
	TCHAR line[LINE_BUFFER_SIZE];
	memset(line, 0, sizeof(line));
	_vsnprintf(line, sizeof(line) - 2 * sizeof(TCHAR), format, ap);
	line[LINE_BUFFER_SIZE-2] = (TCHAR)'\0';
#if (!defined(_UNICODE) && !defined(_MBCS))
	int len = strlen(line);
	if (len > 0 && len <= sizeof(line) - 2 * sizeof(TCHAR) && line[len-1] == (TCHAR)'\n') {
		// Replace trailing '\n' with MS-DOS style end-of-line.
		line[len-1] = (TCHAR)'\r';
		line[len] =   (TCHAR)'\n';
		line[len+1] = (TCHAR)'\0';
	}
#endif
	
	ReallyPrintLine(line);
	ReallyPrintLine(TEXT("\n"));
}
Exemplo n.º 5
0
void CCoBroker::AddList(const cLog::cEventDesc &EventDesc, const TCHAR *Item, ...) throw( )
{
	try
	{
		// Exit if verbosity level is _NO_TRACE_ of high than defined level
		if( (_NO_TRACE_ == EventDesc.getVerbosity()) || (EventDesc.getVerbosity() >= _TRACE_CALLS_) )
			return;
		SYSTEMTIME SysTime;
		GetLocalTime(&SysTime);
		TCHAR Buf[MAX_PATH];
		tstring TimeStr;
		if(!GetTimeFormat(LOCALE_USER_DEFAULT,0,&SysTime,NULL,Buf,MAX_PATH))
			TimeStr += _T("Invalid time");
		else
			TimeStr += Buf;
		TimeStr += _T("> ");

		va_list vl;
		tstring str;
		for(va_start(vl, Item); Item; Item=va_arg(vl, PTCHAR))
		{
			str += Item;
		}
		va_end(vl);

		TimeStr += str;
		TimeStr+=_T(" ");
		if (EventDesc.getCallStack())
			TimeStr+=EventDesc.getCallStack();//call stack

		//HRESULT result;
		//result=NotifyLogMessage(CComBSTR(TimeStr.c_str()),EventDesc.getSeverity());
		::PostMessage(m_hWnd,m_msgFireNotifyLogMessage, reinterpret_cast<WPARAM>(new CComBSTR(TimeStr.c_str())),EventDesc.getSeverity());
	}
	catch(...)
	{
	}
}
Exemplo n.º 6
0
void
isc_time_formattimestamp(const isc_time_t *t, char *buf, unsigned int len) {
	FILETIME localft;
	SYSTEMTIME st;
	char DateBuf[50];
	char TimeBuf[50];

	static const char badtime[] = "99-Bad-9999 99:99:99.999";

	REQUIRE(len > 0);
	if (FileTimeToLocalFileTime(&t->absolute, &localft) &&
	    FileTimeToSystemTime(&localft, &st)) {
		GetDateFormat(LOCALE_USER_DEFAULT, 0, &st, "dd-MMM-yyyy",
			      DateBuf, 50);
		GetTimeFormat(LOCALE_USER_DEFAULT, TIME_NOTIMEMARKER|
			      TIME_FORCE24HOURFORMAT, &st, NULL, TimeBuf, 50);

		snprintf(buf, len, "%s %s.%03u", DateBuf, TimeBuf,
			 st.wMilliseconds);

	} else
		snprintf(buf, len, badtime);
}
Exemplo n.º 7
0
static void ConvertPGPTimeToString(PGPTime time,
								   char *dateString, 
								   PGPUInt32 dateStrLength,
								   char *timeString,
								   PGPUInt32 timeStrLength) 
{
	SYSTEMTIME	systemtime;
	time_t		ttTime;
	struct tm*	ptm;

	ttTime = PGPGetStdTimeFromPGPTime(time);
	ptm = localtime(&ttTime);

	StdTimeToSystemTime(ptm, &systemtime);

	GetDateFormat(LOCALE_USER_DEFAULT, DATE_SHORTDATE, &systemtime, 
		NULL, dateString, dateStrLength);

	GetTimeFormat(LOCALE_USER_DEFAULT, LOCALE_NOUSEROVERRIDE, &systemtime,
		NULL, timeString, timeStrLength);

	return;
}
Exemplo n.º 8
0
char *GetTimeLeft(DWORD dwTimeLeft,
                  char *szTimeString,
                  DWORD dwTimeStringBufSize)
{
  DWORD      dwTimeLeftPP;
  SYSTEMTIME stTime;

  ZeroMemory(&stTime, sizeof(stTime));
  dwTimeLeftPP         = dwTimeLeft + 1;
  stTime.wHour         = (unsigned)(dwTimeLeftPP / 60 / 60);
  stTime.wMinute       = (unsigned)((dwTimeLeftPP / 60) % 60);
  stTime.wSecond       = (unsigned)(dwTimeLeftPP % 60);

  ZeroMemory(szTimeString, dwTimeStringBufSize);
  /* format time string using user's local time format information */
  GetTimeFormat(LOCALE_USER_DEFAULT,
                TIME_NOTIMEMARKER|TIME_FORCE24HOURFORMAT,
                &stTime,
                NULL,
                szTimeString,
                dwTimeStringBufSize);

  return(szTimeString);
}
Exemplo n.º 9
0
/* Update all locale samples */
static VOID
UpdateLocaleSample(HWND hwndDlg, LCID lcidLocale)
{
    TCHAR OutBuffer[MAX_SAMPLES_STR_SIZE];

    /* Get number format sample */
    GetNumberFormat(lcidLocale, NO_FLAG, SAMPLE_NUMBER, NULL, OutBuffer,
                    MAX_SAMPLES_STR_SIZE);
    SendMessage(GetDlgItem(hwndDlg, IDC_NUMSAMPLE_EDIT),
                 WM_SETTEXT, 0, (LPARAM)OutBuffer);

    /* Get monetary format sample */
    GetCurrencyFormat(lcidLocale, LOCALE_USE_CP_ACP, SAMPLE_NUMBER, NULL,
                      OutBuffer, MAX_SAMPLES_STR_SIZE);
    SendMessage(GetDlgItem(hwndDlg, IDC_MONEYSAMPLE_EDIT),
                 WM_SETTEXT, 0, (LPARAM)OutBuffer);

    /* Get time format sample */
    GetTimeFormat(lcidLocale, NO_FLAG, NULL, NULL, OutBuffer, MAX_SAMPLES_STR_SIZE);
    SendMessage(GetDlgItem(hwndDlg, IDC_TIMESAMPLE_EDIT),
        WM_SETTEXT,
        0,
        (LPARAM)OutBuffer);

    /* Get short date format sample */
    GetDateFormat(lcidLocale, DATE_SHORTDATE, NULL, NULL, OutBuffer,
        MAX_SAMPLES_STR_SIZE);
    SendMessage(GetDlgItem(hwndDlg, IDC_SHORTTIMESAMPLE_EDIT), WM_SETTEXT,
        0, (LPARAM)OutBuffer);

    /* Get long date sample */
    GetDateFormat(lcidLocale, DATE_LONGDATE, NULL, NULL, OutBuffer,
        MAX_SAMPLES_STR_SIZE);
    SendMessage(GetDlgItem(hwndDlg, IDC_FULLTIMESAMPLE_EDIT),
        WM_SETTEXT, 0, (LPARAM)OutBuffer);
}
Exemplo n.º 10
0
CString FormatDateTime32bit(const Variant& value)
{
   unsigned int uiTime = GetUnsignedIntValue(value);

   FILETIME fileTime = { 0 };
   BOOL bRet = DosDateTimeToFileTime(HIWORD(uiTime), LOWORD(uiTime), &fileTime);
   if (bRet != TRUE)
      return _T("N/A");

   SYSTEMTIME systemTime = { 0 };
   bRet = FileTimeToSystemTime(&fileTime, &systemTime);
   if (bRet != TRUE)
      return _T("N/A");

   CString cszDate;
   GetDateFormat(LOCALE_USER_DEFAULT, 0, &systemTime, _T("yyyy'-'MM'-'dd"), cszDate.GetBuffer(32), 32);
   cszDate.ReleaseBuffer();

   CString cszTime;
   GetTimeFormat(LOCALE_USER_DEFAULT, 0, &systemTime, _T(" HH':'mm':'ss"), cszTime.GetBuffer(32), 32);
   cszTime.ReleaseBuffer();

   return cszDate + cszTime;
}
Exemplo n.º 11
0
/* Ad-hoc API exported by Opera: date and time */
/* static */ OP_STATUS
ES_ImportedAPI::FormatLocalTime(ES_ImportedAPI::DateFormatSpec how, uni_char *buf, unsigned length, ES_ImportedAPI::TimeElements* time)
{
#if defined(MSWIN) || defined(WINGOGI)
    SYSTEMTIME dtime;
    unsigned len = 0;

    dtime.wYear = time->year;
    dtime.wMonth = time->month + 1;
    dtime.wDayOfWeek = time->day_of_week;
    dtime.wDay = time->day_of_month;
    dtime.wHour = time->hour;
    dtime.wMinute = time->minute;
    dtime.wSecond = time->second;
    dtime.wMilliseconds = time->millisecond;

	if (how == GET_DATE_AND_TIME || how == GET_DATE)
		if ((len = GetDateFormat(LOCALE_USER_DEFAULT, DATE_LONGDATE, &dtime, NULL, buf, length)) == 0)
			goto failure;

	if (how == GET_DATE_AND_TIME)
		buf[len - 1] = ' ';

	if (how == GET_DATE_AND_TIME || how == GET_TIME)
        if ((len = GetTimeFormat(LOCALE_USER_DEFAULT, 0, &dtime, NULL, buf + len, length - len)) == 0)
			goto failure;

	return OpStatus::OK;

failure:
	// It seems that GetDateFormat or GetTimeFormat fails on Windows 95 (and perhaps some
	// installations of Windows 98).  It would be bad to return an empty string, so just
	// handle it by the default action.
#endif // MSWIN || WINGOGI
	return OpStatus::ERR;
}
Exemplo n.º 12
0
void ConvertDate(const FILETIME& ft,wchar_t *DateText,wchar_t *TimeText)
{
	if (ft.dwHighDateTime==0 && ft.dwLowDateTime==0)
	{
		if (DateText!=NULL)
			*DateText=0;

		if (TimeText!=NULL)
			*TimeText=0;

		return;
	}

	SYSTEMTIME st;
	FILETIME ct;
	FileTimeToLocalFileTime(&ft,&ct);
	FileTimeToSystemTime(&ct,&st);

	if (TimeText!=NULL)
		GetTimeFormat(LOCALE_USER_DEFAULT, 0, &st, 0, TimeText, MAX_DATETIME);

	if (DateText!=NULL)
		GetDateFormat(LOCALE_USER_DEFAULT, 0, &st, 0, DateText, MAX_DATETIME);
}
Exemplo n.º 13
0
STDMETHODIMP CBaseGraph::QueryPreferredFormat(GUID* pFormat)
{
    return GetTimeFormat(pFormat);
}
Exemplo n.º 14
0
static void	MyGetEnvironmentInfo (void)
{
    static FilePath	stMyApplicationPath;
    static DWORD	stMyDummy;
    static DWORD	stMyVersionSize;
    static char		*stMyVersionInfo;
    static UINT		stMyVersionInfoSize;
    static char		stMyTempString [256];
    static HANDLE	stMyFile;
    static DWORD	stMyFileSize;
    static FILETIME	stMyFileTime, stMyDummy1, stMyDummy2;
    static SYSTEMTIME	stMySystemTime;
    	
    //
    // Line 1: Date: Oct 20, 2000
    //
    
    // Start with current date label
    MyAddToBuffer ("Date: ");

    // Add the current date
    GetDateFormat (LOCALE_USER_DEFAULT, 0, NULL, "MMM d yyyy", 
        stMyTempString, sizeof (stMyTempString));
    MyAddToBuffer (stMyTempString);

    // Add a space
    MyAddToBuffer (" ");
    
    // Add the current time    
    GetTimeFormat (LOCALE_USER_DEFAULT, TIME_NOSECONDS, NULL, NULL, 
        stMyTempString, sizeof (stMyTempString));
    MyAddToBuffer (stMyTempString);
    
    // Add a newline
    MyAddToBuffer ("\r\n\r\n");
    
    //
    // Line 2: File Name: d:\ready\ready.exe
    //
    
    // Start with file name label
    MyAddToBuffer ("File Name: ");

    // Add the application path
    GetModuleFileName (NULL, stMyApplicationPath, sizeof (stMyApplicationPath));
    MyAddToBuffer (stMyApplicationPath);

    // Add a newline
    MyAddToBuffer ("\r\n");
    
    //
    // Line 3 (Maybe): Version: 1.0.2  [Mini/Restricted/IBM/71]
    //

    // Start with the version label
    MyAddToBuffer ("Version: ");
    
    // Set to empty string by default
    stMyVersionSize = GetFileVersionInfoSize (stMyApplicationPath, &stMyDummy);
    if ((stMyVersionSize != 0) && (stMyVersionSize <= stCrashBufferLeft))
    {
	if (GetFileVersionInfo (stMyApplicationPath, stMyDummy, 
				stCrashBufferLeft, stCrashBufferPtr))
	{
	    if (VerQueryValue (stCrashBufferPtr, 
			    "\\StringFileInfo\\04090000\\ProductVersion", 
			    &stMyVersionInfo, &stMyVersionInfoSize))
	    {			    
		// Add the version number (size includes \0)
		memmove (stCrashBufferPtr, stMyVersionInfo, 
			 stMyVersionInfoSize);
		stCrashBufferLeft -= stMyVersionInfoSize - 1;
		stCrashBufferPtr += stMyVersionInfoSize - 1; 
	    }
	    else
	    {
	    	MyAddToBuffer ("Unknown");
	    }
	}
	else
	{
	    MyAddToBuffer ("Unknown");
	}
    }
    else
    {
    	MyAddToBuffer ("Unknown");
    }
    
    if (gProgram.globalsInitialized)
    {
	// Add a spaces
	MyAddToBuffer ("  [");

	if (gProgram.miniVersion)
            MyAddToBuffer ("Mini/");
	if (gProgram.restrictedVersion)
            MyAddToBuffer ("Restricted/");
	if (gProgram.assistedByIBM)
            MyAddToBuffer ("IBM/");

	if (gProgram.expiryDateString [0] != 0)
	{
            MyAddToBuffer (gProgram.expiryDateString);
            MyAddToBuffer ("/");
	}

	wsprintf (stMyTempString, "%d]", gProgram.installKind);										    					        
        MyAddToBuffer (stMyTempString);
    } // if (gProgram.globalsInitialized)
		    
    // Add a newline
    MyAddToBuffer ("\r\n");
    
    //
    // Line 4: File Size: 2876346
    //
    stMyFile = CreateFile (stMyApplicationPath, GENERIC_READ, FILE_SHARE_READ,
                         NULL, OPEN_EXISTING, 0, 0);
    if (stMyFile != (HANDLE) INVALID_HANDLE_VALUE)
    {
    	stMyFileSize = GetFileSize (stMyFile, NULL);

    	// Start with the size label
	MyAddToBuffer ("File Size: ");
    
	// Add the file size
	wsprintf (stMyTempString, "%d\r\n", stMyFileSize);
	MyAddToBuffer (stMyTempString);
    	
    	//
    	// Line 5: File Date: Oct 10, 2000
    	//
    	GetFileTime (stMyFile, &stMyDummy1, &stMyDummy2, &stMyFileTime);
	if (FileTimeToSystemTime (&stMyFileTime, &stMySystemTime))
	{
    	    // Start with the date label
	    MyAddToBuffer ("File Date: ");
    
	    // Add the file date
	    GetDateFormat (LOCALE_USER_DEFAULT, 0, &stMySystemTime, 
	    	"MMM d yyyy", stMyTempString, sizeof (stMyTempString));
	    MyAddToBuffer (stMyTempString);
	    MyAddToBuffer (" ");
    	
	    // Add the file time
	    GetTimeFormat (LOCALE_USER_DEFAULT, TIME_NOSECONDS, &stMySystemTime, 
	        NULL, stMyTempString, sizeof (stMyTempString));
	    MyAddToBuffer (stMyTempString);
	}
	
	CloseHandle (stMyFile);
    }
    
    //
    // Line 6: Operating System: Windows 95
    //
    MyAddToBuffer ("\r\nOperating System: ");
    switch (gProgram.operatingSystem)
    {
    	case UNKNOWN_OS:
    	    MyAddToBuffer ("Unknown Windows version\r\n");
    	    break;
    	case WIN_95:
    	    MyAddToBuffer ("Windows 95\r\n");
    	    break;
	case WIN_95_OSR2:
    	    MyAddToBuffer ("Windows 95 Service Pack 2\r\n");
    	    break;
	case WIN_98:
    	    MyAddToBuffer ("Windows 98\r\n");
    	    break;
	case WIN_98_SE:
    	    MyAddToBuffer ("Windows 98 Second Edition\r\n");
    	    break;
	case WIN_ME:
    	    MyAddToBuffer ("Windows Me\r\n");
    	    break;
	case WIN_NT:
    	    MyAddToBuffer ("Windows NT\r\n");
    	    break;
	case WIN_2000:
    	    MyAddToBuffer ("Windows 2000\r\n");
    	    break;
	case WIN_XP:
    	    MyAddToBuffer ("Windows XP\r\n");
    	    break;
	case WIN_NEWER:
    	    MyAddToBuffer ("After Windows XP\r\n");
    	    break;
    	default:
    	    MyAddToBuffer ("Bad OS Value (%d)\r\n", gProgram.operatingSystem);
    	    break;
    	
    } // switch
    
    // 
    // Line 7: JVM: Ready Built-in JRE (1.4.2 or later)
    //
    MyAddToBuffer ("JVM: ");
    switch (gProperties.JVMType)
    {
	case JRE_131:
	    MyAddToBuffer ("Ready JRE 1.3.1\r\n");
	    break;
	case JRE_BUILT_IN:
	    MyAddToBuffer ("Ready Built-in JRE (1.4.2 or later)\r\n");
	    break;
	case JRE_IN_JRE_DIR:
	    MyAddToBuffer ("Ready User-installed JRE\r\n");
	    break;
	case JDK_IN_JRE_DIR:
	    MyAddToBuffer ("Ready User-installed JDK\r\n");
	    break;
	case JRE_IN_REGISTRY:
	    MyAddToBuffer ("Ready System JRE\r\n");
	    break;
	case JDK_IN_REGISTRY:
	    MyAddToBuffer ("Ready System JDK\r\n");
	    break;
    } // switch            
    
    // 
    // Line 8: "assert": enabled
    //
    if (gProperties.oldJavaCompile)
    {
    	MyAddToBuffer ("\"assert\" Statements: disabled\r\n");
    }
    else
    {
    	MyAddToBuffer ("\"assert\" Statements: enabled\r\n");
    }    	
} // MyGetEnvironmentInfo
Exemplo n.º 15
0
STDMETHODIMP CBaseMuxerFilter::QueryPreferredFormat(GUID* pFormat)
{
	return GetTimeFormat(pFormat);
}
Exemplo n.º 16
0
LONG
SecMgrpDlgProcInitReport(
    HWND hwnd,
    UINT wMsg,
    DWORD wParam,
    LONG lParam
    )
/*++

Routine Description:

    This function is the dialog process for the dialog that informs the user
    that a new report file is being initialized.  It asks the user to be patient
    and then goes about notifying all the smedlys of the new report file.

Arguments

    None - all information is available in module-wide variables.


Return Values:


--*/
{
    HWND
        Button;

    HCURSOR
        hCursor;

    DWORD
        StringId,
        OutputLineLength;

    BOOL
        Result;

    TCHAR
        OutputLine[SECMGR_MAX_RESOURCE_STRING_LENGTH];


    switch (wMsg) {

    case WM_INITDIALOG:

        if (!SecMgrpReportActive) {
            EndDialog(hwnd, 0);
            return(TRUE);
        }


        SetForegroundWindow(hwnd);
        ShowWindow(hwnd, SW_NORMAL);

        //
        // Change the cursor to an hourglass
        //

        hCursor = SetCursor( LoadCursor(NULL, IDC_WAIT) );
        ShowCursor(TRUE);


        //
        // put header information in the new report file
        //


        //
        // time
        //

        LoadString( SecMgrphInstance,
                    SECMGRP_STRING_REPORT_TIME,
                    OutputLine,
                    sizeof(OutputLine)
                    );
        SecMgrPrintReportLine( OutputLine );

        OutputLineLength = GetTimeFormat( (SHORT)NtCurrentTeb()->CurrentLocale,
                                          TIME_FORCE24HOURFORMAT,     // Flags
                                          NULL,                       // use current time
                                          NULL,                       // Format for current locale
                                          OutputLine,                 // Receives time string
                                          sizeof(OutputLine)
                                          );
        ASSERT(OutputLineLength != 0);
        SecMgrPrintReportLine( OutputLine );


        //
        // Date
        //

        LoadString( SecMgrphInstance,
                    SECMGRP_STRING_REPORT_DATE,
                    OutputLine,
                    sizeof(OutputLine)
                    );
        SecMgrPrintReportLine( OutputLine );


        OutputLineLength = GetDateFormat( (SHORT)NtCurrentTeb()->CurrentLocale,
                                          0,                          // Flags
                                          NULL,                       // use current date
                                          NULL,                       // Format for current locale
                                          OutputLine,                 // Receives date string
                                          sizeof(OutputLine)
                                          );
        ASSERT(OutputLineLength != 0);
        SecMgrPrintReportLine( OutputLine );


        //
        // Machine
        //

        LoadString( SecMgrphInstance,
                    SECMGRP_STRING_REPORT_MACHINE,
                    OutputLine,
                    sizeof(OutputLine)
                    );
        SecMgrPrintReportLine( OutputLine );

        OutputLineLength = sizeof(OutputLine);
        Result = GetComputerName( OutputLine, &OutputLineLength );
        ASSERT(Result);
        SecMgrPrintReportLine( OutputLine );


        //
        // Security Level
        //

        SecMgrpReportSecurityLevel( SECMGRP_STRING_REPORT_LEVEL, SecMgrpCurrentLevel );



        SecMgrPrintReportLine( L"\n\n" );




        //
        // Now notify the smedlys
        // There are two passes.
        //      Pass 1 - Before we print out the summary list
        //      Pass 2 - After we print out the summary list
        //

        SecMgrpSmedlyReportFileChange( SecMgrpReportActive, 1 );    //Pass 1
        SecMgrpFillInItemList( TRUE, hwnd );
        SecMgrpSmedlyReportFileChange( SecMgrpReportActive, 2 );    //Pass 2

        //
        // That's it - we're done
        //

        EndDialog(hwnd, 0);
        return(TRUE);


    case WM_SYSCOMMAND:
        switch (wParam & 0xfff0) {
        case SC_CLOSE:
            EndDialog(hwnd, 0);
            return(TRUE);
        }

        return(FALSE);


    default:
        break;

    }

    return FALSE;
}
Exemplo n.º 17
0
extern "C" BOOL EditPrint(HWND hwnd,LPCWSTR pszDocTitle,LPCWSTR pszPageFormat)
{

  // Don't print empty documents
  if (SendMessage(hwnd,SCI_GETLENGTH,0,0) == 0) {
    MsgBox(MBWARN,IDS_PRINT_EMPTY);
    return TRUE;
  }

  int startPos;
  int endPos;

  HDC hdc;

  RECT rectMargins;
  RECT rectPhysMargins;
  RECT rectSetup;
  POINT ptPage;
  POINT ptDpi;

  //RECT rectSetup;

  TEXTMETRIC tm;

  int headerLineHeight;
  HFONT fontHeader;

  int footerLineHeight;
  HFONT fontFooter;

  WCHAR dateString[MIDSZ_BUFFER] = { L'\0' };

  DOCINFO di = {sizeof(DOCINFO), nullptr, nullptr, nullptr, 0};

  int lengthDoc;
  int lengthDocMax;
  int lengthPrinted;

  struct Sci_RangeToFormat frPrint;

  int pageNum;
  BOOL printPage;

  WCHAR pageString[32] = { L'\0' };

  HPEN pen;
  HPEN penOld;

  PRINTDLG pdlg = { sizeof(PRINTDLG), nullptr, nullptr, nullptr, nullptr, 
    0, 0, 0, 0, 0, 0, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr };
  pdlg.hwndOwner = GetParent(hwnd);
  pdlg.hInstance = g_hInstance;
  pdlg.Flags = PD_USEDEVMODECOPIES | PD_ALLPAGES | PD_RETURNDC;
  pdlg.nFromPage = 1;
  pdlg.nToPage = 1;
  pdlg.nMinPage = 1;
  pdlg.nMaxPage = 0xffffU;
  pdlg.nCopies = 1;
  pdlg.hDC = nullptr;
  pdlg.hDevMode = hDevMode;
  pdlg.hDevNames = hDevNames;

  startPos = (int)SendMessage(hwnd,SCI_GETSELECTIONSTART,0,0);
  endPos = (int)SendMessage(hwnd,SCI_GETSELECTIONEND,0,0);

  if (startPos == endPos) {
    pdlg.Flags |= PD_NOSELECTION;
  } else {
    pdlg.Flags |= PD_SELECTION;
  }

  // |= 0 - Don't display dialog box, just use the default printer and options
  pdlg.Flags |= (flagPrintFileAndLeave == 1) ? PD_RETURNDEFAULT : 0;

  if (!PrintDlg(&pdlg)) {
    return TRUE; // False means error...
  }

  hDevMode = pdlg.hDevMode;
  hDevNames = pdlg.hDevNames;

  hdc = pdlg.hDC;

  // Get printer resolution
  ptDpi.x = GetDeviceCaps(hdc, LOGPIXELSX);    // dpi in X direction
  ptDpi.y = GetDeviceCaps(hdc, LOGPIXELSY);    // dpi in Y direction

  // Start by getting the physical page size (in device units).
  ptPage.x = GetDeviceCaps(hdc, PHYSICALWIDTH);   // device units
  ptPage.y = GetDeviceCaps(hdc, PHYSICALHEIGHT);  // device units

  // Get the dimensions of the unprintable
  // part of the page (in device units).
  rectPhysMargins.left = GetDeviceCaps(hdc, PHYSICALOFFSETX);
  rectPhysMargins.top = GetDeviceCaps(hdc, PHYSICALOFFSETY);

  // To get the right and lower unprintable area,
  // we take the entire width and height of the paper and
  // subtract everything else.
  rectPhysMargins.right = ptPage.x            // total paper width
                          - GetDeviceCaps(hdc, HORZRES) // printable width
                          - rectPhysMargins.left;        // left unprintable margin

  rectPhysMargins.bottom = ptPage.y            // total paper height
                           - GetDeviceCaps(hdc, VERTRES)  // printable height
                           - rectPhysMargins.top;        // right unprintable margin

  // At this point, rectPhysMargins contains the widths of the
  // unprintable regions on all four sides of the page in device units.

  // Take in account the page setup given by the user (if one value is not null)
  if (pagesetupMargin.left != 0 || pagesetupMargin.right != 0 ||
          pagesetupMargin.top != 0 || pagesetupMargin.bottom != 0) {

    // Convert the hundredths of millimeters (HiMetric) or
    // thousandths of inches (HiEnglish) margin values
    // from the Page Setup dialog to device units.
    // (There are 2540 hundredths of a mm in an inch.)

    WCHAR localeInfo[3];
    GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_IMEASURE, localeInfo, 3);

    if (localeInfo[0] == L'0') {  // Metric system. L'1' is US System
      rectSetup.left = MulDiv (pagesetupMargin.left, ptDpi.x, 2540);
      rectSetup.top = MulDiv (pagesetupMargin.top, ptDpi.y, 2540);
      rectSetup.right  = MulDiv(pagesetupMargin.right, ptDpi.x, 2540);
      rectSetup.bottom  = MulDiv(pagesetupMargin.bottom, ptDpi.y, 2540);
    } else {
      rectSetup.left  = MulDiv(pagesetupMargin.left, ptDpi.x, 1000);
      rectSetup.top  = MulDiv(pagesetupMargin.top, ptDpi.y, 1000);
      rectSetup.right  = MulDiv(pagesetupMargin.right, ptDpi.x, 1000);
      rectSetup.bottom  = MulDiv(pagesetupMargin.bottom, ptDpi.y, 1000);
    }

    // Dont reduce margins below the minimum printable area
    rectMargins.left  = max(rectPhysMargins.left, rectSetup.left);
    rectMargins.top  = max(rectPhysMargins.top, rectSetup.top);
    rectMargins.right  = max(rectPhysMargins.right, rectSetup.right);
    rectMargins.bottom  = max(rectPhysMargins.bottom, rectSetup.bottom);
  } else {
    rectMargins.left  = rectPhysMargins.left;
    rectMargins.top  = rectPhysMargins.top;
    rectMargins.right  = rectPhysMargins.right;
    rectMargins.bottom  = rectPhysMargins.bottom;
  }

  // rectMargins now contains the values used to shrink the printable
  // area of the page.

  // Convert device coordinates into logical coordinates
  DPtoLP(hdc, (LPPOINT)&rectMargins, 2);
  DPtoLP(hdc, (LPPOINT)&rectPhysMargins, 2);

  // Convert page size to logical units and we're done!
  DPtoLP(hdc, (LPPOINT) &ptPage, 1);

  headerLineHeight = MulDiv(8,ptDpi.y, 72);
  fontHeader = CreateFont(headerLineHeight,
                          0, 0, 0,
                          FW_BOLD,
                          0,
                          0,
                          0, 0, 0,
                          0, 0, 0,
                          L"Arial");
  SelectObject(hdc, fontHeader);
  GetTextMetrics(hdc, &tm);
  headerLineHeight = tm.tmHeight + tm.tmExternalLeading;

  if (iPrintHeader == 3)
    headerLineHeight = 0;

  footerLineHeight = MulDiv(7,ptDpi.y, 72);
  fontFooter = CreateFont(footerLineHeight,
                          0, 0, 0,
                          FW_NORMAL,
                          0,
                          0,
                          0, 0, 0,
                          0, 0, 0,
                          L"Arial");
  SelectObject(hdc, fontFooter);
  GetTextMetrics(hdc, &tm);
  footerLineHeight = tm.tmHeight + tm.tmExternalLeading;

  if (iPrintFooter == 1)
    footerLineHeight = 0;

  di.lpszDocName = pszDocTitle;
  di.lpszOutput = nullptr;
  di.lpszDatatype = nullptr;
  di.fwType = 0;
  if (StartDoc(hdc, &di) < 0) {
    DeleteDC(hdc);
    if (fontHeader)
      DeleteObject(fontHeader);
    if (fontFooter)
      DeleteObject(fontFooter);
    return FALSE;
  }

  // Get current date...
  SYSTEMTIME st;
  GetLocalTime(&st);
  GetDateFormat(LOCALE_USER_DEFAULT,DATE_SHORTDATE,&st,nullptr,dateString,MIDSZ_BUFFER);

  // Get current time...
  if (iPrintHeader == 0)
  {
    WCHAR timeString[SMALL_BUFFER] = { L'\0' };
    GetTimeFormat(LOCALE_USER_DEFAULT,TIME_NOSECONDS,&st,nullptr,timeString,SMALL_BUFFER);
    StringCchCat(dateString,COUNTOF(dateString),L" ");
    StringCchCat(dateString,COUNTOF(dateString),timeString);
  }

  // Set print color mode
  int printColorModes[5] = {
    SC_PRINT_NORMAL,
    SC_PRINT_INVERTLIGHT,
    SC_PRINT_BLACKONWHITE,
    SC_PRINT_COLOURONWHITE,
    SC_PRINT_COLOURONWHITEDEFAULTBG };
  SendMessage(hwnd,SCI_SETPRINTCOLOURMODE,printColorModes[iPrintColor],0);

  // Set print zoom...
  SendMessage(hwnd,SCI_SETPRINTMAGNIFICATION,(WPARAM)iPrintZoom,0);

  lengthDoc = (int)SendMessage(hwnd,SCI_GETLENGTH,0,0);
  lengthDocMax = lengthDoc;
  lengthPrinted = 0;

  // Requested to print selection
  if (pdlg.Flags & PD_SELECTION) {
    if (startPos > endPos) {
      lengthPrinted = endPos;
      lengthDoc = startPos;
    } else {
      lengthPrinted = startPos;
      lengthDoc = endPos;
    }

    if (lengthPrinted < 0)
      lengthPrinted = 0;
    if (lengthDoc > lengthDocMax)
      lengthDoc = lengthDocMax;
  }

  // We must substract the physical margins from the printable area
  frPrint.hdc = hdc;
  frPrint.hdcTarget = hdc;
  frPrint.rc.left = rectMargins.left - rectPhysMargins.left;
  frPrint.rc.top = rectMargins.top - rectPhysMargins.top;
  frPrint.rc.right = ptPage.x - rectMargins.right - rectPhysMargins.left;
  frPrint.rc.bottom = ptPage.y - rectMargins.bottom - rectPhysMargins.top;
  frPrint.rcPage.left = 0;
  frPrint.rcPage.top = 0;
  frPrint.rcPage.right = ptPage.x - rectPhysMargins.left - rectPhysMargins.right - 1;
  frPrint.rcPage.bottom = ptPage.y - rectPhysMargins.top - rectPhysMargins.bottom - 1;
  frPrint.rc.top += headerLineHeight + headerLineHeight / 2;
  frPrint.rc.bottom -= footerLineHeight + footerLineHeight / 2;
  // Print each page
  pageNum = 1;

  while (lengthPrinted < lengthDoc) {
    printPage = (!(pdlg.Flags & PD_PAGENUMS) ||
                 (pageNum >= pdlg.nFromPage) && (pageNum <= pdlg.nToPage));

    StringCchPrintf(pageString,COUNTOF(pageString),pszPageFormat,pageNum);

    if (printPage) {

      // Show wait cursor...
      SendMessage(g_hwndEdit, SCI_SETCURSOR, (WPARAM)SC_CURSORWAIT, 0);

      // Display current page number in Statusbar
      StatusUpdatePrintPage(pageNum);

      StartPage(hdc);

      SetTextColor(hdc, RGB(0,0,0));
      SetBkColor(hdc, RGB(0xFF, 0xFF, 0xFF));
      SelectObject(hdc, fontHeader);
      UINT ta = SetTextAlign(hdc, TA_BOTTOM);
      RECT rcw = {frPrint.rc.left, frPrint.rc.top - headerLineHeight - headerLineHeight / 2,
                  frPrint.rc.right, frPrint.rc.top - headerLineHeight / 2};
      rcw.bottom = rcw.top + headerLineHeight;

      if (iPrintHeader < 3)
      {
        ExtTextOut(hdc, frPrint.rc.left + 5, frPrint.rc.top - headerLineHeight / 2,
                      /*ETO_OPAQUE*/0, &rcw, pszDocTitle,
                      lstrlen(pszDocTitle), nullptr);
      }

      // Print date in header
      if (iPrintHeader == 0 || iPrintHeader == 1)
      {
        SIZE sizeInfo;
        SelectObject(hdc,fontFooter);
        GetTextExtentPoint32(hdc,dateString,StringCchLenW(dateString,COUNTOF(dateString)),&sizeInfo);
        ExtTextOut(hdc, frPrint.rc.right - 5 - sizeInfo.cx, frPrint.rc.top - headerLineHeight / 2,
                      /*ETO_OPAQUE*/0, &rcw, dateString,
                      StringCchLenW(dateString,COUNTOF(dateString)), nullptr);
      }

      if (iPrintHeader < 3)
      {
        SetTextAlign(hdc, ta);
        pen = CreatePen(0, 1, RGB(0,0,0));
        penOld = (HPEN)SelectObject(hdc, pen);
        MoveToEx(hdc, frPrint.rc.left, frPrint.rc.top - headerLineHeight / 4, nullptr);
        LineTo(hdc, frPrint.rc.right, frPrint.rc.top - headerLineHeight / 4);
        SelectObject(hdc, penOld);
        DeleteObject(pen);
      }
    }

    frPrint.chrg.cpMin = lengthPrinted;
    frPrint.chrg.cpMax = lengthDoc;

    lengthPrinted = (int)SendMessage(hwnd, SCI_FORMATRANGE, printPage, (LPARAM)&frPrint);

    if (printPage) {
      SetTextColor(hdc, RGB(0,0,0));
      SetBkColor(hdc, RGB(0xFF, 0xFF, 0xFF));
      SelectObject(hdc, fontFooter);
      UINT ta = SetTextAlign(hdc, TA_TOP);
      RECT rcw = {frPrint.rc.left, frPrint.rc.bottom + footerLineHeight / 2,
                  frPrint.rc.right, frPrint.rc.bottom + footerLineHeight + footerLineHeight / 2};

      if (iPrintFooter == 0)
      {
        SIZE sizeFooter;
        GetTextExtentPoint32(hdc,pageString,StringCchLenW(pageString,COUNTOF(pageString)),&sizeFooter);
        ExtTextOut(hdc, frPrint.rc.right - 5 - sizeFooter.cx, frPrint.rc.bottom + footerLineHeight / 2,
                      /*ETO_OPAQUE*/0, &rcw, pageString,
                      StringCchLenW(pageString,COUNTOF(pageString)), nullptr);

        SetTextAlign(hdc, ta);
        pen = ::CreatePen(0, 1, RGB(0,0,0));
        penOld = (HPEN)SelectObject(hdc, pen);
        SetBkColor(hdc, RGB(0,0,0));
        MoveToEx(hdc, frPrint.rc.left, frPrint.rc.bottom + footerLineHeight / 4, nullptr);
        LineTo(hdc, frPrint.rc.right, frPrint.rc.bottom + footerLineHeight / 4);
        SelectObject(hdc, penOld);
        DeleteObject(pen);
      }

      EndPage(hdc);
    }
    pageNum++;

    if ((pdlg.Flags & PD_PAGENUMS) && (pageNum > pdlg.nToPage))
      break;
  }

  SendMessage(hwnd,SCI_FORMATRANGE, FALSE, 0);

  EndDoc(hdc);
  DeleteDC(hdc);
  if (fontHeader)
    DeleteObject(fontHeader);
  if (fontFooter)
    DeleteObject(fontFooter);

  // Reset Statusbar to default mode
  StatusSetSimple(g_hwndStatus,FALSE);

  // Remove wait cursor...
  { POINT pt; SendMessage(g_hwndEdit, SCI_SETCURSOR, (WPARAM)SC_CURSORNORMAL, 0); GetCursorPos(&pt); SetCursorPos(pt.x, pt.y); }

  return TRUE;
}
Exemplo n.º 18
0
void DrawIdleScreen(void)
{
  unsigned char msd;
  unsigned char lsd;

  unsigned char Row = 6;
  unsigned char Col = 0;

  int Minutes;

  /* display hour */
  int Hour = GetRTCHOUR();

  /* if required convert to twelve hour format */
  if ( GetTimeFormat() == TWELVE_HOUR )
  {
    if ( Hour == 0 )
    {
      Hour = 12;
    }
    else if ( Hour > 12 )
    {
      Hour -= 12;
    }
  }

  msd = Hour / 10;
  lsd = Hour % 10;

  /* if first digit is zero then leave location blank */
  if ( msd != 0 )
  {
    WriteTimeDigit(msd,Row,Col,LEFT_JUSTIFIED);
  }
  Col += 1;
  WriteTimeDigit(lsd,Row,Col,RIGHT_JUSTIFIED);
  Col += 2;

  /* the colon takes the first 5 bits on the byte*/
  WriteTimeColon(Row,Col,RIGHT_JUSTIFIED);
  Col+=1;

  /* display minutes */
  Minutes = GetRTCMIN();
  msd = Minutes / 10;
  lsd = Minutes % 10;
  WriteTimeDigit(msd,Row,Col,RIGHT_JUSTIFIED);
  Col += 2;
  WriteTimeDigit(lsd,Row,Col,LEFT_JUSTIFIED);

  if ( nvDisplaySeconds )
  {
    /* the final colon's spacing isn't quite the same */
    int Seconds = GetRTCSEC();
    msd = Seconds / 10;
    lsd = Seconds % 10;

    Col +=2;
    WriteTimeColon(Row,Col,LEFT_JUSTIFIED);
    Col += 1;
    WriteTimeDigit(msd,Row,Col,LEFT_JUSTIFIED);
    Col += 1;
    WriteTimeDigit(lsd,Row,Col,RIGHT_JUSTIFIED);

  }
  else /* now things starting getting fun....*/
  {
    DisplayAmPm();

    if ( QueryBluetoothOn() == 0 )
    {
      CopyColumnsIntoMyBuffer(pBluetoothOffIdlePageIcon,
                              IDLE_PAGE_ICON_STARTING_ROW,
                              IDLE_PAGE_ICON_SIZE_IN_ROWS,
                              IDLE_PAGE_ICON_STARTING_COL,
                              IDLE_PAGE_ICON_SIZE_IN_COLS);
    }
    else if ( QueryPhoneConnected() == 0 )
    {
      CopyColumnsIntoMyBuffer(pPhoneDisconnectedIdlePageIcon,
                              IDLE_PAGE_ICON_STARTING_ROW,
                              IDLE_PAGE_ICON_SIZE_IN_ROWS,
                              IDLE_PAGE_ICON_STARTING_COL,
                              IDLE_PAGE_ICON_SIZE_IN_COLS);
    }
    else
    {
      if ( QueryBatteryCharging() )
      {
        CopyColumnsIntoMyBuffer(pBatteryChargingIdlePageIconType2,
                                IDLE_PAGE_ICON2_STARTING_ROW,
                                IDLE_PAGE_ICON2_SIZE_IN_ROWS,
                                IDLE_PAGE_ICON2_STARTING_COL,
                                IDLE_PAGE_ICON2_SIZE_IN_COLS);
      }
      else
      {
        unsigned int bV = 3500;

        if ( bV < 3500 )
        {
          CopyColumnsIntoMyBuffer(pLowBatteryIdlePageIconType2,
                                  IDLE_PAGE_ICON2_STARTING_ROW,
                                  IDLE_PAGE_ICON2_SIZE_IN_ROWS,
                                  IDLE_PAGE_ICON2_STARTING_COL,
                                  IDLE_PAGE_ICON2_SIZE_IN_COLS);
        }
        else
        {
          DisplayDayOfWeek();
          DisplayDate();
        }
      }
    }
  }
}
Exemplo n.º 19
0
STDMETHODIMP CStreamSwitcherPassThru::GetTimeFormat(GUID* pFormat)
{
    CallPeerSeeking(GetTimeFormat(pFormat));
}
Exemplo n.º 20
0
//================================================================================================
//-------------+++--> Format T-Clock's OutPut String From Current Date, Time, & System Information:
unsigned MakeFormat(char buf[FORMAT_MAX_SIZE], const char* fmt, SYSTEMTIME* pt, int beat100)   //------------------+++-->
{
	const char* bufend = buf+FORMAT_MAX_SIZE;
	const char* pos;
	char* out = buf;
	ULONGLONG TickCount = 0;
	
	while(*fmt) {
		if(*fmt == '"') {
			for(++fmt; *fmt&&*fmt!='"'; )
				*out++ = *fmt++;
			if(*fmt) ++fmt;
			continue;
		}
		if(*fmt=='\\' && fmt[1]=='n') {
			fmt+=2;
			*out++='\n';
		}
		/// for testing
		else if(*fmt == 'S' && fmt[1] == 'S' && (fmt[2] == 'S' || fmt[2] == 's')) {
			fmt += 3;
			out += api.WriteFormatNum(out, (int)pt->wSecond, 2, 0);
			*out++ = '.';
			out += api.WriteFormatNum(out, (int)pt->wMilliseconds, 3, 0);
		}
		
		else if(*fmt == 'y' && fmt[1] == 'y') {
			int len;
			len = 2;
			if(*(fmt + 2) == 'y' && *(fmt + 3) == 'y') len = 4;
			
			out += api.WriteFormatNum(out, (len==2)?(int)pt->wYear%100:(int)pt->wYear, len, 0);
			fmt += len;
		} else if(*fmt == 'm') {
			if(*(fmt + 1) == 'm' && *(fmt + 2) == 'e') {
				*out++ = m_MonthEng[pt->wMonth-1][0];
				*out++ = m_MonthEng[pt->wMonth-1][1];
				*out++ = m_MonthEng[pt->wMonth-1][2];
				fmt += 3;
			} else if(fmt[1] == 'm' && fmt[2] == 'm') {
				if(*(fmt + 3) == 'm') {
					fmt += 4;
					for(pos=m_MonthLong; *pos; ) *out++=*pos++;
				} else {
					fmt += 3;
					for(pos=m_MonthShort; *pos; ) *out++=*pos++;
				}
			} else {
				if(fmt[1] == 'm') {
					fmt += 2;
					*out++ = (char)((int)pt->wMonth / 10) + '0';
				} else {
					++fmt;
					if(pt->wMonth > 9)
						*out++ = (char)((int)pt->wMonth / 10) + '0';
				}
				*out++ = (char)((int)pt->wMonth % 10) + '0';
			}
		} else if(*fmt == 'a' && fmt[1] == 'a' && fmt[2] == 'a') {
			if(*(fmt + 3) == 'a') {
				fmt += 4;
				for(pos=m_DayOfWeekLong; *pos; ) *out++=*pos++;
			} else {
				fmt += 3;
				for(pos=m_DayOfWeekShort; *pos; ) *out++=*pos++;
			}
		} else if(*fmt=='d') {
			if(fmt[1]=='d' && fmt[2]=='e'){
				fmt+=3;
				for(pos=m_DayOfWeekEng[pt->wDayOfWeek]; *pos; ) *out++=*pos++;
			}else if(fmt[1]=='d' && fmt[2]=='d') {
				fmt+=3;
				if(*fmt=='d'){
					++fmt;
					pos=m_DayOfWeekLong;
				}else{
					pos=m_DayOfWeekShort;
				}
				for(; *pos; ) *out++=*pos++;
			}else{
				if(fmt[1]=='d') {
					fmt+=2;
					*out++ = (char)((int)pt->wDay / 10) + '0';
				}else{
					++fmt;
					if(pt->wDay > 9)
						*out++ = (char)((int)pt->wDay / 10) + '0';
				}
				*out++ = (char)((int)pt->wDay % 10) + '0';
			}
		} else if(*fmt=='h') {
			int hour = pt->wHour;
			while(hour >= 12) // faster than mod 12 if "hour" <= 24
				hour -= 12;
			if(!hour && !g_bHourZero)
				hour = 12;
			if(fmt[1] == 'h') {
				fmt += 2;
				*out++ = (char)(hour / 10) + '0';
			} else {
				++fmt;
				if(hour > 9)
					*out++ = (char)(hour / 10) + '0';
			}
			*out++ = (char)(hour % 10) + '0';
		} else if(*fmt=='H') {
			if(fmt[1] == 'H') {
				fmt += 2;
				*out++ = (char)(pt->wHour / 10) + '0';
			} else {
				++fmt;
				if(pt->wHour > 9)
					*out++ = (char)(pt->wHour / 10) + '0';
			}
			*out++ = (char)(pt->wHour % 10) + '0';
		} else if((*fmt=='w'||*fmt=='W') && (fmt[1]=='+'||fmt[1]=='-')) {
			char is_12h = (*fmt == 'w');
			char is_negative = (*++fmt == '-');
			int hour = 0;
			for(; *++fmt<='9'&&*fmt>='0'; ){
				hour *= 10;
				hour += *fmt-'0';
			}
			if(is_negative) hour = -hour;
			hour = (pt->wHour + hour)%24;
			if(hour < 0) hour += 24;
			if(is_12h){
				while(hour >= 12) // faster than mod 12 if "hour" <= 24
					hour -= 12;
				if(!hour && !g_bHourZero)
					hour = 12;
			}
			*out++ = (char)(hour / 10) + '0';
			*out++ = (char)(hour % 10) + '0';
		} else if(*fmt == 'n') {
			if(fmt[1] == 'n') {
				fmt += 2;
				*out++ = (char)((int)pt->wMinute / 10) + '0';
			} else {
				++fmt;
				if(pt->wMinute > 9)
					*out++ = (char)((int)pt->wMinute / 10) + '0';
			}
			*out++ = (char)((int)pt->wMinute % 10) + '0';
		} else if(*fmt == 's') {
			if(fmt[1] == 's') {
				fmt += 2;
				*out++ = (char)((int)pt->wSecond / 10) + '0';
			} else {
				++fmt;
				if(pt->wSecond > 9)
					*out++ = (char)((int)pt->wSecond / 10) + '0';
			}
			*out++ = (char)((int)pt->wSecond % 10) + '0';
		} else if(*fmt == 't' && fmt[1] == 't') {
			fmt += 2;
			if(pt->wHour < 12) pos = m_AM; else pos = m_PM;
			while(*pos) *out++ = *pos++;
		} else if(*fmt == 'A' && fmt[1] == 'M') {
			if(fmt[2] == '/' &&
			   fmt[3] == 'P' && fmt[4] == 'M') {
				if(pt->wHour < 12) *out++ = 'A'; //--+++--> 2010 - Noon / MidNight Decided Here!
				else *out++ = 'P';
				*out++ = 'M'; fmt += 5;
			} else if(fmt[2] == 'P' && fmt[3] == 'M') {
				fmt += 4;
				if(pt->wHour < 12) pos = m_AM; else pos = m_PM;
				while(*pos) *out++ = *pos++;
			} else *out++ = *fmt++;
		} else if(*fmt == 'a' && fmt[1] == 'm' && fmt[2] == '/' &&
				  fmt[3] == 'p' && fmt[4] == 'm') {
			if(pt->wHour < 12) *out++ = 'a';
			else *out++ = 'p';
			*out++ = 'm'; fmt += 5;
		}
		// internet time
		else if(*fmt == '@' && fmt[1] == '@' && fmt[2] == '@') {
			fmt += 3;
			*out++ = '@';
			*out++ = (char)(beat100 / 10000) + '0';
			*out++ = (char)((beat100 % 10000) / 1000) + '0';
			*out++ = (char)((beat100 % 1000) / 100) + '0';
			if(*fmt=='.' && fmt[1]=='@') {
				fmt += 2;
				*out++ = '.';
				*out++ = (char)((beat100 % 100) / 10) + '0';
				if(*fmt=='@'){
					++fmt;
					*out++ = (char)((beat100 % 10)) + '0';
				}
			}
		}
		// alternate calendar
		else if(*fmt == 'Y' && m_AltYear > -1) {
			int n = 1;
			while(*fmt == 'Y') { n *= 10; ++fmt; }
			if(n < m_AltYear) {
				n = 1; while(n < m_AltYear) n *= 10;
			}
			for(;;) {
				*out++ = (char)((m_AltYear % n) / (n/10)) + '0';
				if(n == 10) break;
				n /= 10;
			}
		} else if(*fmt == 'g') {
			for(pos=m_EraStr; *pos&&*fmt=='g'; ){
				char* p2 = CharNextExA(m_codepage, pos, 0);
				while(pos != p2) *out++ = *pos++;
				++fmt;
			}
			while(*fmt == 'g') fmt++;
		}
		
		else if(*fmt == 'L' && strncmp(fmt, "LDATE", 5) == 0) {
			GetDateFormat(LOCALE_USER_DEFAULT,
						  DATE_LONGDATE, pt, NULL, out, (int)(bufend-out));
			for(; *out; ++out);
			fmt += 5;
		}
		
		else if(*fmt == 'D' && strncmp(fmt, "DATE", 4) == 0) {
			GetDateFormat(LOCALE_USER_DEFAULT,
						  DATE_SHORTDATE, pt, NULL, out, (int)(bufend-out));
			for(; *out; ++out);
			fmt += 4;
		}
		
		else if(*fmt == 'T' && strncmp(fmt, "TIME", 4) == 0) {
			GetTimeFormat(LOCALE_USER_DEFAULT,
						  0, pt, NULL, out, (int)(bufend-out));
			for(; *out; ++out);
			fmt += 4;
		} else if(*fmt == 'S') { // uptime
			int width, padding, num;
			const char* old_fmt = ++fmt;
			char specifier = api.GetFormat(&fmt, &width, &padding);
			if(!TickCount) TickCount = api.GetTickCount64();
			switch(specifier){
			case 'd'://days
				num = (int)(TickCount/86400000);
				break;
			case 'a'://hours total
				num = (int)(TickCount/3600000);
				break;
			case 'h'://hours (max 24)
				num = (TickCount/3600000)%24;
				break;
			case 'n'://minutes
				num = (TickCount/60000)%60;
				break;
			case 's'://seconds
				num = (TickCount/1000)%60;
				break;
			case 'T':{// ST, uptime as h:mm:ss
				ULONGLONG past = TickCount/1000;
				int hour, minute;
				num = past%60; past /= 60;
				minute = past%60; past /= 60;
				hour = (int)past;
				
				out += api.WriteFormatNum(out, hour, width, padding);
				*out++ = ':';
				out += api.WriteFormatNum(out, minute, 2, 0);
				*out++ = ':';
				width = 2; padding = 0;
				break;}
			default:
				specifier = '\0';
				fmt = old_fmt;
				*out++ = 'S';
			}
			if(specifier)
				out += api.WriteFormatNum(out, num, width, padding);
		} else if(*fmt == 'W') { // Week-of-Year
			struct tm tmnow;
			time_t ts = time(NULL);
			localtime_r(&ts, &tmnow);
			++fmt;
			if(*fmt == 's') { // Week-Of-Year Starts Sunday
				out += strftime(out, bufend-out, "%U", &tmnow);
				++fmt;
			} else if(*fmt == 'm') { // Week-Of-Year Starts Monday
				out += strftime(out, bufend-out, "%W", &tmnow);
				++fmt;
			} else if(*fmt == 'i') { // ISO-8601 week (1st version by henriko.se, 2nd by White-Tiger)
				int wday,borderdays,week;
				for(;;){
					wday = (!tmnow.tm_wday?6:tmnow.tm_wday-1); // convert from Sun-Sat to Mon-Sun (0-5)
					borderdays = (tmnow.tm_yday + 7 - wday) % 7; // +7 to prevent it from going negative
					week = (tmnow.tm_yday + 6 - wday) / 7;
					if(borderdays >= 4){ // year starts with at least 4 days
						++week;
					} else if(!week){ // we're still in last year's week
						--tmnow.tm_year;
						tmnow.tm_mon = 11;
						tmnow.tm_mday = 31;
						tmnow.tm_isdst = -1;
						if(mktime(&tmnow)==-1){ // mktime magically updates tm_yday, tm_wday
							week = 1;
							break; // fail safe
						}
						tmnow.tm_mon = 0; // just to speed up the "if" below, since we know that it can't be week 1
						continue; // repeat (once)
					}
					if(tmnow.tm_mon==11 && tmnow.tm_mday>=29){ // end of year, could be week 1
						borderdays = 31 - tmnow.tm_mday + wday;
						if(borderdays < 3)
							week = 1;
					}
					break;
				}
				out += wsprintf(out,"%d",week);
				++fmt;
			} else if(*fmt == 'u') {
				int week = 1 + (tmnow.tm_yday + 6 - tmnow.tm_wday) / 7;
				out += wsprintf(out,"%d",week);
				++fmt;
			} else if(*fmt == 'w') { // SWN (Simple Week Number)
				out += wsprintf(out,"%d",1 + tmnow.tm_yday / 7);
				++fmt;
			}
		}
//================================================================================================
//======================================= JULIAN DATE Code ========================================
		else if(*fmt == 'J' && *(fmt + 1) == 'D') {
			double y, M, d, h, m, s, bc, JD;
			struct tm Julian;
			int id, is, i=0;
			char* szJulian;
			time_t UTC = time(NULL);
			
			gmtime_r(&UTC, &Julian);
			
			y = Julian.tm_year +1900;	// Year
			M = Julian.tm_mon +1;		// Month
			d = Julian.tm_mday;			// Day
			h = Julian.tm_hour;			// Hours
			m = Julian.tm_min;			// Minutes
			s = Julian.tm_sec;			// Seconds
			// This Handles the January 1, 4713 B.C up to
			bc = 100.0 * y + M - 190002.5; // Year 0 Part.
			JD = 367.0 * y;
			
			JD -= floor(7.0*(y + floor((M+9.0)/12.0))/4.0);
			JD += floor(275.0*M/9.0);
			JD += d;
			JD += (h + (m + s/60.0)/60.0)/24.0;
			JD += 1721013.5; // BCE 2 November 18 00:00:00.0 UT - Tuesday
			JD -= 0.5*bc/fabs(bc);
			JD += 0.5;
			
			szJulian = _fcvt(JD, 4, &id, &is); // Make it a String
			while(*szJulian) {
				if(i == id) { //--//-++-> id = Decimal Point Precision/Position
					*out++ = '.'; // ReInsert the Decimal Point Where it Belongs.
				} else {
					*out++ = *szJulian++; //--+++--> Done!
				}
				i++;
			}
			fmt +=2;
		}
//================================================================================================
//======================================= ORDINAL DATE Code =======================================
		else if(*fmt == 'O' && *(fmt + 1) == 'D') { //--------+++--> Ordinal Date UTC:
			char szOD[16] = {0};
			struct tm today;
			time_t UTC = time(NULL);
			char* od;
			
			gmtime_r(&UTC, &today);
			strftime(szOD, 16, "%Y-%j", &today);
			od = szOD;
			while(*od) *out++ = *od++;
			fmt +=2;
		}
		//==========================================================================
		else if(*fmt == 'O' && *(fmt + 1) == 'd') { //------+++--> Ordinal Date Local:
			char szOD[16] = {0};
			struct tm today;
			time_t ts = time(NULL);
			char* od;
			
			localtime_r(&ts, &today);
			strftime(szOD, 16, "%Y-%j", &today);
			od = szOD;
			while(*od) *out++ = *od++;
			fmt +=2;
		}
		//==========================================================================
		else if(*fmt == 'D' && strncmp(fmt, "DOY", 3) == 0) { //--+++--> Day-Of-Year:
			char szDoy[8] = {0};
			struct tm today;
			time_t ts = time(NULL);
			char* doy;
			
			localtime_r(&ts, &today);
			strftime(szDoy, 8, "%j", &today);
			doy = szDoy;
			while(*doy) *out++ = *doy++;
			fmt +=3;
		}
		//==========================================================================
		else if(*fmt == 'P' && strncmp(fmt, "POSIX", 5) == 0) { //-> Posix/Unix Time:
			char szPosix[16] = {0}; // This will Give the Number of Seconds That Have
			char* posix; //--+++--> Elapsed Since the Unix Epoch: 1970-01-01 00:00:00
			
			wsprintf(szPosix, "%ld", time(NULL));
			posix = szPosix;
			while(*posix) *out++ = *posix++;
			fmt +=5;
		}
		//==========================================================================
		else if(*fmt == 'T' && strncmp(fmt, "TZN", 3) == 0) { //--++-> TimeZone Name:
			#ifndef __GNUC__ /* forces us to link with msvcr100 */
			char szTZName[TZNAME_MAX] = {0};
			size_t lRet;
			char* tzn;
			int iDST;
			
			_get_daylight(&iDST);
			if(iDST) {
				_get_tzname(&lRet, szTZName, TZNAME_MAX, 1);
			} else {
				_get_tzname(&lRet, szTZName, TZNAME_MAX, 0);
			}
			
			tzn = szTZName;
			while(*tzn) *out++ = *tzn++;
			#endif
			fmt +=3;
		}
//=================================================================================================
		else {
			for(pos=CharNext(fmt); fmt!=pos; )  *out++=*fmt++;
		}
	}
	*out='\0';
	return (unsigned)(out-buf);
}
Exemplo n.º 21
0
void CLibraryFrame::RunLocalSearch(CQuerySearch* pSearch)
{
	CWaitCursor pCursor;

	pSearch->BuildWordList( true, true );

	CSingleLock oLock( &Library.m_pSection, TRUE );

	CAlbumFolder* pRoot = Library.GetAlbumRoot();
	if ( ! pRoot ) return;

	CAlbumFolder* pFolder = pRoot->GetFolderByURI( CSchema::uriSearchFolder );
	if ( pFolder == NULL )
	{
		pFolder = pRoot->AddFolder( CSchema::uriSearchFolder, L"Search Results" );
		if ( pFolder->m_pSchema != NULL )
		{
			int nColon = pFolder->m_pSchema->m_sTitle.Find( L':' );
			if ( nColon >= 0 )
				pFolder->m_sName = pFolder->m_pSchema->m_sTitle.Mid( nColon + 1 );
		}
	}
	else
	{
		// Get translated name of the default search folder
		// We will clear it, not others as user may want to keep several folders
		CString strFolderName;
		int nColon = pFolder->m_pSchema->m_sTitle.Find( L':' );
		if ( nColon >= 0 )
			strFolderName = pFolder->m_pSchema->m_sTitle.Mid( nColon + 1 );
		if ( ! strFolderName.IsEmpty() )
			pFolder	= pRoot->GetFolder( strFolderName );

		if ( pFolder == NULL )
		{
			pFolder = pRoot->AddFolder( CSchema::uriSearchFolder, L"Search Results" );
			if ( pFolder->m_pSchema != NULL && ! strFolderName.IsEmpty() )
				pFolder->m_sName = strFolderName;
		}
		else
			pFolder->Clear();
	}

	if ( pFolder->m_pSchema )
	{
		CString strDate, strTime;
		SYSTEMTIME pTime;

		GetLocalTime( &pTime );
		GetDateFormat( LOCALE_USER_DEFAULT, 0, &pTime, L"yyyy-MM-dd", strDate.GetBuffer( 64 ), 64 );
		GetTimeFormat( LOCALE_USER_DEFAULT, 0, &pTime, L"hh:mm tt", strTime.GetBuffer( 64 ), 64 );
		strDate.ReleaseBuffer(); strTime.ReleaseBuffer();

		CXMLElement* pOuter = pFolder->m_pSchema->Instantiate();
		CXMLElement* pInner = pOuter->AddElement( L"searchFolder" );
		pInner->AddAttribute( L"title", pFolder->m_sName );
		pInner->AddAttribute( L"content", pSearch->m_sSearch );
		pInner->AddAttribute( L"date", strDate );
		pInner->AddAttribute( L"time", strTime );
		pFolder->SetMetadata( pOuter );
		delete pOuter;
	}

	if ( CFileList* pFiles = Library.Search( pSearch, 0, TRUE ) )
	{
		for ( POSITION pos = pFiles->GetHeadPosition(); pos; )
		{
			const CLibraryFile* pFile = pFiles->GetNext( pos );

			if ( Settings.Search.SchemaTypes && pSearch->m_pSchema != NULL )
			{
				if ( ! pSearch->m_pSchema->FilterType( pFile->m_sName ) )
					pFile = NULL;
			}

			if ( pFile != NULL && pFile->IsAvailable() )
				pFolder->AddFile( const_cast< CLibraryFile* >( pFile ) );
		}

		delete pFiles;
	}

	oLock.Unlock();

	Update();
	Display( pFolder );
	GetParent()->PostMessage( WM_COMMAND, ID_VIEW_LIBRARY );
}
Exemplo n.º 22
0
///////////////////////////////////////////////////////////////////////////////////////////
//    Function:        NLSDlgProc
//
//    Description:    Message-processing function for text tab
//
//    Comments:        
//
///////////////////////////////////////////////////////////////////////////////////////////
INT_PTR CALLBACK NLSDlgProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    BOOL bProcessedMsg = TRUE;
    
    switch(uMsg)
    {
        case WM_INITDIALOG:
        {
            LVCOLUMN    lvcCol = {0};
            UINT        lcid = 0;
            LVFINDINFO  lvInfo = {0};
            int         iItem = 0;

            // load our own icon
            SendMessage(GetParent(hDlg), WM_SETICON, ICON_BIG, (LPARAM) (LoadIcon(g_hInst, MAKEINTRESOURCE(IDI_MAINICON))));

            // Create our list column  for the listview control
            g_hwndList = GetDlgItem(hDlg, IDC_LV_LCID);
            g_hDlg = hDlg;

            lvcCol.mask = LVCF_TEXT;
            LoadString(g_hRes, STR_LANGID, g_tcsTemp, MAX_STR);
            lvcCol.pszText = g_tcsTemp;
            ListView_InsertColumn(g_hwndList, COLUMN_LANGID, (LV_COLUMN *)&lvcCol);

            LoadString(g_hRes, STR_LANG, g_tcsTemp, MAX_STR);
            lvcCol.pszText = g_tcsTemp;
            ListView_InsertColumn(g_hwndList, COLUMN_LANGUAGE, (LV_COLUMN *)&lvcCol);

            LoadString(g_hRes, STR_NLANG, g_tcsTemp, MAX_STR);
            lvcCol.pszText = g_tcsTemp;
            ListView_InsertColumn(g_hwndList, COLUMN_NATIVELANG, (LV_COLUMN *)&lvcCol);

            LoadString(g_hRes, STR_NCOUNTRY, g_tcsTemp, MAX_STR);
            lvcCol.pszText = g_tcsTemp;
            ListView_InsertColumn(g_hwndList, COLUMN_NATIVECOUNTRYREGION, (LV_COLUMN *)&lvcCol);

            LoadString(g_hRes, STR_ACP, g_tcsTemp, MAX_STR);
            lvcCol.pszText = g_tcsTemp;
            ListView_InsertColumn(g_hwndList, COLUMN_ACP, (LV_COLUMN *)&lvcCol);

            LoadString(g_hRes, STR_OEMCP, g_tcsTemp, MAX_STR);
            lvcCol.pszText = g_tcsTemp;
            ListView_InsertColumn(g_hwndList, COLUMN_OEMCP, (LV_COLUMN *)&lvcCol);

            // fill out our listview control with available locales (supported ones).
            EnumSystemLocales(EnumLocalesProc, LCID_SUPPORTED);

            // Initialize formatting fields related to the selected locale in the listview
            InitNLSFields(hDlg, LOCALE_USER_DEFAULT);

            // Set the column width of the listview control.
            ListView_SetColumnWidth(g_hwndList, COLUMN_LANGID, LVSCW_AUTOSIZE_USEHEADER);
            ListView_SetColumnWidth(g_hwndList, COLUMN_LANGUAGE, LVSCW_AUTOSIZE_USEHEADER);
            ListView_SetColumnWidth(g_hwndList, COLUMN_NATIVELANG, LVSCW_AUTOSIZE_USEHEADER);
            ListView_SetColumnWidth(g_hwndList, COLUMN_NATIVECOUNTRYREGION, LVSCW_AUTOSIZE_USEHEADER);
            ListView_SetColumnWidth(g_hwndList, COLUMN_ACP, LVSCW_AUTOSIZE_USEHEADER);
            ListView_SetColumnWidth(g_hwndList, COLUMN_OEMCP, LVSCW_AUTOSIZE_USEHEADER);

            // Find user's current locale and select that item in the listview control.
            lcid = GetUserDefaultLCID();
            
            // Our list has all the LCIDs in 4 digits (0409) whereas GetUserDefaultLCID returs (409).
            if (lcid < 0x1000)
            {
                _sntprintf(g_tcsTemp,MAX_STR,TEXT("0%x"), lcid);
            }
            else
            {
                _sntprintf(g_tcsTemp,MAX_STR,TEXT("%x"), lcid);
            }

            lvInfo.flags = LVFI_STRING;
            lvInfo.psz = g_tcsTemp;

            iItem = ListView_FindItem(g_hwndList, 0, &lvInfo);
            ListView_SetItemState (g_hwndList, iItem, LVIS_FOCUSED | LVIS_SELECTED, 0x000F);
            ListView_EnsureVisible(g_hwndList, iItem, FALSE);

            // Set some of the extended styles of our list view (cool reports ;-)
            ListView_SetExtendedListViewStyle(g_hwndList, LVS_EX_FULLROWSELECT | LVS_EX_HEADERDRAGDROP | LVS_EX_GRIDLINES | LVS_EX_TWOCLICKACTIVATE);
        }
        break;

        case WM_NOTIFY:
            switch (((NMHDR *)lParam)->code)
            {
                case LVN_COLUMNCLICK:
                    {
                        NM_LISTVIEW nmv;
                        static int iLastSort = COLUMN_LANGID;
                        LPARAM lSortParam = -1;
                        LVFINDINFO lvInfo;
                        int         iItem;

                        // When a column is clicked we need to redo our sorting of preview table.

                        nmv = *(const NM_LISTVIEW *) lParam;

                        // We don't sort for native language and native country name (avoid confusion).
                        if ((nmv.iSubItem == COLUMN_NATIVELANG) || (nmv.iSubItem == COLUMN_NATIVECOUNTRYREGION))
                        {
                            break;
                        }

                        // If our last sorting was on a different column, we need to do more
                        // than simply reverting our sorting.
                        // Because of listview sorting limitations, we need to redo our list...
                        if (iLastSort != nmv.iSubItem)
                        {
                            // The list view sorting is based on a q-sort, we need to redo our list!
                            ListView_DeleteAllItems(g_hwndList);
                            g_iCounter  = 0;
                            EnumSystemLocales(EnumLocalesProc, LCID_SUPPORTED);

                            // Make sure the last selection remains active after sorting...
                            if (g_iCurLocale < 0x1000)
                            {
                                _sntprintf(g_tcsTemp,MAX_STR,TEXT("0%x"), g_iCurLocale);
                            }
                            else
                            {
                                _sntprintf(g_tcsTemp,MAX_STR,TEXT("%x"), g_iCurLocale);
                            }

                            lvInfo.flags = LVFI_STRING;
                            lvInfo.psz = g_tcsTemp;
                            iItem = ListView_FindItem(g_hwndList, 0, &lvInfo);
                            ListView_SetItemState (g_hwndList, iItem, LVIS_FOCUSED | LVIS_SELECTED, 0x000F);

                            // Update our flag for the last column sorted and set the sorting flag
                            iLastSort = nmv.iSubItem;
                            lSortParam = iLastSort;
                        }

                        // Do the actual sorting...
                        ListView_SortItems(g_hwndList, (PFNLVCOMPARE)CompareFunc, lSortParam);

                        // Make sure our selection is visible after the sorting!
                        ListView_EnsureVisible(g_hwndList, ListView_GetSelectionMark(g_hwndList), FALSE);
                    }
                    break;

                case LVN_ITEMCHANGED:   /* fall-through */
                case LVN_ITEMACTIVATE:
                    {
                        LPNM_LISTVIEW lpnmlv = (LPNM_LISTVIEW)lParam;
                        static    int iItem;
                        LVITEM    lvItem = {0};

                        // Item selection has been changed.
                        // Find the new langId and update our formatting fields...
                        if (iItem != lpnmlv->iItem)
                        {
                            iItem = lpnmlv->iItem;

                            lvItem.mask = LVIF_TEXT;
                            lvItem.iItem = iItem;
                            lvItem.pszText = g_tcsTemp;
                            lvItem.cchTextMax  = STR_LEN;
                            ListView_GetItem(g_hwndList, &lvItem);                                                    
                            g_iCurLocale = iConvertStrToInt(lvItem.pszText);
                            InitNLSFields(hDlg, g_iCurLocale);
                        }

                        // Show advanced data on the selected locale...
                        if (((NMHDR *)lParam)->code == LVN_ITEMACTIVATE)
                        {
                           bProcessedMsg = (DialogBox(g_hRes, MAKEINTRESOURCE(DLG_LCID), hDlg, LcidDlgProc) != -1);
                        }
                    }
                    break;
                }
                break;

                case WM_COMMAND:
                    switch(LOWORD(wParam))
                    {
                        case IDCANCEL: /* fall-through*/
                        case IDOK:
                            break;

                        case IDC_TIMEFORMAT:
                            {
                                if(HIWORD(wParam) == CBN_SELCHANGE)
                                {
                                    // Time formating selection has been changed.
                                    // Re-edit time
                                    HWND    hList = NULL;
                                    LRESULT index = 0;
                                    TCHAR    tcTemp[MAX_STR];

                                    hList = GetDlgItem(hDlg, IDC_TIMEFORMAT);

                                    if(NULL == hList)
                                    {
                                        bProcessedMsg = FALSE;
                                        break;
                                    }

                                    index = SendMessage(hList, CB_GETCURSEL, 0, 0);
                                    SendMessage(hList, CB_GETLBTEXT, index, (LPARAM) g_tcsTemp);
                                    GetTimeFormat(g_iCurLocale, 0, NULL, g_tcsTemp, tcTemp, MAX_STR);
                                    SetWindowText(GetDlgItem(hDlg, IDC_TIMESAMPLE), tcTemp);
                                }
                            }
                            break;

                        case IDC_SDATEFORMAT:
                            {
                                if(HIWORD(wParam) == CBN_SELCHANGE)
                                {
                                    // short date formating selection has been changed.
                                    // Re-edit short date
                                    HWND    hList = NULL;
                                    LRESULT index = 0;
                                    TCHAR    tcTemp[MAX_STR];

                                    hList = GetDlgItem(hDlg, IDC_SDATEFORMAT);
                                    
                                    if(NULL == hList)
                                    {
                                        bProcessedMsg = FALSE;
                                        break;
                                    }
                                    index = SendMessage(hList, CB_GETCURSEL, 0, 0);
                                    SendMessage(hList, CB_GETLBTEXT, index, (LPARAM) g_tcsTemp);
                                    GetDateFormat(g_iCurLocale, 0, NULL, g_tcsTemp, tcTemp, MAX_STR);
                                    SetWindowText(GetDlgItem(hDlg, IDC_SDATESAMPLE), tcTemp);
                                }
                            }
                            break;

                        case IDC_LDATEFORMAT:
                            {
                                if(HIWORD(wParam) == CBN_SELCHANGE)
                                {
                                    // long date formating selection has been changed.
                                    // Re-edit long date
                                    HWND    hList = NULL;
                                    LRESULT index = 0;
                                    TCHAR    tcTemp[MAX_STR];

                                    hList = GetDlgItem(hDlg, IDC_LDATEFORMAT);
                                    
                                    if(NULL == hList)
                                    {
                                        bProcessedMsg = FALSE;
                                        break;
                                    }

                                    index = SendMessage(hList, CB_GETCURSEL, 0, 0);
                                    SendMessage(hList, CB_GETLBTEXT, index, (LPARAM) g_tcsTemp);
                                    GetDateFormat(g_iCurLocale, 0, NULL, g_tcsTemp, tcTemp, MAX_STR);
                                    SetWindowText(GetDlgItem(hDlg, IDC_LDATESAMPLE), tcTemp);
                                }
                            }
                            break;
                    }
                    break;

        default:
            bProcessedMsg = FALSE;
    }
    
    return bProcessedMsg;
}
Exemplo n.º 23
0
Arquivo: log.c Projeto: schvin/unbound
void
log_vmsg(int pri, const char* type,
	const char *format, va_list args)
{
	char message[MAXSYSLOGMSGLEN];
	unsigned int* tid = (unsigned int*)ub_thread_key_get(logkey);
	time_t now;
#if defined(HAVE_STRFTIME) && defined(HAVE_LOCALTIME_R) 
	char tmbuf[32];
	struct tm tm;
#elif defined(UB_ON_WINDOWS)
	char tmbuf[128], dtbuf[128];
#endif
	(void)pri;
	vsnprintf(message, sizeof(message), format, args);
#ifdef HAVE_SYSLOG_H
	if(logging_to_syslog) {
		syslog(pri, "[%d:%x] %s: %s", 
			(int)getpid(), tid?*tid:0, type, message);
		return;
	}
#elif defined(UB_ON_WINDOWS)
	if(logging_to_syslog) {
		char m[32768];
		HANDLE* s;
		LPCTSTR str = m;
		DWORD tp = MSG_GENERIC_ERR;
		WORD wt = EVENTLOG_ERROR_TYPE;
		if(strcmp(type, "info") == 0) {
			tp=MSG_GENERIC_INFO;
			wt=EVENTLOG_INFORMATION_TYPE;
		} else if(strcmp(type, "warning") == 0) {
			tp=MSG_GENERIC_WARN;
			wt=EVENTLOG_WARNING_TYPE;
		} else if(strcmp(type, "notice") == 0 
			|| strcmp(type, "debug") == 0) {
			tp=MSG_GENERIC_SUCCESS;
			wt=EVENTLOG_SUCCESS;
		}
		snprintf(m, sizeof(m), "[%s:%x] %s: %s", 
			ident, tid?*tid:0, type, message);
		s = RegisterEventSource(NULL, SERVICE_NAME);
		if(!s) return;
		ReportEvent(s, wt, 0, tp, NULL, 1, 0, &str, NULL);
		DeregisterEventSource(s);
		return;
	}
#endif /* HAVE_SYSLOG_H */
	if(!logfile) return;
	if(log_now)
		now = (time_t)*log_now;
	else	now = (time_t)time(NULL);
#if defined(HAVE_STRFTIME) && defined(HAVE_LOCALTIME_R) 
	if(log_time_asc && strftime(tmbuf, sizeof(tmbuf), "%b %d %H:%M:%S",
		localtime_r(&now, &tm))%(sizeof(tmbuf)) != 0) {
		/* %sizeof buf!=0 because old strftime returned max on error */
		fprintf(logfile, "%s %s[%d:%x] %s: %s\n", tmbuf, 
			ident, (int)getpid(), tid?*tid:0, type, message);
	} else
#elif defined(UB_ON_WINDOWS)
	if(log_time_asc && GetTimeFormat(LOCALE_USER_DEFAULT, 0, NULL, NULL,
		tmbuf, sizeof(tmbuf)) && GetDateFormat(LOCALE_USER_DEFAULT, 0,
		NULL, NULL, dtbuf, sizeof(dtbuf))) {
		fprintf(logfile, "%s %s %s[%d:%x] %s: %s\n", dtbuf, tmbuf, 
			ident, (int)getpid(), tid?*tid:0, type, message);
	} else
#endif
	fprintf(logfile, "[" ARG_LL "d] %s[%d:%x] %s: %s\n", (long long)now, 
		ident, (int)getpid(), tid?*tid:0, type, message);
#ifdef UB_ON_WINDOWS
	/* line buffering does not work on windows */
	fflush(logfile);
#endif
}
Exemplo n.º 24
0
///////////////////////////////////////////////////////////////////////////////////////////
//  Function:       InitNLSFields
//
//  Description:    Initialize NLS formatting fields for a given LCID
//
//  Comments:
//
///////////////////////////////////////////////////////////////////////////////////////////
void InitNLSFields(HWND hDlg, LCID lcid)
{
    TCHAR   tcsTemp[MAX_STR];
    HWND    hList = NULL;

    // Init larg number fields...
    LoadString(g_hInst, STR_LARGEPOSNUMBER, g_tcsTemp, MAX_STR);
    GetNumberFormat(lcid, 0, g_tcsTemp, NULL, tcsTemp, MAX_STR);
    SetWindowText(GetDlgItem(hDlg, IDC_POS_NUMBER), tcsTemp);

    LoadString(g_hInst, STR_LARGENEGNUMBER, g_tcsTemp, MAX_STR);
    GetNumberFormat(lcid, 0, g_tcsTemp, NULL, tcsTemp, MAX_STR);
    SetWindowText(GetDlgItem(hDlg, IDC_NEG_NUMBER), tcsTemp);

    // Init the currency field format...
    LoadString(g_hInst, STR_LARGEPOSNUMBER, g_tcsTemp, MAX_STR);
    GetCurrencyFormat(lcid, 0, g_tcsTemp, NULL, tcsTemp, MAX_STR);
    SetWindowText(GetDlgItem(hDlg, IDC_POS_CURRENCY), tcsTemp);

    LoadString(g_hInst, STR_LARGENEGNUMBER, g_tcsTemp, MAX_STR);
    GetCurrencyFormat(lcid, 0, g_tcsTemp, NULL, tcsTemp, MAX_STR);
    SetWindowText(GetDlgItem(hDlg, IDC_NEG_CURRENCY), tcsTemp);

    // Init time field format...
    // Delete our previous list of items...
    hList = GetDlgItem(g_hDlg, IDC_TIMEFORMAT);
    if(NULL != hList)
    {
        SendMessage(hList, CB_RESETCONTENT , 0, 0);

        // Enumerates the time formats that are available for a specified locale.
        EnumTimeFormats(EnumTimeFormatsProc, lcid, 0);
        SendMessage(hList, CB_SETCURSEL, 0, 0);          // item index
        SendMessage(hList, CB_GETLBTEXT, 0, (LPARAM) g_tcsTemp);
        GetTimeFormat(lcid, 0, NULL, g_tcsTemp, tcsTemp, MAX_STR);
        SetWindowText(GetDlgItem(hDlg, IDC_TIMESAMPLE), tcsTemp);
    }

    // Init calendar field format...
    // Delete our previous list of items...
    hList = GetDlgItem(g_hDlg, IDC_CALFORMAT);
    if(NULL != hList)
    {
        SendMessage(hList, CB_RESETCONTENT , 0, 0);

        // Enumerates the short date formats that are available for a specified locale.
        EnumCalendarInfo(EnumCalendarInfoProc, lcid, ENUM_ALL_CALENDARS, CAL_SCALNAME);
        SendMessage(hList, CB_SETCURSEL, 0, 0);          // item index
        SendMessage(hList, CB_GETLBTEXT, 0, (LPARAM) g_tcsTemp);
    }

    // Init short date field format...
    // Delete our previous list of items...
    hList = GetDlgItem(g_hDlg, IDC_SDATEFORMAT);
    if(NULL != hList)
    {
        SendMessage(hList, CB_RESETCONTENT , 0, 0);

        // Enumerates the short date formats that are available for a specified locale.
        EnumDateFormats(EnumSDateFormatsProc, lcid, DATE_SHORTDATE);
        SendMessage(hList, CB_SETCURSEL, 0, 0);          // item index
        SendMessage(hList, CB_GETLBTEXT, 0, (LPARAM) g_tcsTemp);
        GetDateFormat(lcid, 0, NULL, g_tcsTemp, tcsTemp, MAX_STR);
        SetWindowText(GetDlgItem(hDlg, IDC_SDATESAMPLE), tcsTemp);
    }

    // Init long date field format...
    // Delete our previous list of items...
    hList = GetDlgItem(g_hDlg, IDC_LDATEFORMAT);
    if(NULL != hList)
    {
        SendMessage(hList, CB_RESETCONTENT , 0, 0);

        // Enumerates the long date formats that are available for a specified locale
        EnumDateFormats(EnumLDateFormatsProc, lcid, DATE_LONGDATE);
        SendMessage(hList, CB_SETCURSEL, 0, 0);          // item index
        SendMessage(hList, CB_GETLBTEXT, 0, (LPARAM) g_tcsTemp);
        GetDateFormat(lcid, 0, NULL, g_tcsTemp, tcsTemp, MAX_STR);
        SetWindowText(GetDlgItem(hDlg, IDC_LDATESAMPLE), tcsTemp);
    }
}
Exemplo n.º 25
0
INT_PTR srvVariablesHandler(WPARAM, LPARAM lParam)
{
    ARGUMENTSINFO *ai = (ARGUMENTSINFO*)lParam;
    ai->flags = AIF_DONTPARSE;
    TCString Result;
    if (!mir_tstrcmp(ai->targv[0], VAR_AWAYSINCE_TIME)) {
        GetTimeFormat(LOCALE_USER_DEFAULT, 0, g_ProtoStates[VarParseData.szProto].AwaySince, (ai->argc > 1 && *ai->targv[1]) ? ai->targv[1] : _T("H:mm"), Result.GetBuffer(256), 256);
        Result.ReleaseBuffer();
    }
    else if (!mir_tstrcmp(ai->targv[0], VAR_AWAYSINCE_DATE)) {
        GetDateFormat(LOCALE_USER_DEFAULT, 0, g_ProtoStates[VarParseData.szProto].AwaySince, (ai->argc > 1 && *ai->targv[1]) ? ai->targv[1] : NULL, Result.GetBuffer(256), 256);
        Result.ReleaseBuffer();
    }
    else if (!mir_tstrcmp(ai->targv[0], VAR_STATDESC)) {
        Result = (VarParseData.Flags & VPF_XSTATUS) ? STR_XSTATUSDESC : pcli->pfnGetStatusModeDescription(g_ProtoStates[VarParseData.szProto].Status, 0);
    }
    else if (!mir_tstrcmp(ai->targv[0], VAR_MYNICK)) {
        if (g_MoreOptPage.GetDBValueCopy(IDC_MOREOPTDLG_MYNICKPERPROTO) && VarParseData.szProto)
            Result = db_get_s(NULL, VarParseData.szProto, "Nick", (TCHAR*)NULL);

        if (Result == NULL)
            Result = pcli->pfnGetContactDisplayName(NULL, 0);

        if (Result == NULL)
            Result = TranslateT("Stranger");
    }
    else if (!mir_tstrcmp(ai->targv[0], VAR_REQUESTCOUNT)) {
        mir_sntprintf(Result.GetBuffer(16), 16, _T("%d"), db_get_w(ai->fi->hContact, MOD_NAME, DB_REQUESTCOUNT, 0));
        Result.ReleaseBuffer();
    }
    else if (!mir_tstrcmp(ai->targv[0], VAR_MESSAGENUM)) {
        mir_sntprintf(Result.GetBuffer(16), 16, _T("%d"), db_get_w(ai->fi->hContact, MOD_NAME, DB_MESSAGECOUNT, 0));
        Result.ReleaseBuffer();
    }
    else if (!mir_tstrcmp(ai->targv[0], VAR_TIMEPASSED)) {
        ULARGE_INTEGER ul_AwaySince, ul_Now;
        SYSTEMTIME st;
        GetLocalTime(&st);
        SystemTimeToFileTime(&st, (LPFILETIME)&ul_Now);
        SystemTimeToFileTime(g_ProtoStates[VarParseData.szProto].AwaySince, (LPFILETIME)&ul_AwaySince);
        ul_Now.QuadPart -= ul_AwaySince.QuadPart;
        ul_Now.QuadPart /= 10000000; // now it's in seconds
        Result.GetBuffer(256);
        if (ul_Now.LowPart >= 7200) // more than 2 hours
            mir_sntprintf(Result, 256, TranslateT("%d hours"), ul_Now.LowPart / 3600);
        else if (ul_Now.LowPart >= 120) // more than 2 minutes
            mir_sntprintf(Result, 256, TranslateT("%d minutes"), ul_Now.LowPart / 60);
        else
            mir_sntprintf(Result, 256, TranslateT("%d seconds"), ul_Now.LowPart);
        Result.ReleaseBuffer();
    }
    else if (!mir_tstrcmp(ai->targv[0], VAR_PREDEFINEDMESSAGE)) {
        ai->flags = 0; // reset AIF_DONTPARSE flag
        if (ai->argc != 2)
            return NULL;

        COptPage MsgTreeData(g_MsgTreePage);
        COptItem_TreeCtrl *TreeCtrl = (COptItem_TreeCtrl*)MsgTreeData.Find(IDV_MSGTREE);
        TreeCtrl->DBToMem(CString(MOD_NAME));

        for (int i = 0; i < TreeCtrl->Value.GetSize(); i++) {
            if (!(TreeCtrl->Value[i].Flags & TIF_GROUP) && !mir_tstrcmpi(TreeCtrl->Value[i].Title, ai->targv[1])) {
                Result = TreeCtrl->Value[i].User_Str1;
                break;
            }
        }
        if (Result == NULL) // if we didn't find a message with specified title
            return NULL; // return it now, as later we change NULL to ""
    }
    else if (!mir_tstrcmp(ai->targv[0], VAR_PROTOCOL)) {
        if (VarParseData.szProto) {
            CString AnsiResult;
            CallProtoService(VarParseData.szProto, PS_GETNAME, 256, (LPARAM)AnsiResult.GetBuffer(256));
            AnsiResult.ReleaseBuffer();
            Result = _A2T(AnsiResult);
        }
        if (Result == NULL) // if we didn't find a message with specified title
            return NULL; // return it now, as later we change NULL to ""
    }
    TCHAR *szResult = (TCHAR*)malloc((Result.GetLen() + 1) * sizeof(TCHAR));
    if (!szResult)
        return NULL;

    mir_tstrcpy(szResult, (Result != NULL) ? Result : _T(""));
    return (INT_PTR)szResult;
}
Exemplo n.º 26
0
WORD
TZF_Timestamp (wchar_t* const out)
{
  SYSTEMTIME stLogTime;

#if 0
  // Check for Windows 8 / Server 2012
  static bool __hasSystemTimePrecise =
    (LOBYTE (LOWORD (GetVersion ())) == 6  &&
     HIBYTE (LOWORD (GetVersion ())) >= 2) ||
     LOBYTE (LOWORD (GetVersion () > 6));

  // More accurate timestamp is available on Windows 6.2+
  if (__hasSystemTimePrecise) {
    FILETIME   ftLogTime;
    GetSystemTimePreciseAsFileTime (&ftLogTime);
    FileTimeToSystemTime           (&ftLogTime, &stLogTime);
  } else {
#else
    GetLocalTime (&stLogTime);
#endif
  //}

  wchar_t date [64] = { L'\0' };
  wchar_t time [64] = { L'\0' };

  GetDateFormat (LOCALE_INVARIANT,DATE_SHORTDATE,   &stLogTime,NULL,date,64);
  GetTimeFormat (LOCALE_INVARIANT,TIME_NOTIMEMARKER,&stLogTime,NULL,time,64);

  out [0] = L'\0';

  lstrcatW (out, date);
  lstrcatW (out, L" ");
  lstrcatW (out, time);
  lstrcatW (out, L".");

  return stLogTime.wMilliseconds;
}

tzf_logger_t dll_log;


void
tzf_logger_t::close (void)
{
  if (fLog != NULL) {
    fflush (fLog);
    fclose (fLog);
  }

  initialized = false;
  silent      = true;

  DeleteCriticalSection (&log_mutex);
}

bool
tzf_logger_t::init (const char* const szFileName,
                    const char* const szMode)
{
  if (initialized)
    return true;

  //
  // Split the path, so we can create the log directory if necessary
  //
  if (strstr (szFileName, "\\")) {
    char* szSplitPath = strdup (szFileName);

    // Replace all instances of '/' with '\'
    size_t len = strlen (szSplitPath);
    for (size_t i = 0; i < len; i++) {
      if (szSplitPath [i] == '/')
        szSplitPath [i] = '\\';
    }

    char* szSplitter  = strrchr (szSplitPath, '\\');
         *szSplitter  = '\0';

    char path [MAX_PATH] = { '\0' };

    char* subpath = strtok (szSplitPath, "\\");

    // For each subdirectory, create it...
    while (subpath != nullptr) {
      strcat           (path, subpath);
      CreateDirectoryA (path, NULL);
      strcat           (path, "\\");

      subpath = strtok (NULL, "\\");
    }

    free (szSplitPath);
  }

  fLog = fopen (szFileName, szMode);

  BOOL bRet = InitializeCriticalSectionAndSpinCount (&log_mutex, 2500);

  if ((! bRet) || (fLog == NULL)) {
    silent = true;
    return false;
  }

  initialized = true;
  return initialized;
}

void
tzf_logger_t::LogEx (bool                 _Timestamp,
  _In_z_ _Printf_format_string_
                     wchar_t const* const _Format, ...)
{
  va_list _ArgList;

  if (! initialized)
    return;

  EnterCriticalSection (&log_mutex);

  if ((! fLog) || silent) {
    LeaveCriticalSection (&log_mutex);
    return;
  }

  if (_Timestamp) {
    wchar_t wszLogTime [128];

    WORD ms = TZF_Timestamp (wszLogTime);

    fwprintf (fLog, L"%s%03u: ", wszLogTime, ms);
  }

  va_start (_ArgList, _Format);
  {
    vfwprintf (fLog, _Format, _ArgList);
  }
  va_end   (_ArgList);

  fflush (fLog);

  LeaveCriticalSection (&log_mutex);
}
Exemplo n.º 27
0
PTSTR Expand(PTSTR ptzDst, TCHAR tMacro, CXT& XT)
{
	INT i;
	switch (tMacro)
	{
	case 'E':
		for (PCTSTR p = XT.ptzFile; *p; *ptzDst++ = *p++);
		return ptzDst;

	case 'C':
		if (PCTSTR q = UStrRChr(XT.ptzFile, '\\'))
		{
			for (PCTSTR p = XT.ptzFile; p < q; *ptzDst++ = *p++);
		}
		return ptzDst;

	case 'T':
		ptzDst += GetTimeFormat(LOCALE_USER_DEFAULT, 0, NULL, NULL, ptzDst, MAX_NAME) - 1;
		return ptzDst;

	case 'D':
		ptzDst += GetDateFormat(LOCALE_USER_DEFAULT, 0, NULL, NULL, ptzDst, MAX_NAME) - 1;
		return ptzDst;

	case 'X':
	case 'x':
		ptzDst += UStrPrint(ptzDst,  (tMacro == 'X') ? TEXT("%#X") : TEXT("%d"), XT.hXVar);
		return ptzDst;

	case '0':
	case '1':
	case '2':
	case '3':
	case '4':
	case '5':
	case '6':
	case '7':
	case '8':
	case '9':
		for (PTSTR p = g_tzXVar[tMacro - '0']; *p; p++) *ptzDst++ = *p;
		return ptzDst;

	case 'A': i = CSIDL_APPDATA; break;
	case 'Y': i = CSIDL_MYDOCUMENTS; break;
	case 'S': i = CSIDL_STARTUP; break;
	case 'M': i = CSIDL_STARTMENU; break;
	case 'P': i = CSIDL_PROGRAMS; break;
	case 'V': i = CSIDL_FAVORITES; break;
	case 'Z': i = CSIDL_MYPICTURES; break;
	case 'U': i = CSIDL_MYMUSIC; break;
	case 'I': i = CSIDL_MYVIDEO; break;
	case 'F': i = CSIDL_PROGRAM_FILES; break;
	case 'O': i = CSIDL_SENDTO; break;
	case 'o': i = CSIDL_DESKTOPDIRECTORY; break;

	case 'd': i = CSIDL_COMMON_DESKTOPDIRECTORY; break;
	case 'a': i = CSIDL_COMMON_APPDATA; break;
	case 'y': i = CSIDL_COMMON_DOCUMENTS; break;
	case 's': i = CSIDL_COMMON_STARTUP; break;
	case 'm': i = CSIDL_COMMON_STARTMENU; break;
	case 'p': i = CSIDL_COMMON_PROGRAMS; break;
	case 'v': i = CSIDL_COMMON_FAVORITES; break;
	case 'z': i = CSIDL_COMMON_PICTURES; break;
	case 'u': i = CSIDL_COMMON_MUSIC; break;
	case 'i': i = CSIDL_COMMON_VIDEO; break;
	case 'f': i = CSIDL_PROGRAM_FILES_COMMON; break;

	case 'W': case 'w': i = CSIDL_WINDOWS; break;

	case 'R': *ptzDst++ = '\r'; return ptzDst;
	case 'N': *ptzDst++ = '\n'; return ptzDst;
	default: *ptzDst++ = tMacro; return ptzDst;
	}

	SHGetSpecialFolderPath(NULL, ptzDst, i, TRUE);
	ptzDst += UStrLen(ptzDst);
	return ptzDst;
}
static void write_log(int log_action, const char* buff)
{
/******************************************************************************
 *
 *  w r i t e _ l o g
 *
 ******************************************************************************
 *
 *  Description:  Writes the guardian information to either the Windows 95
 *                property sheet structure (log_entry) or to the Windows NT
 *                Event Log
 *****************************************************************************/
	const size_t BUFF_SIZE = 512;
	char tmp_buff[BUFF_SIZE];

	// Move to the end of the log_entry list
	log_info* log_temp = log_entry;
	while (log_temp->next)
		log_temp = log_temp->next;

	log_info* tmp = static_cast<log_info*>(malloc(sizeof(log_info)));
	memset(tmp, 0, sizeof(log_info));

#ifdef NOT_USED_OR_REPLACED
	time_t ltime;
	time(&ltime);
	const tm* today = localtime(&ltime);

	sprintf(tmp->log_time, "%02d:%02d", today->tm_hour, today->tm_min);
	sprintf(tmp->log_date, "%02d/%02d/%02d", today->tm_mon + 1, today->tm_mday, today->tm_year % 100);
#else
	// TMN: Fixed this after bug-report. Should it really force
	// 24hr format in e.g US, where they use AM/PM wharts?
	GetTimeFormat(LOCALE_USER_DEFAULT, TIME_NOSECONDS | TIME_FORCE24HOURFORMAT, NULL, NULL,
				  tmp->log_time, sizeof(tmp->log_time));
	GetDateFormat(LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL, NULL,
				  tmp->log_date, sizeof(tmp->log_date));
#endif

	if (log_action >= IDS_LOG_START && log_action <= IDS_LOG_TERM)
	{
		// Only Windows 95 needs this information since it goes in the property sheet
		LoadString(hInstance_gbl, log_action, tmp_buff, sizeof(tmp->log_action));
		sprintf(tmp->log_action, "%s", tmp_buff);
		tmp->next = NULL;
		log_temp->next = tmp;
	}

	if (service_flag)
	{
		// on NT
		HANDLE hLog = RegisterEventSource(NULL, service_name->c_str());
		if (!hLog)
			gds__log("Error opening Windows NT Event Log");
		else
		{
			char buffer[BUFF_SIZE];
			char* act_buff[1];
			act_buff[0] = buffer;

			LoadString(hInstance_gbl, log_action + 1, tmp_buff, sizeof(tmp_buff));
			sprintf(act_buff[0], "%s", buff);

			LPTSTR lpMsgBuf;
			FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
						  FORMAT_MESSAGE_ARGUMENT_ARRAY |
						  FORMAT_MESSAGE_FROM_STRING,
						  tmp_buff, 0, 0, (LPTSTR) &lpMsgBuf, 0,
						  reinterpret_cast<va_list*>(act_buff));

			const int len = MIN(BUFF_SIZE - 1, strlen(lpMsgBuf) - 1);
			strncpy(act_buff[0], lpMsgBuf, len);
			act_buff[0][len] = 0;
			LocalFree(lpMsgBuf);
			WORD wLogType;

			switch (log_action)
			{
			case IDS_LOG_START:
			case IDS_LOG_STOP:
				wLogType = EVENTLOG_INFORMATION_TYPE;
				break;
			default:
				wLogType = EVENTLOG_ERROR_TYPE;
			}

			if (!ReportEvent
				(hLog, wLogType, 0, log_action + 1, NULL, 1, 0,
				 const_cast<const char**>(act_buff), NULL))
			{
				FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
							  FORMAT_MESSAGE_FROM_SYSTEM |
							  FORMAT_MESSAGE_IGNORE_INSERTS, NULL,
							  GetLastError(),
							  MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),	// Default language
							  (LPTSTR) & lpMsgBuf, 0, NULL);
				gds__log("Unable to update NT Event Log.\n\tOS Message: %s", lpMsgBuf);
				LocalFree(lpMsgBuf);
			}
			DeregisterEventSource(hLog);
		}
	}

	// Write to the Firebird log
	if (*buff)
		gds__log(buff);
}
Exemplo n.º 29
0
/****************************************************************************
 * WCMD_HandleTildaModifiers
 *
 * Handle the ~ modifiers when expanding %0-9 or (%a-z in for command)
 *    %~xxxxxV  (V=0-9 or 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, WCHAR *forVariable, WCHAR *forValue, BOOL justFors) {

#define NUMMODIFIERS 11
  static const WCHAR validmodifiers[NUMMODIFIERS] = {
        '~', 'f', 'd', 'p', 'n', 'x', 's', 'a', 't', 'z', '$'
  };
  static const WCHAR space[] = {' ', '\0'};

  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 / %s\n",
               wine_dbgstr_w(lastModifier), wine_dbgstr_w(forVariable));

    if (!justFors && context && (*lastModifier >= '0' || *lastModifier <= '9')) {
      /* Its a valid parameter identifier - OK */
      break;

    } else if (forVariable && *lastModifier == *(forVariable+1)) {
      /* Its a valid parameter identifier - OK */
      break;

    } else {
      lastModifier--;
    }
  }
  if (lastModifier == firstModifier) return; /* Invalid syntax */

  /* Extract the parameter to play with */
  if ((*lastModifier >= '0' && *lastModifier <= '9')) {
    strcpyW(outputparam, WCMD_parameter (context -> command,
                 *lastModifier-'0' + context -> shift_count[*lastModifier-'0'], NULL));
  } else {
    strcpyW(outputparam, forValue);
  }

  /* 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;

  /* Useful for debugging purposes: */
  /*printf("Modifier string '%*.*s' and variable is %c\n Param starts as '%s'\n",
             (modifierLen), (modifierLen), firstModifier, *lastModifier,
             outputparam);*/

  /* 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 *start = strchrW(firstModifier, '$') + 1;
    WCHAR *end   = strchrW(firstModifier, ':');
    WCHAR env[MAX_PATH];
    WCHAR fullpath[MAX_PATH];

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

    /* If env var not found, return empty string */
    if ((GetEnvironmentVariable(env, fullpath, MAX_PATH) == 0) ||
        (SearchPath(fullpath, outputparam, NULL,
                    MAX_PATH, outputparam, NULL) == 0)) {
      finaloutput[0] = 0x00;
      outputparam[0] = 0x00;
      skipFileParsing = TRUE;
    }
  }

  /* After this, we need full information on the file,
    which is valid not to exist.  */
  if (!skipFileParsing) {
    if (GetFullPathName(outputparam, MAX_PATH, fullfilename, NULL) == 0)
      return;

    exists = GetFileAttributesExW(fullfilename, GetFileExInfoStandard,
                                  &fileInfo);

    /* 2. Handle 'a' : Output attributes */
    if (exists &&
        memchrW(firstModifier, 'a', modifierLen) != NULL) {

      WCHAR defaults[] = {'-','-','-','-','-','-','-','-','-','\0'};
      doneModifier = TRUE;
      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 */
    if (exists &&
        memchrW(firstModifier, 't', modifierLen) != NULL) {

      SYSTEMTIME systime;
      int datelen;

      doneModifier = TRUE;
      if (finaloutput[0] != 0x00) strcatW(finaloutput, space);

      /* Format the time */
      FileTimeToSystemTime(&fileInfo.ftLastWriteTime, &systime);
      GetDateFormat(LOCALE_USER_DEFAULT, DATE_SHORTDATE, &systime,
                        NULL, thisoutput, MAX_PATH);
      strcatW(thisoutput, space);
      datelen = strlenW(thisoutput);
      GetTimeFormat(LOCALE_USER_DEFAULT, TIME_NOSECONDS, &systime,
                        NULL, (thisoutput+datelen), MAX_PATH-datelen);
      strcatW(finaloutput, thisoutput);
    }

    /* 4. Handle 'z' : File length */
    if (exists &&
        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 (finaloutput[0] != 0x00) strcatW(finaloutput, space);
      wsprintf(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, space);
      /* Don't flag as doneModifier - %~s on its own is processed later */
      GetShortPathName(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, space);
      strcatW(finaloutput, fullfilename);
    } else {

      WCHAR drive[10];
      WCHAR dir[MAX_PATH];
      WCHAR fname[MAX_PATH];
      WCHAR ext[MAX_PATH];
      BOOL doneFileModifier = FALSE;

      if (finaloutput[0] != 0x00) strcatW(finaloutput, space);

      /* Split into components */
      WCMD_splitpath(fullfilename, drive, dir, fname, ext);

      /* 5. Handle 'd' : Drive Letter */
      if (memchrW(firstModifier, 'd', modifierLen) != NULL) {
        strcatW(finaloutput, drive);
        doneModifier = TRUE;
        doneFileModifier = TRUE;
      }

      /* 6. Handle 'p' : Path */
      if (memchrW(firstModifier, 'p', modifierLen) != NULL) {
        strcatW(finaloutput, dir);
        doneModifier = TRUE;
        doneFileModifier = TRUE;
      }

      /* 7. Handle 'n' : Name */
      if (memchrW(firstModifier, 'n', modifierLen) != NULL) {
        strcatW(finaloutput, fname);
        doneModifier = TRUE;
        doneFileModifier = TRUE;
      }

      /* 8. Handle 'x' : Ext */
      if (memchrW(firstModifier, 'x', modifierLen) != NULL) {
        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, space);
        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 */
  pos = WCMD_strdupW(lastModifier+1);
  strcpyW(*start, finaloutput);
  strcatW(*start, pos);
  free(pos);
}
Exemplo n.º 30
0
void DrawSimpleIdleScreen(void)
{
  unsigned char msd;
  unsigned char lsd;

  unsigned char Row = 6;
  unsigned char Col = 0;

  int Minutes;
  /* display hour */
  int Hour = GetRTCHOUR();
  if (Hour < 0 || Hour > 23) {
    Hour = 0;
  }

  /* if required convert to twelve hour format */
  if ( GetTimeFormat() == TWELVE_HOUR )
  {
    if ( Hour == 0 )
    {
      Hour = 12;
    }
    else if ( Hour > 12 )
    {
      Hour -= 12;
    }
  }

  msd = Hour / 10;
  lsd = Hour % 10;

  /* if first digit is zero then leave location blank */
  if ( msd != 0 )
  {
    WriteTimeDigit(msd, Row, Col, LEFT_JUSTIFIED);
  }
  Col += 1;
  WriteTimeDigit(lsd, Row, Col, RIGHT_JUSTIFIED);
  Col += 2;

  /* the colon takes the first 5 bits on the byte*/
  WriteTimeColon(Row,Col,RIGHT_JUSTIFIED);
  Col += 1;

  /* display minutes */
  Minutes = GetRTCMIN();
  if (Minutes < 0 || Minutes > 59) {
    Minutes = 0;
  }
  msd = Minutes / 10;
  lsd = Minutes % 10;

  WriteTimeDigit(msd, Row, Col, RIGHT_JUSTIFIED);
  Col += 2;
  WriteTimeDigit(lsd, Row, Col, LEFT_JUSTIFIED);

  if ( nvDisplaySeconds )
  {
    /* the final colon's spacing isn't quite the same */
    int Seconds = GetRTCSEC();

    msd = Seconds / 10;
    lsd = Seconds % 10;

    Col +=2;
    WriteTimeColon(Row,Col,LEFT_JUSTIFIED);
    Col += 1;
    WriteTimeDigit(msd,Row,Col,LEFT_JUSTIFIED);
    Col += 1;
    WriteTimeDigit(lsd,Row,Col,RIGHT_JUSTIFIED);

  }
  else
  {
    DisplayAmPm();
    DisplayDayOfWeek();
    DisplayDate();

  }

}