LRESULT CALLBACK WndProc2(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_CREATE: iVerPos = 0; stScrollInfoVer.cbSize = sizeof(SCROLLINFO); stScrollInfoVer.fMask = SIF_POS | SIF_RANGE | SIF_PAGE; stScrollInfoVer.nMin = 1; stScrollInfoVer.nMax = 100; stScrollInfoVer.nPos = 1; stScrollInfoVer.nPage = 10; SetScrollInfo(hWnd, SB_VERT, &stScrollInfoVer, FALSE); iHorPos = 0; stScrollInfoHor.cbSize = sizeof(SCROLLINFO); stScrollInfoHor.fMask = SIF_POS | SIF_RANGE | SIF_PAGE; stScrollInfoHor.nMin = 1; stScrollInfoHor.nMax = 100; stScrollInfoHor.nPos = 1; stScrollInfoHor.nPage = 10; SetScrollInfo(hWnd, SB_HORZ, &stScrollInfoHor, FALSE); if (!DIBLoadPng(&bg1, "bg01a.png")) { MessageBox(hWnd, "load 1 Fail", "Load png", MB_OK); } if (true) { if (!DIBLoadPng(&bg2, "nm001.png")) //("images\\bg01a.png")) { MessageBox(hWnd, "load 2 Fail", "Load png", MB_OK); } } else { if (!DIBLoadBmp(&bg2, "image2.bmp")) { MessageBox(hWnd, "load 2 Fail", "Load image2.bmp", MB_OK); } } break; case WM_PAINT: { PAINTSTRUCT ps; HDC hDC = BeginPaint(hWnd, &ps); { RECT rect; GetClientRect(hWnd, &rect); PatBlt(hDC, 0, 0, rect.right, rect.bottom, BLACKNESS); if (false) { struct dib_struct temp; DIBCreate(&temp, 800, 600, 24); DIBCopy(&temp, &bg2); DIBDraw(&temp, hDC, 0, 0, rect.right - rect.left, rect.bottom - rect.top); DIBRelease(&temp); } else { POINT point; point.x = 0; point.y = 0; SIZE size; size.cx = 300;//432; size.cy = 400;//480; RECT fill_rect; fill_rect.left = fill_rect.top = 100; fill_rect.right = fill_rect.bottom = 200; COLORREF color = RGB(0, 255, 0); //RGB(255, 255, 255); DIBMix(&bg1, &bg2, point, size, point, color); //DIBFillRect(&bg1, fill_rect, RGB(255, 0, 0)); DIBDraw(&bg1, hDC, 0, 0, rect.right - rect.left, rect.bottom - rect.top); } } EndPaint(hWnd, &ps); } return 0; case WM_ERASEBKGND: return FALSE; case WM_VSCROLL: //((HWND)lParam) switch(LOWORD(wParam)) { case SB_LINEUP: iVerPos += 5; break; case SB_LINEDOWN: iVerPos -= 5; break; case SB_PAGEUP: iVerPos += 20; break; case SB_PAGEDOWN: iVerPos -= 20; break; case SB_THUMBPOSITION: iVerPos = 100 - HIWORD(wParam); //OutputDebugString("hello\n"); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } if (iVerPos < 5) { iVerPos = 0; } else if (iVerPos > 100) { iVerPos = 100; } stScrollInfoVer.fMask = SIF_POS; stScrollInfoVer.nPos = 100 - iVerPos; SetScrollInfo(hWnd, SB_VERT, &stScrollInfoVer, TRUE); { char dbg[255] = {0}; sprintf(dbg, "Ver:%d\n", stScrollInfoVer.nPos); OutputDebugString(dbg); } break; case WM_HSCROLL: //((HWND)lParam) switch(LOWORD(wParam)) { case SB_LINEUP: iHorPos += 5; break; case SB_LINEDOWN: iHorPos -= 5; break; case SB_PAGEUP: iHorPos += 20; break; case SB_PAGEDOWN: iHorPos -= 20; break; case SB_THUMBPOSITION: iHorPos = 100 - HIWORD(wParam); //OutputDebugString("hello\n"); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } if (iHorPos < 5) { iHorPos = 0; } else if (iHorPos > 95) { iHorPos = 100; } stScrollInfoHor.fMask = SIF_POS; stScrollInfoHor.nPos = 100 - iHorPos; SetScrollInfo(hWnd, SB_HORZ, &stScrollInfoHor, TRUE); { char dbg[255] = {0}; sprintf(dbg, "Hor:%d\n", stScrollInfoHor.nPos); OutputDebugString(dbg); } break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; }
//----------------------------------------------------------------------------- // Purpose: Draws text to the screen inside the given rectangular region, using the given font //----------------------------------------------------------------------------- bool CGameEngineGL::BDrawString( HGAMEFONT hFont, RECT rect, DWORD dwColor, DWORD dwFormat, const char *pchText ) { if ( !hFont ) { OutputDebugString( "Someone is calling BDrawString with a null font handle\n" ); return false; } if ( !pchText || !*pchText ) { return true; } // Very simple cache of complete strings as whole textures. // There are much better ways of doing efficient text rendering. // If nothing else we should expire the strings not being used. HGAMETEXTURE hTexture; char szFontPrefix[32]; sprintf( szFontPrefix, "%d:", hFont ); std::map< std::string, HGAMETEXTURE >::iterator iter; iter = m_MapStrings.find( std::string(szFontPrefix) + std::string(pchText) ); if ( iter == m_MapStrings.end() ) { static SDL_Color white = { 0xff, 0xff, 0xff, 0xff }; // Calculate the text block size int nWrapLength = 0; int w, h; char *s = (char *)pchText; for ( char *p = strchr( s, '\n' ); p; p = strchr( s, '\n' ) ) { *p = '\0'; if ( TTF_SizeUTF8( m_MapGameFonts[ hFont ], s, &w, &h ) == 0 ) { nWrapLength = std::max( w, nWrapLength ); } *p = '\n'; s = p + 1; } if ( TTF_SizeUTF8( m_MapGameFonts[ hFont ], s, &w, &h ) == 0 ) { nWrapLength = std::max( w, nWrapLength ); } SDL_Surface *surface = TTF_RenderUTF8_Blended_Wrapped( m_MapGameFonts[ hFont ], pchText, white, nWrapLength ); if ( !surface ) { OutputDebugString( "Out of memory\n" ); return false; } uint32 uWidth = power_of_two( surface->w ); uint32 uHeight = power_of_two( surface->h ); byte *pRGBAData = (byte *)malloc( uWidth*uHeight*4 ); if ( !pRGBAData ) { OutputDebugString( "Out of memory\n" ); return false; } memset( pRGBAData, 0, uWidth*uHeight*4 ); byte *src = (byte*)surface->pixels; byte *dst = pRGBAData; memset(dst, 0xff, uWidth*4); for ( uint32 row = 0; row < surface->h; ++row ) { memcpy( dst, src, surface->w * 4 ); src += surface->pitch; dst += uWidth * 4; } hTexture = HCreateTexture( pRGBAData, uWidth, uHeight ); free( pRGBAData ); // Record the actual text width and height m_MapTextures[ hTexture ].m_uWidth = surface->w; m_MapTextures[ hTexture ].m_uHeight = surface->h; SDL_FreeSurface( surface ); m_MapStrings[ std::string(szFontPrefix) + std::string(pchText) ] = hTexture; } else { hTexture = iter->second; } int nWidth = m_MapTextures[ hTexture ].m_uWidth; int nHeight = m_MapTextures[ hTexture ].m_uHeight; float u = (float)nWidth / power_of_two(nWidth); float v = (float)nHeight / power_of_two(nHeight); // Get text position int nLeft = rect.left, nTop = rect.top; if ( dwFormat & TEXTPOS_TOP ) { nTop = rect.top; } else if ( dwFormat & TEXTPOS_VCENTER ) { nTop = rect.top + ((rect.bottom - rect.top) - nHeight) / 2; } else if ( dwFormat & TEXTPOS_BOTTOM ) { nTop = rect.bottom - nHeight; } if ( dwFormat & TEXTPOS_LEFT ) { nLeft = rect.left; } else if ( dwFormat & TEXTPOS_CENTER ) { nLeft = rect.left + ((rect.right - rect.left) - nWidth) / 2; } else if ( dwFormat & TEXTPOS_RIGHT ) { nLeft = rect.right - nWidth; } //printf("Drawing text '%s' at %d,%d %dx%d {%d,%d %d,%d}\n", pchText, nLeft, nTop, nWidth, nHeight, rect.left, rect.top, rect.right, rect.bottom); return BDrawTexturedQuad( nLeft, nTop, nLeft + nWidth, nTop + nHeight, 0.0f, 0.0f, u, v, dwColor, hTexture ); }
void cStatement::Do(){// Metodo para ejecutar Acciones switch(meType){ case 1:{// eStatementRemove // std::string lacObject = macParam1 + " Removed \n"; // OutputDebugString( lacObject.c_str()); cLevel &lLevel = cGame::Get().GetLevel(); lLevel.Remove( macParam1); ;}break; case 2:{// eStatementMessage // std::string lacObject = macParam1 + " Message Sended \n"; // OutputDebugString( lacObject.c_str()); cGame::Get().PrintMessage(macParam1);// le enviamos una solicitud que imprima el bendito mensaje a Game ;}break; case 3:{// eStatementMove // std::string lacObject = macParam1 + " moved to " + macParam2 + "\n"; // OutputDebugString( lacObject.c_str()); cLevel &lLevel = cGame::Get().GetLevel(); lLevel.Move( macParam1, macParam2[0]); ;}break; case 4:{// eStatementConversation // std::string lacObject = macParam1 + " moved to " + macParam2 + "\n"; // OutputDebugString( "\n Realizando conversación: \n"); cConversationManager::Get().StartConversation(macParam1); // macParam1 == "Comienzo" ;}break; case 5:{// eStatementExit cGame::Get().SetFinish(true); ;}break; case 6:{// eStatementUpdateStats // points & lives if ( macParam1 == "scoreup" ) cGame::Get().PlayerScored(atoi(macParam2.c_str())); else if ( macParam1 == "PlayerDies") { cGame::Get().PlayerDies(); cGame::Get().SetPlayingMode(false); } // cGame::Get().PrintMessage(macParam1); ;}break; default:{// es una Condicional ejecutada como acción OutputDebugString(" Error: using Do Method with Conditionants "); ;}break; } ;}
/** * Perform the actual logging. * @param val */ void log(std::stringstream & val) { std::lock_guard<std::recursive_mutex> l1(mutex_); static const bool use_file = true; if (use_file) { static std::string path = filesystem::data_path() + "debug.log" ; if (ofstream_.is_open() == false) { ofstream_.open( path, std::fstream::out | std::fstream::app ); } if (ofstream_.is_open() == true) { /** * Limit size. */ if (ofstream_.tellp() > 10 * 1000000) { ofstream_.close(); ofstream_.open(path, std::fstream::out); } ofstream_ << val.str() << std::endl; ofstream_.flush(); } } static bool use_cout = true; if (use_cout) { #if (defined _WIN32 || defined WIN32) || (defined _WIN64 || defined WIN64) #if defined(_UNICODE) DWORD len = MultiByteToWideChar( CP_ACP, 0, val.str().c_str(), -1, NULL, 0 ); std::unique_ptr<wchar_t> buf(new wchar_t[len]); MultiByteToWideChar( CP_ACP, 0, val.str().c_str(), -1, buf.get(), len ); OutputDebugString(buf.get()); OutputDebugString(L"\n"); std::cerr << val.str() << std::endl; #else OutputDebugString(val.str().c_str()); OutputDebugString(L"\n"); std::cerr << val.str() << std::endl; #endif // _UNICODE #else // Not Windows. #if (defined __ANDROID__) __android_log_print( ANDROID_LOG_DEBUG, "logger", val.str().c_str() ); #else std::cerr << val.str() << std::endl; #endif #endif // defined _WIN32 || defined WIN32) || (defined _WIN64 || defined WIN64 } }
//----------------------------------------------------------------------------- // Purpose: Draw a textured quad //----------------------------------------------------------------------------- bool CGameEngineGL::BDrawTexturedQuad( float xPos0, float yPos0, float xPos1, float yPos1, float u0, float v0, float u1, float v1, DWORD dwColor, HGAMETEXTURE hTexture ) { if ( m_bShuttingDown ) return false; // Find the texture std::map<HGAMETEXTURE, TextureData_t>::iterator iter; iter = m_MapTextures.find( hTexture ); if ( iter == m_MapTextures.end() ) { OutputDebugString( "BDrawTexturedQuad called with invalid hTexture value\n" ); return false; } // Check if we are out of room and need to flush the buffer, or if our texture is changing // then we also need to flush the buffer. if ( m_dwQuadsToFlush == QUAD_BUFFER_TOTAL_SIZE || m_hLastTexture != hTexture ) { BFlushQuadBuffer(); } // Bind the new texture glBindTexture( GL_TEXTURE_2D, iter->second.m_uTextureID ); DWORD dwOffset = m_dwQuadsToFlush*12; m_rgflQuadsData[dwOffset] = xPos0; m_rgflQuadsData[dwOffset+1] = yPos0; m_rgflQuadsData[dwOffset+2] = 1.0; m_rgflQuadsData[dwOffset+3] = xPos1; m_rgflQuadsData[dwOffset+4] = yPos0; m_rgflQuadsData[dwOffset+5] = 1.0; m_rgflQuadsData[dwOffset+6] = xPos1; m_rgflQuadsData[dwOffset+7] = yPos1; m_rgflQuadsData[dwOffset+8] = 1.0; m_rgflQuadsData[dwOffset+9] = xPos0; m_rgflQuadsData[dwOffset+10] = yPos1; m_rgflQuadsData[dwOffset+11] = 1.0; dwOffset = m_dwQuadsToFlush*16; m_rgflQuadsColorData[dwOffset] = COLOR_RED( dwColor ); m_rgflQuadsColorData[dwOffset+1] = COLOR_GREEN( dwColor ); m_rgflQuadsColorData[dwOffset+2] = COLOR_BLUE( dwColor ); m_rgflQuadsColorData[dwOffset+3] = COLOR_ALPHA( dwColor ); m_rgflQuadsColorData[dwOffset+4] = COLOR_RED( dwColor ); m_rgflQuadsColorData[dwOffset+5] = COLOR_GREEN( dwColor ); m_rgflQuadsColorData[dwOffset+6] = COLOR_BLUE( dwColor ); m_rgflQuadsColorData[dwOffset+7] = COLOR_ALPHA( dwColor ); m_rgflQuadsColorData[dwOffset+8] = COLOR_RED( dwColor ); m_rgflQuadsColorData[dwOffset+9] = COLOR_GREEN( dwColor ); m_rgflQuadsColorData[dwOffset+10] = COLOR_BLUE( dwColor ); m_rgflQuadsColorData[dwOffset+11] = COLOR_ALPHA( dwColor ); m_rgflQuadsColorData[dwOffset+12] = COLOR_RED( dwColor ); m_rgflQuadsColorData[dwOffset+13] = COLOR_GREEN( dwColor ); m_rgflQuadsColorData[dwOffset+14] = COLOR_BLUE( dwColor ); m_rgflQuadsColorData[dwOffset+15] = COLOR_ALPHA( dwColor ); dwOffset = m_dwQuadsToFlush*8; m_rgflQuadsTextureData[dwOffset] = u0; m_rgflQuadsTextureData[dwOffset+1] = v0; m_rgflQuadsTextureData[dwOffset+2] = u1; m_rgflQuadsTextureData[dwOffset+3] = v0; m_rgflQuadsTextureData[dwOffset+4] = u1; m_rgflQuadsTextureData[dwOffset+5] = v1; m_rgflQuadsTextureData[dwOffset+6] = u0; m_rgflQuadsTextureData[dwOffset+7] = v1; ++m_dwQuadsToFlush; return true; }
BOOL CTrackDlg::PreTranslateMessage(MSG* pMsg) { if(pMsg->message == WM_KEYDOWN) { int nChar = pMsg->wParam; if((nChar == 'Z') || (nChar == 'X')) { if((pMsg->lParam & 0xFFFF) == 1) { CString str; BOOL stepped = FALSE; if((nChar == 'Z') && (m_step != LEFT)) { m_step = LEFT; m_numSteps++; stepped = TRUE; } else if ((nChar == 'X') && (m_step != RIGHT)) { m_step = RIGHT; m_numSteps++; stepped = TRUE; } if(stepped && m_racing) { m_progress.SetPos(m_numSteps); if(m_numSteps == m_totalSteps) { DWORD diff; m_racing = FALSE; diff = (GetTickCount() - m_start); str.Format("%0.3fs\n", diff / 1000.0); OutputDebugString(str); MessageBox(str); UpdateData(); m_info = "DONE"; // Report the stats. //////////////////// ReportStats(diff); // Update best time(s) if needed. ///////////////////////////////// CString * topStr; CString * bestStr; DWORD topTime; DWORD bestTime; if(m_event == EVENT_50) { topStr = &m_top50; bestStr = &m_best50; } else if(m_event == EVENT_100) { topStr = &m_top100; bestStr = &m_best100; } else { topStr = &m_top200; bestStr = &m_best200; } topTime = (DWORD)(atof(*topStr) * 1000); bestTime = (DWORD)(atof(*bestStr) * 1000); if(!bestTime || (diff < bestTime)) { bestStr->Format("%0.3f", diff / 1000.0); if(diff < topTime) *topStr = *bestStr; } UpdateData(FALSE); m_event = EVENT_NONE; } } } return TRUE; } } return CDialog::PreTranslateMessage(pMsg); }
void CLoginPage::OnBnClickedSigninButton() { // TODO: Add your control notification handler code here if (CXfireCore::IsConnected()){ if (::PostThreadMessage(g_nActiveThreadID, WM_TERM_THREAD, 0, 0) == 0) { DbgMsg(L"Thread 0x%02x possibly already terminated\n", g_nActiveThreadID); } return; } CXfireCore::InitToZero(); WCHAR cTemp[0x100]; ::GetWindowText(GetDlgItem(IDC_USERNAME)->GetSafeHwnd(),cTemp,0x100); WideCharToMultiByte( CP_ACP, // ANSI Code Page 0, // No special handling of unmapped chars cTemp, // wide-character string to be converted 0x100, CXfireCore::s_cUserName, 0x100, NULL, NULL ); // Unrepresented char replacement - Use Default ::GetWindowText(GetDlgItem(IDC_PASSWORD)->GetSafeHwnd(),cTemp,0x100); WideCharToMultiByte( CP_ACP, // ANSI Code Page 0, // No special handling of unmapped chars cTemp, // wide-character string to be converted 0x100, CXfireCore::s_cPassword, 0x100, NULL, NULL ); // Unrepresented char replacement - Use Default if (strlen(CXfireCore::s_cUserName)<1 || strlen(CXfireCore::s_cPassword)<1 ) { AfxMessageBox(L"Your username or password is too short.",MB_ICONINFORMATION|MB_OK); return; } SaveUserData(); // GetDlgItem(IDC_SIGNIN_BUTTON)->EnableWindow(FALSE); GetDlgItem(IDC_CONNECT_STATUS)->SetWindowText(L"Please wait connecting..."); CClientThread* pThread = (CClientThread*)AfxBeginThread(RUNTIME_CLASS(CClientThread), THREAD_PRIORITY_NORMAL, 0, CREATE_SUSPENDED); if (!pThread) { OutputDebugString(L"CClientThread AfxBeginThread Failed!!!CRITICAL ERROR \n"); return; } m_pClientThread=pThread; g_nActiveThreadID=pThread->m_nThreadID; pThread->m_socket.m_pThread = pThread; // the thread that m_socket lives // Now start the thread. pThread->ResumeThread(); }
/////////////////////////////////////////////////////////// //功能: 压缩指定文件或文件夹 /////////////////////////////////////////////////////////// DWORD Compress(char* szInFilePath,char* szOutCabPath,char* pkey) { CCompress i_Compress; //压缩后的文件cab路径 if(szOutCabPath == NULL) { OutputDebugString("Compress ERROR: Output file name can not be NULL!"); return 2; } //设置加密KEY if(pkey != NULL) { i_Compress.SetEncryptionKey(pkey, (DWORD)strlen(pkey)); } else { #ifdef ENCRYPE_VERSION i_Compress.SetEncryptionKey("HYResources", (DWORD)strlen("HYResources")); #endif } //单字符串转换为宽字符串 szOutCabPath int nLen = MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, szOutCabPath, -1, NULL, 0 ); wchar_t* szOutCabPathW = new wchar_t[nLen+1]; MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, szOutCabPath, -1, szOutCabPathW, nLen ); //初始化 if(!i_Compress.CreateFCIContextW(szOutCabPathW)) { OutputDebugString("Compress ERROR: Could not create FCI context!"); return 3; } //单字符串转换为宽字符串 szInFilePath nLen = MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, szInFilePath, -1, NULL, 0 ); wchar_t* szInFilePathW = new wchar_t[nLen+1]; MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, szInFilePath, -1, szInFilePathW, nLen ); //开始压缩 //要压缩的文件夹或文件夹 if(PathIsDirectory(szInFilePath)) { if (!i_Compress.AddFolderW(szInFilePathW)) { OutputDebugString("Compress ERROR:AddFolder fail!\n"); return 4; } } else { wchar_t * wpNameInCab= wcsrchr(szInFilePathW,'\\'); if(wpNameInCab != NULL) wpNameInCab++; if(!i_Compress.AddFileW(szInFilePathW,wpNameInCab)) { OutputDebugString("Compress ERROR:AddFile fail!\n"); return 4; } } //释放资源 if (!i_Compress.DestroyFCIContext()) { OutputDebugString("Compress ERROR: Could not flush Cabinet!\n"); return 5; } delete [] szInFilePathW; delete [] szOutCabPathW; return 0; }
/////////////////////////////////////////////////////////// //功能: 解压到指定流 /////////////////////////////////////////////////////////// DWORD ExtractToStream(char* szCabFilePath,char *szFileFlag,char **szOutStream,char* pkey) { CExtract i_ExtrFile; CExtract::kCallbacks k_ExtrCallbacks; k_ExtrCallbacks.f_OnBeforeCopyFile = &OnBeforeCopyFile; i_ExtrFile .SetCallbacks(&k_ExtrCallbacks); if(szCabFilePath == NULL || !PathFileExists(szCabFilePath)) { OutputDebugString("Extract Error: cab file not exist!"); return 1; } if(pkey != NULL) { i_ExtrFile.SetDecryptionKey(pkey,(DWORD)strlen(pkey)); } else { #ifdef ENCRYPE_VERSION i_ExtrFile.SetDecryptionKey("HYResources",(DWORD)strlen("HYResources")); #endif } if(szFileFlag == NULL) { OutputDebugString("Extract ERROR: szFileFlag can not be NULL"); return 2; } if (!i_ExtrFile.CreateFDIContext()) { OutputDebugString("Extract ERROR: Could not create FDI context"); return 3; } int nLen = MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, szCabFilePath, -1, NULL, 0 ); wchar_t* szCabFilePathW = new wchar_t[nLen+1]; MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, szCabFilePath, -1, szCabFilePathW, nLen ); if(!i_ExtrFile.IsCabinetW(szCabFilePathW, NULL)) { OutputDebugString("Extract Error: The file is not a valid Cabinet!"); return 4; } if (!i_ExtrFile.ExtractFileW(szCabFilePathW, L"MEMORY", szFileFlag)) { OutputDebugString("Extract ERROR: Maybe the key or the FileFlag is wrong!"); return 5; } int nFileLen = 0; char *pFile = (char*)i_ExtrFile.mi_ExtractMem.GetData(&nFileLen); char* pStream = NULL; if(nFileLen == 0 || pFile == NULL) { OutputDebugString("Extract ERROR: no file is expressed!"); return 6; } try { pStream = new char[nFileLen+1]; } catch(...) { OutputDebugString("Extract ERROR: express exception"); delete [] szCabFilePathW; return 7; } strncpy(pStream,pFile,nFileLen); pStream[nFileLen] = '\0'; *szOutStream = pStream; delete [] szCabFilePathW; return 0; }
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { // TODO: Place code here. BYTE *t; char disp[128]; CBusPortThread pt; CController ct; BYTE group[6]; BYTE buf[528]; DWORD bytes; DWORD id; int i; struct tag_doorstatus ds; struct log_tag *log; pt.OpenPort(); pt.CreateThread(); Sleep(1000); ct.SetMachineAddr(1); ct.LinkBusPort(&pt); // if( ct.Test() ) { /* ds.crc = 0; ds.param = 0; ds.t.hour_start = 0; ds.t.hour_end = 23; ds.t.minute_start = 0; ds.t.minute_end = 59; ds.t.weeks = 7; ds.t.other = 0; t = (BYTE *)&ds; chk = 0; for( int i = 0; i < DOOR_STATE_SIZE; i++) chk ^= t[i]; ds.crc = chk; //F142080008000143F100B8FB010000CC8E00 ct.SetLongData( DOOR_STATE_PAGE, 0, (BYTE *)&ds,DOOR_STATE_SIZE); //F101080008000100 ct.GetLongData( DOOR_STATE_PAGE, 0, (BYTE *)&ds,DOOR_STATE_SIZE); */ /* for( i = 0; i < 6;i++) group[i] = 0; if( ct.User_Add(0x00000001, group, 6, 0) ) OutputDebugString("User_Add:Success\n"); else { wsprintf(disp,"User_Add:Fail 0x%04lx",ct.GetErrCode()); OutputDebugString("User_Add:Fail\n"); } if( ct.GetLongData( USER_ID_PAGE + 30, 0, (BYTE *)buf,200)) OutputDebugString("GetLongData:Success\n"); else { wsprintf(disp,"GetLongData:Fail 0x%04lx",ct.GetErrCode()); OutputDebugString(disp); } */ id = 0; while( 1 ) { bytes = sizeof(buf); if ( !ct.DownloadLog( id, (struct log_tag *)buf, &bytes) ) continue; bytes /= 16; for( i = 0; i < bytes; i++ ) { log = (struct log_tag *)(buf + 16 * i) ; wsprintf(disp,"[0x%08lx] Node:0x%02lx, type: 0x%2lx 20%02ld-%02ld-%02ld %02ld:%02ld:%02ld\n", log->id, log->node, log->time.year, log->time.month, log->time.day, log->time.hour, log->time.minute, log->time.second ); OutputDebugString(disp); id = log->id; } } } pt.ExitThread(); pt.ClosePort(); return 0; }
bool IntegrityCheckModule(const char *moduleFilename, const byte *expectedModuleMac, SecByteBlock *pActualMac, unsigned long *pMacFileLocation) { std::auto_ptr<MessageAuthenticationCode> mac(NewIntegrityCheckingMAC()); unsigned int macSize = mac->DigestSize(); SecByteBlock tempMac; SecByteBlock &actualMac = pActualMac ? *pActualMac : tempMac; actualMac.resize(macSize); unsigned long tempLocation; unsigned long &macFileLocation = pMacFileLocation ? *pMacFileLocation : tempLocation; macFileLocation = 0; MeterFilter verifier(new HashFilter(*mac, new ArraySink(actualMac, actualMac.size()))); // MeterFilter verifier(new FileSink("c:\\dt.tmp")); std::ifstream moduleStream; #ifdef CRYPTOPP_WIN32_AVAILABLE HMODULE h; { char moduleFilenameBuf[MAX_PATH] = ""; if (moduleFilename == NULL) { #if (_MSC_VER >= 1400 && !defined(_STLPORT_VERSION)) // ifstream doesn't support wide filename on other compilers wchar_t wideModuleFilename[MAX_PATH]; if (GetModuleFileNameW(s_hModule, wideModuleFilename, MAX_PATH) > 0) { moduleStream.open(wideModuleFilename, std::ios::in | std::ios::binary); h = GetModuleHandleW(wideModuleFilename); } else #endif { GetModuleFileNameA(s_hModule, moduleFilenameBuf, MAX_PATH); moduleFilename = moduleFilenameBuf; } } #endif if (moduleFilename != NULL) { moduleStream.open(moduleFilename, std::ios::in | std::ios::binary); #ifdef CRYPTOPP_WIN32_AVAILABLE h = GetModuleHandleA(moduleFilename); moduleFilename = NULL; } #endif } if (!moduleStream) { #ifdef CRYPTOPP_WIN32_AVAILABLE OutputDebugString("Crypto++ DLL integrity check failed. Cannot open file for reading."); #endif return false; } FileStore file(moduleStream); #ifdef CRYPTOPP_WIN32_AVAILABLE // try to hash from memory first const byte *memBase = (const byte *)h; const IMAGE_DOS_HEADER *ph = (IMAGE_DOS_HEADER *)memBase; const IMAGE_NT_HEADERS *phnt = (IMAGE_NT_HEADERS *)(memBase + ph->e_lfanew); const IMAGE_SECTION_HEADER *phs = IMAGE_FIRST_SECTION(phnt); DWORD nSections = phnt->FileHeader.NumberOfSections; size_t currentFilePos = 0; size_t checksumPos = (byte *)&phnt->OptionalHeader.CheckSum - memBase; size_t checksumSize = sizeof(phnt->OptionalHeader.CheckSum); size_t certificateTableDirectoryPos = (byte *)&phnt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY] - memBase; size_t certificateTableDirectorySize = sizeof(phnt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY]); size_t certificateTablePos = phnt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY].VirtualAddress; size_t certificateTableSize = phnt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY].Size; verifier.AddRangeToSkip(0, checksumPos, checksumSize); verifier.AddRangeToSkip(0, certificateTableDirectoryPos, certificateTableDirectorySize); verifier.AddRangeToSkip(0, certificateTablePos, certificateTableSize); while (nSections--) { switch (phs->Characteristics) { default: break; case IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ: case IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ: unsigned int sectionSize = STDMIN(phs->SizeOfRawData, phs->Misc.VirtualSize); const byte *sectionMemStart = memBase + phs->VirtualAddress; unsigned int sectionFileStart = phs->PointerToRawData; size_t subSectionStart = 0, nextSubSectionStart; do { const byte *subSectionMemStart = sectionMemStart + subSectionStart; size_t subSectionFileStart = sectionFileStart + subSectionStart; size_t subSectionSize = sectionSize - subSectionStart; nextSubSectionStart = 0; unsigned int entriesToReadFromDisk[] = {IMAGE_DIRECTORY_ENTRY_IMPORT, IMAGE_DIRECTORY_ENTRY_IAT}; for (unsigned int i=0; i<COUNTOF(entriesToReadFromDisk); i++) { const IMAGE_DATA_DIRECTORY &entry = phnt->OptionalHeader.DataDirectory[entriesToReadFromDisk[i]]; const byte *entryMemStart = memBase + entry.VirtualAddress; if (subSectionMemStart <= entryMemStart && entryMemStart < subSectionMemStart + subSectionSize) { subSectionSize = entryMemStart - subSectionMemStart; nextSubSectionStart = entryMemStart - sectionMemStart + entry.Size; } } #if defined(_MSC_VER) && _MSC_VER >= 1400 // first byte of _CRT_DEBUGGER_HOOK gets modified in memory by the debugger invisibly, so read it from file if (IsDebuggerPresent()) { if (subSectionMemStart <= (byte *)&_CRT_DEBUGGER_HOOK && (byte *)&_CRT_DEBUGGER_HOOK < subSectionMemStart + subSectionSize) { subSectionSize = (byte *)&_CRT_DEBUGGER_HOOK - subSectionMemStart; nextSubSectionStart = (byte *)&_CRT_DEBUGGER_HOOK - sectionMemStart + 1; } } #endif if (subSectionMemStart <= expectedModuleMac && expectedModuleMac < subSectionMemStart + subSectionSize) { // found stored MAC macFileLocation = (unsigned long)(subSectionFileStart + (expectedModuleMac - subSectionMemStart)); verifier.AddRangeToSkip(0, macFileLocation, macSize); } file.TransferTo(verifier, subSectionFileStart - currentFilePos); verifier.Put(subSectionMemStart, subSectionSize); file.Skip(subSectionSize); currentFilePos = subSectionFileStart + subSectionSize; subSectionStart = nextSubSectionStart; } while (nextSubSectionStart != 0); } phs++; } #endif file.TransferAllTo(verifier); #ifdef CRYPTOPP_WIN32_AVAILABLE // if that fails (could be caused by debug breakpoints or DLL base relocation modifying image in memory), // hash from disk instead if (!VerifyBufsEqual(expectedModuleMac, actualMac, macSize)) { OutputDebugString("In memory integrity check failed. This may be caused by debug breakpoints or DLL relocation.\n"); moduleStream.clear(); moduleStream.seekg(0); verifier.Initialize(MakeParameters(Name::OutputBuffer(), ByteArrayParameter(actualMac, (unsigned int)actualMac.size()))); // verifier.Initialize(MakeParameters(Name::OutputFileName(), (const char *)"c:\\dt2.tmp")); verifier.AddRangeToSkip(0, checksumPos, checksumSize); verifier.AddRangeToSkip(0, certificateTableDirectoryPos, certificateTableDirectorySize); verifier.AddRangeToSkip(0, certificateTablePos, certificateTableSize); verifier.AddRangeToSkip(0, macFileLocation, macSize); FileStore(moduleStream).TransferAllTo(verifier); } #endif if (VerifyBufsEqual(expectedModuleMac, actualMac, macSize)) return true; #ifdef CRYPTOPP_WIN32_AVAILABLE std::string hexMac; HexEncoder(new StringSink(hexMac)).PutMessageEnd(actualMac, actualMac.size()); OutputDebugString((("Crypto++ DLL integrity check failed. Actual MAC is: " + hexMac) + "\n").c_str()); #endif return false; }
/// Get center of mass of units in army (account for world wrap!) CvPlot* CvArmyAI::GetCenterOfMass(DomainTypes eDomainRequired) { int iTotalX = 0; int iTotalY = 0; int iNumUnits = 0; #if defined(MOD_BALANCE_CORE) UnitHandle pUnit = GetFirstUnit(); if (!pUnit) return NULL; int iTotalX2 = 0; int iTotalY2 = 0; int iWorldWidth = GC.getMap().getGridWidth(); int iWorldHeight = GC.getMap().getGridHeight(); //the first unit is our reference ... int iRefX = pUnit->getX(); int iRefY = pUnit->getY(); iNumUnits++; pUnit = GetNextUnit(); while(pUnit) { int iDX = pUnit->getX() - iRefX; int iDY = pUnit->getY() - iRefY; if (GC.getMap().isWrapX()) { if( iDX > +(iWorldWidth / 2)) iDX -= iWorldWidth; if( iDX < -(iWorldWidth / 2)) iDX += iWorldWidth; } if (GC.getMap().isWrapY()) { if( iDY > +(iWorldHeight / 2)) iDY -= iWorldHeight; if( iDY < -(iWorldHeight / 2)) iDY += iWorldHeight; } iTotalX += iDX; iTotalY += iDY; iTotalX2 += iDX*iDX; iTotalY2 += iDY*iDY; iNumUnits++; pUnit = GetNextUnit(); } if (iNumUnits==0) return NULL; //this is for debugging float fVarX = (iTotalX2 / (float)iNumUnits) - (iTotalX/(float)iNumUnits)*(iTotalX/(float)iNumUnits); float fVarY = (iTotalY2 / (float)iNumUnits) - (iTotalY/(float)iNumUnits)*(iTotalY/(float)iNumUnits); //finally, compute average (with rounding) int iAvgX = (iTotalX + (iNumUnits / 2)) / iNumUnits + iRefX; int iAvgY = (iTotalY + (iNumUnits / 2)) / iNumUnits + iRefY; if (fVarX > 64 || fVarY > 64) { CvString msg = CvString::format("Warning: Army %d with %d units Center of Mass (%d,%d) has a large variance (%.2f,%.2f)\n", GetID(), iNumUnits, iAvgX, iAvgY, fVarX, fVarY); OutputDebugString( msg.c_str() ); } //this handles wrapped coordinates CvPlot* pCOM = GC.getMap().plot(iAvgX, iAvgY); if (!pCOM) return NULL; //don't return it directly but use the plot of the closest unit pUnit = GetFirstUnit(); std::vector<SPlotWithScore> vPlots; while (pUnit) { if (eDomainRequired == NO_DOMAIN || pUnit->plot()->getDomain()==eDomainRequired) vPlots.push_back( SPlotWithScore(pUnit->plot(),plotDistance(*pUnit->plot(),*pCOM)) ); pUnit = GetNextUnit(); } if (vPlots.empty()) return NULL; //this sorts ascending! std::sort(vPlots.begin(),vPlots.end()); return vPlots.front().pPlot; #else CvPlot* pRtnValue = NULL; UnitHandle pUnit; int iReferenceUnitX = -1; int iWorldWidth = GC.getMap().getGridWidth(); pUnit = GetFirstUnit(); if(pUnit) { iReferenceUnitX = pUnit->getX(); } while(pUnit) { int iUnitX = pUnit->getX(); bool bWorldWrapAdjust = false; int iDiff = iUnitX - iReferenceUnitX; if(abs(iDiff) > (iWorldWidth / 2)) { bWorldWrapAdjust = true; } if(bWorldWrapAdjust) { iTotalX += iUnitX + iWorldWidth; } else { iTotalX += iUnitX; } iTotalY += pUnit->getY(); iNumUnits++; pUnit = GetNextUnit(); } if(iNumUnits > 0) { int iAverageX = (iTotalX + (iNumUnits / 2)) / iNumUnits; if(iAverageX >= iWorldWidth) { iAverageX = iAverageX - iWorldWidth; } int iAverageY = (iTotalY + (iNumUnits / 2)) / iNumUnits; pRtnValue = GC.getMap().plot(iAverageX, iAverageY); } // Domain check if (eDomainRequired != NO_DOMAIN && pRtnValue) { if (pRtnValue->isWater() && eDomainRequired == DOMAIN_LAND || !pRtnValue->isWater() && eDomainRequired == DOMAIN_SEA) { // Find an adjacent plot that works for (int iI = 0; iI < NUM_DIRECTION_TYPES; iI++) { CvPlot *pLoopPlot = plotDirection(pRtnValue->getX(), pRtnValue->getY(), ((DirectionTypes)iI)); if (pLoopPlot != NULL) { if (pLoopPlot->isWater() && eDomainRequired == DOMAIN_SEA || !pLoopPlot->isWater() && eDomainRequired == DOMAIN_LAND) { return pLoopPlot; } } } // Try two plots out if really having problems for (int iDX = -2; iDX <= 2; iDX++) { for (int iDY = -2; iDY <= 2; iDY++) { CvPlot *pLoopPlot = plotXYWithRangeCheck(pRtnValue->getX(), pRtnValue->getY(), iDX, iDY, 2); if (pLoopPlot) { if (plotDistance(pRtnValue->getX(), pRtnValue->getY(), pLoopPlot->getX(), pLoopPlot->getY()) == 2) { if (pLoopPlot->isWater() && eDomainRequired == DOMAIN_SEA || !pLoopPlot->isWater() && eDomainRequired == DOMAIN_LAND) { return pLoopPlot; } } } } } // Give up - just use location of first unit pUnit = GetFirstUnit(); pRtnValue = pUnit->plot(); } } return pRtnValue; #endif }
INT WINAPI WinMain(HINSTANCE hInst, HINSTANCE ignoreMe0, LPSTR ignoreMe1, INT ignoreMe2) { HRESULT hr = S_OK; HWND hWnd = NULL; HDC hDC = NULL; HGLRC hRC = NULL; MSG msg = {}; PIXELFORMATDESCRIPTOR pfd; LARGE_INTEGER previousTime; LARGE_INTEGER freqTime; double aveDeltaTime = 0.0; LPCSTR wndName = "Flow Snake"; IFC( InitWindow(hWnd, g_width, g_height, wndName) ); hDC = GetDC(hWnd); // Create the GL context. ZeroMemory(&pfd, sizeof(pfd)); pfd.nSize = sizeof(pfd); pfd.nVersion = 1; pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cColorBits = 24; pfd.cDepthBits = 16; pfd.iLayerType = PFD_MAIN_PLANE; int pixelFormat = ChoosePixelFormat(hDC, &pfd); SetPixelFormat(hDC, pixelFormat, &pfd); hRC = wglCreateContext(hDC); wglMakeCurrent(hDC, hRC); IFC( Init() ); QueryPerformanceFrequency(&freqTime); QueryPerformanceCounter(&previousTime); // ------------------- // Start the Game Loop // ------------------- while (msg.message != WM_QUIT) { if (PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } else { LARGE_INTEGER currentTime; __int64 elapsed; double deltaTime; QueryPerformanceCounter(¤tTime); elapsed = currentTime.QuadPart - previousTime.QuadPart; deltaTime = double(elapsed) / freqTime.QuadPart; aveDeltaTime = aveDeltaTime * 0.9 + 0.1 * deltaTime; previousTime = currentTime; IFC( Update(deltaTime) ); Render(); SwapBuffers(hDC); if (glGetError() != GL_NO_ERROR) { Error("OpenGL error.\n"); } } } Cleanup: if(hRC) wglDeleteContext(hRC); if(hDC) ReleaseDC(hWnd, hDC); if(hWnd) DestroyWindow(hWnd); char strBuf[256]; sprintf_s(strBuf, "Average frame duration = %.3f ms\n", aveDeltaTime*1000.0f); OutputDebugString(strBuf); return FAILED(hr); }
SocketTracker::SocketTracker(void):MotionTracker() { OutputDebugString("Socket Tracker Created\n"); init(); }
void LgbZOrderDlogBar::syncWithView( CDrawGUIView *pView, const CString &fileName, const std::vector<int> &zClipTics, const bool &setZClipToMax, LgbZLeanBounds_t limits, Lgb_UserZVals_t userVals ) { char buff[100]; #ifdef DEBUG sprintf_s( buff, 100, "%s %d, %d, %d, %d\n", "LgbZOrderDlogBar set to\n:ZLean, ZClip, ZClipMin, ZClipMax", userVals.zLeanVal, userVals.zClipVal, zClipTics.front(), zClipTics.back() ); OutputDebugString(buff); if( setZClipToMax ) OutputDebugString("setZClipToMax == true\n"); else OutputDebugString("setZClipToMax == false\n"); for(size_t i=0;i<zClipTics.size();i++){ sprintf_s( buff, 100, "%s %d %s %d\n", "Tic[", i, "]=: ", zClipTics[i] ); OutputDebugString(buff); } #endif this->SetWindowTextA( fileName ); m_pCDrawGuiView = pView; m_cZLimits = limits; m_cZUserVals = userVals; m_ctlSlider_ZLean.m_pDlogBar = this; m_ctlSlider_ZLean.SetRangeMin( m_cZLimits.zLeanMin ); m_ctlSlider_ZLean.SetRangeMax( m_cZLimits.zLeanMax ); m_ctlSlider_ZLean.SetPos ( m_cZUserVals.zLeanVal ); m_ctlSlider_ZClip.m_pDlogBar = this; m_ctlSlider_ZClip.SetRangeMin( zClipTics.front() ); m_ctlSlider_ZClip.SetRangeMax( zClipTics.back() ); if(setZClipToMax) m_ctlSlider_ZClip.SetPos( zClipTics.back() ); else m_ctlSlider_ZClip.SetPos( m_cZUserVals.zClipVal ); m_ctlEdit_ZClip.SetWindowTextA( intToString( m_ctlSlider_ZClip.GetPos() )); m_ctlEdit_ZLeanVal.SetWindowTextA( intToString( m_ctlSlider_ZLean.GetPos() )); m_ctlSlider_ZLean.SetTic( 1 ); m_ctlSlider_ZLean.SetTic( 2 ); m_ctlSlider_ZLean.SetTic( 3 ); m_ctlSlider_ZLean.SetTicFreq( 1 ); m_ctlSlider_ZClip.ClearTics(0); m_ctlSlider_ZClip.SetTicFreq( 1 ); for(size_t i=0;i<zClipTics.size();i++){ m_ctlSlider_ZClip.SetTic( zClipTics[i] ); } m_ctlSlider_ZClip.RedrawWindow(); UpdateData(false); }
size_t NetworkSource::DoPump(lword &byteCount, bool blockingOutput, unsigned long maxTime, bool checkDelimiter, byte delimiter) { NetworkReceiver &receiver = AccessReceiver(); lword maxSize = byteCount; byteCount = 0; bool forever = maxTime == INFINITE_TIME; Timer timer(Timer::MILLISECONDS, forever); BufferedTransformation *t = AttachedTransformation(); if (m_outputBlocked) goto DoOutput; while (true) { if (m_dataBegin == m_dataEnd) { if (receiver.EofReceived()) break; if (m_waitingForResult) { if (receiver.MustWaitForResult() && !receiver.Wait(SaturatingSubtract(maxTime, timer.ElapsedTime()), CallStack("NetworkSource::DoPump() - wait receive result", 0))) break; unsigned int recvResult = receiver.GetReceiveResult(); #if CRYPTOPP_TRACE_NETWORK OutputDebugString((IntToString((unsigned int)this) + ": Received " + IntToString(recvResult) + " bytes\n").c_str()); #endif m_dataEnd += recvResult; m_waitingForResult = false; if (!receiver.MustWaitToReceive() && !receiver.EofReceived() && m_dataEnd != m_buf.size()) goto ReceiveNoWait; } else { m_dataEnd = m_dataBegin = 0; if (receiver.MustWaitToReceive()) { if (!receiver.Wait(SaturatingSubtract(maxTime, timer.ElapsedTime()), CallStack("NetworkSource::DoPump() - wait receive", 0))) break; receiver.Receive(m_buf+m_dataEnd, m_buf.size()-m_dataEnd); m_waitingForResult = true; } else { ReceiveNoWait: m_waitingForResult = true; // call Receive repeatedly as long as data is immediately available, // because some receivers tend to return data in small pieces #if CRYPTOPP_TRACE_NETWORK OutputDebugString((IntToString((unsigned int)this) + ": Receiving " + IntToString(m_buf.size()-m_dataEnd) + " bytes\n").c_str()); #endif while (receiver.Receive(m_buf+m_dataEnd, m_buf.size()-m_dataEnd)) { unsigned int recvResult = receiver.GetReceiveResult(); #if CRYPTOPP_TRACE_NETWORK OutputDebugString((IntToString((unsigned int)this) + ": Received " + IntToString(recvResult) + " bytes\n").c_str()); #endif m_dataEnd += recvResult; if (receiver.EofReceived() || m_dataEnd > m_buf.size() /2) { m_waitingForResult = false; break; } } } } } else { m_putSize = UnsignedMin(m_dataEnd - m_dataBegin, maxSize - byteCount); if (checkDelimiter) m_putSize = std::find(m_buf+m_dataBegin, m_buf+m_dataBegin+m_putSize, delimiter) - (m_buf+m_dataBegin); DoOutput: size_t result = t->PutModifiable2(m_buf+m_dataBegin, m_putSize, 0, forever || blockingOutput); if (result) { if (t->Wait(SaturatingSubtract(maxTime, timer.ElapsedTime()), CallStack("NetworkSource::DoPump() - wait attachment", 0))) goto DoOutput; else { m_outputBlocked = true; return result; } } m_outputBlocked = false; byteCount += m_putSize; m_dataBegin += m_putSize; if (checkDelimiter && m_dataBegin < m_dataEnd && m_buf[m_dataBegin] == delimiter) break; if (maxSize != ULONG_MAX && byteCount == maxSize) break; // once time limit is reached, return even if there is more data waiting // but make 0 a special case so caller can request a large amount of data to be // pumped as long as it is immediately available if (maxTime > 0 && timer.ElapsedTime() > maxTime) break; } } return 0; }
VOID WINAPI ServiceMain (DWORD argc, LPTSTR *argv) { DWORD Status = E_FAIL; OutputDebugString(_T("My Sample Service: ServiceMain: Entry")); g_StatusHandle = RegisterServiceCtrlHandler (SERVICE_NAME, ServiceCtrlHandler); if (g_StatusHandle == NULL) { OutputDebugString(_T("My Sample Service: ServiceMain: RegisterServiceCtrlHandler returned error")); goto EXIT; } // Tell the service controller we are starting ZeroMemory (&g_ServiceStatus, sizeof (g_ServiceStatus)); g_ServiceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS; g_ServiceStatus.dwControlsAccepted = 0; g_ServiceStatus.dwCurrentState = SERVICE_START_PENDING; g_ServiceStatus.dwWin32ExitCode = 0; g_ServiceStatus.dwServiceSpecificExitCode = 0; g_ServiceStatus.dwCheckPoint = 0; if (SetServiceStatus (g_StatusHandle, &g_ServiceStatus) == FALSE) { OutputDebugString(_T("My Sample Service: ServiceMain: SetServiceStatus returned error")); } /* * Perform tasks neccesary to start the service here */ OutputDebugString(_T("My Sample Service: ServiceMain: Performing Service Start Operations")); // Create stop event to wait on later. g_ServiceStopEvent = CreateEvent (NULL, TRUE, FALSE, NULL); if (g_ServiceStopEvent == NULL) { OutputDebugString(_T("My Sample Service: ServiceMain: CreateEvent(g_ServiceStopEvent) returned error")); g_ServiceStatus.dwControlsAccepted = 0; g_ServiceStatus.dwCurrentState = SERVICE_STOPPED; g_ServiceStatus.dwWin32ExitCode = GetLastError(); g_ServiceStatus.dwCheckPoint = 1; if (SetServiceStatus (g_StatusHandle, &g_ServiceStatus) == FALSE) { OutputDebugString(_T("My Sample Service: ServiceMain: SetServiceStatus returned error")); } goto EXIT; } // Tell the service controller we are started g_ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP; g_ServiceStatus.dwCurrentState = SERVICE_RUNNING; g_ServiceStatus.dwWin32ExitCode = 0; g_ServiceStatus.dwCheckPoint = 0; if (SetServiceStatus (g_StatusHandle, &g_ServiceStatus) == FALSE) { OutputDebugString(_T("My Sample Service: ServiceMain: SetServiceStatus returned error")); } // Start the thread that will perform the main task of the service HANDLE hThread = CreateThread (NULL, 0, ServiceWorkerThread, NULL, 0, NULL); OutputDebugString(_T("My Sample Service: ServiceMain: Waiting for Worker Thread to complete")); // Wait until our worker thread exits effectively signaling that the service needs to stop WaitForSingleObject (hThread, INFINITE); OutputDebugString(_T("My Sample Service: ServiceMain: Worker Thread Stop Event signaled")); /* * Perform any cleanup tasks */ OutputDebugString(_T("My Sample Service: ServiceMain: Performing Cleanup Operations")); CloseHandle (g_ServiceStopEvent); g_ServiceStatus.dwControlsAccepted = 0; g_ServiceStatus.dwCurrentState = SERVICE_STOPPED; g_ServiceStatus.dwWin32ExitCode = 0; g_ServiceStatus.dwCheckPoint = 3; if (SetServiceStatus (g_StatusHandle, &g_ServiceStatus) == FALSE) { OutputDebugString(_T("My Sample Service: ServiceMain: SetServiceStatus returned error")); } EXIT: OutputDebugString(_T("My Sample Service: ServiceMain: Exit")); return; }
lword NetworkSink::DoFlush(unsigned long maxTime, size_t targetSize) { NetworkSender &sender = AccessSender(); bool forever = maxTime == INFINITE_TIME; Timer timer(Timer::MILLISECONDS, forever); unsigned int totalFlushSize = 0; while (true) { if (m_buffer.CurrentSize() <= targetSize) break; if (m_needSendResult) { if (sender.MustWaitForResult() && !sender.Wait(SaturatingSubtract(maxTime, timer.ElapsedTime()), CallStack("NetworkSink::DoFlush() - wait send result", 0))) break; unsigned int sendResult = sender.GetSendResult(); #if CRYPTOPP_TRACE_NETWORK OutputDebugString((IntToString((unsigned int)this) + ": Sent " + IntToString(sendResult) + " bytes\n").c_str()); #endif m_buffer.Skip(sendResult); totalFlushSize += sendResult; m_needSendResult = false; if (!m_buffer.AnyRetrievable()) break; } unsigned long timeOut = maxTime ? SaturatingSubtract(maxTime, timer.ElapsedTime()) : 0; if (sender.MustWaitToSend() && !sender.Wait(timeOut, CallStack("NetworkSink::DoFlush() - wait send", 0))) break; size_t contiguousSize = 0; const byte *block = m_buffer.Spy(contiguousSize); #if CRYPTOPP_TRACE_NETWORK OutputDebugString((IntToString((unsigned int)this) + ": Sending " + IntToString(contiguousSize) + " bytes\n").c_str()); #endif sender.Send(block, contiguousSize); m_needSendResult = true; if (maxTime > 0 && timeOut == 0) break; // once time limit is reached, return even if there is more data waiting } m_byteCountSinceLastTimerReset += totalFlushSize; ComputeCurrentSpeed(); if (m_buffer.IsEmpty() && !m_needSendResult) { if (m_eofState == EOF_PENDING_SEND) { sender.SendEof(); m_eofState = sender.MustWaitForEof() ? EOF_PENDING_DELIVERY : EOF_DONE; } while (m_eofState == EOF_PENDING_DELIVERY) { unsigned long timeOut = maxTime ? SaturatingSubtract(maxTime, timer.ElapsedTime()) : 0; if (!sender.Wait(timeOut, CallStack("NetworkSink::DoFlush() - wait EOF", 0))) break; if (sender.EofSent()) m_eofState = EOF_DONE; } } return totalFlushSize; }
// returns false if message not handled bool CFrameHolder::ProcessNcMessage(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT& lResult) { #ifdef _DEBUG if (mb_NcAnimate) { wchar_t szDbg[1024], szMsg[128], szInfo[255]; szInfo[0] = 0; switch (uMsg) { case WM_ERASEBKGND: lstrcpy(szMsg, L"WM_ERASEBKGND"); break; case WM_PAINT: lstrcpy(szMsg, L"WM_PAINT"); break; case WM_NCPAINT: lstrcpy(szMsg, L"WM_NCPAINT"); break; case WM_NCACTIVATE: lstrcpy(szMsg, L"WM_NCACTIVATE"); break; case WM_NCCALCSIZE: lstrcpy(szMsg, L"WM_NCCALCSIZE"); break; case WM_NCHITTEST: lstrcpy(szMsg, L"WM_NCHITTEST"); break; case WM_NCLBUTTONDOWN: lstrcpy(szMsg, L"WM_NCLBUTTONDOWN"); break; case WM_NCMOUSEMOVE: lstrcpy(szMsg, L"WM_NCMOUSEMOVE"); break; case WM_NCMOUSELEAVE: lstrcpy(szMsg, L"WM_NCMOUSELEAVE"); break; case WM_NCMOUSEHOVER: lstrcpy(szMsg, L"WM_NCMOUSEHOVER"); break; case WM_NCLBUTTONDBLCLK: lstrcpy(szMsg, L"WM_NCLBUTTONDBLCLK"); break; case 0xAE: /*WM_NCUAHDRAWCAPTION*/ lstrcpy(szMsg, L"WM_NCUAHDRAWCAPTION"); break; case 0xAF: /*WM_NCUAHDRAWFRAME*/ lstrcpy(szMsg, L"WM_NCUAHDRAWFRAME"); break; case 0x31E: /*WM_DWMCOMPOSITIONCHANGED*/ lstrcpy(szMsg, L"WM_DWMCOMPOSITIONCHANGED"); break; case WM_WINDOWPOSCHANGED: lstrcpy(szMsg, L"WM_WINDOWPOSCHANGED"); break; case WM_SYSCOMMAND: lstrcpy(szMsg, L"WM_SYSCOMMAND"); break; case WM_GETTEXT: lstrcpy(szMsg, L"WM_GETTEXT"); break; case WM_PRINT: lstrcpy(szMsg, L"WM_PRINT"); break; case WM_PRINTCLIENT: lstrcpy(szMsg, L"WM_PRINTCLIENT"); break; case WM_GETMINMAXINFO: lstrcpy(szMsg, L"WM_GETMINMAXINFO"); break; case WM_WINDOWPOSCHANGING: lstrcpy(szMsg, L"WM_WINDOWPOSCHANGING"); break; case WM_MOVE: lstrcpy(szMsg, L"WM_MOVE"); wsprintf(szInfo, L"{%ix%i}", (int)(short)LOWORD(lParam), (int)(short)HIWORD(lParam)); break; case WM_SIZE: lstrcpy(szMsg, L"WM_SIZE"); wsprintf(szInfo, L"%s {%ix%i}", (wParam==SIZE_MAXHIDE) ? L"SIZE_MAXHIDE" : (wParam==SIZE_MAXIMIZED) ? L"SIZE_MAXIMIZED" : (wParam==SIZE_MAXSHOW) ? L"SIZE_MAXSHOW" : (wParam==SIZE_MINIMIZED) ? L"SIZE_MINIMIZED" : (wParam==SIZE_RESTORED) ? L"SIZE_RESTORED" : L"???", (int)(short)LOWORD(lParam), (int)(short)HIWORD(lParam)); break; default: wsprintf(szMsg, L"%u=x%X", uMsg, uMsg); } wsprintf(szDbg, L"MsgInAnimage(%s, %u, %u%s%s)\n", szMsg, (DWORD)wParam, (DWORD)lParam, szInfo[0] ? L" - " : L"", szInfo); OutputDebugString(szDbg); } #endif bool lbRc; static POINT ptLastNcClick = {}; switch (uMsg) { case WM_ERASEBKGND: DBGFUNCTION(L"WM_ERASEBKGND \n"); lResult = TRUE; return true; //return false; case WM_PAINT: DBGFUNCTION(L"WM_PAINT \n"); lResult = OnPaint(hWnd, FALSE); return true; case WM_NCPAINT: DBGFUNCTION(L"WM_NCPAINT \n"); lResult = OnNcPaint(hWnd, uMsg, wParam, lParam); return true; case WM_NCACTIVATE: DBGFUNCTION(L"WM_NCACTIVATE \n"); lResult = OnNcActivate(hWnd, uMsg, wParam, lParam); return true; case WM_NCCALCSIZE: DBGFUNCTION(L"WM_NCCALCSIZE \n"); lResult = OnNcCalcSize(hWnd, uMsg, wParam, lParam); return true; case WM_NCHITTEST: DBGFUNCTION(L"WM_NCHITTEST \n"); lResult = OnNcHitTest(hWnd, uMsg, wParam, lParam); return true; case WM_NCLBUTTONDOWN: case WM_NCLBUTTONUP: case WM_NCRBUTTONDOWN: case WM_NCRBUTTONUP: case WM_NCMBUTTONDOWN: case WM_NCMBUTTONUP: case WM_NCMOUSEMOVE: case WM_NCMOUSELEAVE: case WM_NCMOUSEHOVER: #ifdef _DEBUG switch (uMsg) { case WM_NCLBUTTONDOWN: DBGFUNCTION(L"WM_NCLBUTTONDOWN \n"); break; case WM_NCLBUTTONUP: DBGFUNCTION(L"WM_NCLBUTTONUP \n"); break; case WM_NCRBUTTONDOWN: DBGFUNCTION(L"WM_NCRBUTTONDOWN \n"); break; case WM_NCRBUTTONUP: DBGFUNCTION(L"WM_NCRBUTTONUP \n"); break; case WM_NCMBUTTONDOWN: DBGFUNCTION(L"WM_NCMBUTTONDOWN \n"); break; case WM_NCMBUTTONUP: DBGFUNCTION(L"WM_NCMBUTTONUP \n"); break; case WM_NCMOUSEMOVE: DBGFUNCTION(L"WM_NCMOUSEMOVE \n"); break; case WM_NCMOUSELEAVE: DBGFUNCTION(L"WM_NCMOUSELEAVE \n"); break; case WM_NCMOUSEHOVER: DBGFUNCTION(L"WM_NCMOUSEHOVER \n"); break; } #endif ptLastNcClick = MakePoint(LOWORD(lParam),HIWORD(lParam)); if ((uMsg == WM_NCMOUSEMOVE) || (uMsg == WM_NCLBUTTONUP)) gpConEmu->isSizing(); // могло не сброситься, проверим RedrawLock(); lbRc = gpConEmu->mp_TabBar->ProcessTabMouseEvent(hWnd, uMsg, wParam, lParam, lResult); RedrawUnlock(); if (!lbRc) { if ((wParam == HTSYSMENU && uMsg == WM_NCLBUTTONDOWN) /*|| (wParam == HTCAPTION && uMsg == WM_NCRBUTTONDOWN)*/) { //if (uMsg == WM_NCRBUTTONDOWN) // gpConEmu->ShowSysmenu((SHORT)LOWORD(lParam),(SHORT)HIWORD(lParam)); //else DWORD nCurTick = GetTickCount(); DWORD nOpenDelay = nCurTick - gpConEmu->mn_SysMenuOpenTick; DWORD nCloseDelay = nCurTick - gpConEmu->mn_SysMenuCloseTick; DWORD nDoubleTime = GetDoubleClickTime(); if (gpConEmu->mn_SysMenuOpenTick && (nOpenDelay < nDoubleTime)) { PostMessage(ghWnd, WM_SYSCOMMAND, SC_CLOSE, 0); } else if (gpConEmu->mn_SysMenuCloseTick && (nCloseDelay < (nDoubleTime/2))) { // Пропустить - кликом закрыли меню int nDbg = 0; } else { gpConEmu->ShowSysmenu(); } lResult = 0; lbRc = true; } } return lbRc; //case WM_LBUTTONDBLCLK: // { // // Глюк? DblClick по иконке приводит к WM_LBUTTONDBLCLK вместо WM_NCLBUTTONDBLCLK // POINT pt = MakePoint(LOWORD(lParam),HIWORD(lParam)); // if (gpConEmu->PtDiffTest(pt, ptLastNcClick.x, ptLastNcClick.y, 4)) // { // PostMessage(ghWnd, WM_SYSCOMMAND, SC_CLOSE, 0); // lResult = 0; // return true; // } // } // return false; case WM_MOUSEMOVE: DBGFUNCTION(L"WM_MOUSEMOVE \n"); RedrawLock(); if (gpConEmu->mp_TabBar->GetHoverTab() != -1) { gpConEmu->mp_TabBar->HoverTab(-1); } // Ну и с кнопок убрать подсветку, если была gpConEmu->mp_TabBar->Toolbar_UnHover(); RedrawUnlock(); return false; case WM_NCLBUTTONDBLCLK: if (wParam == HTCAPTION) { mb_NcAnimate = TRUE; } if (wParam == HT_CONEMUTAB) { //RedrawLock(); -- чтобы отрисовать "клик" по кнопке lbRc = gpConEmu->mp_TabBar->ProcessTabMouseEvent(hWnd, uMsg, wParam, lParam, lResult); //RedrawUnlock(); } else if (gpConEmu->OnMouse_NCBtnDblClk(hWnd, uMsg, wParam, lParam)) { lResult = 0; // DblClick на рамке - ресайз по ширине/высоте рабочей области экрана } else { lResult = DefWindowProc(hWnd, uMsg, wParam, lParam); } if (wParam == HTCAPTION) { mb_NcAnimate = FALSE; } return true; case WM_KEYDOWN: case WM_KEYUP: if (gpSet->isTabSelf && (wParam == VK_TAB || gpConEmu->mp_TabBar->IsInSwitch())) { if (isPressed(VK_CONTROL) && !isPressed(VK_MENU) && !isPressed(VK_LWIN) && !isPressed(VK_RWIN)) { if (gpConEmu->mp_TabBar->ProcessTabKeyboardEvent(hWnd, uMsg, wParam, lParam, lResult)) { return true; } } } return false; //case WM_NCCREATE: gpConEmu->CheckGlassAttribute(); return false; case 0xAE: /*WM_NCUAHDRAWCAPTION*/ lResult = OnDwmMessage(hWnd, uMsg, wParam, lParam); return true; case 0xAF: /*WM_NCUAHDRAWFRAME*/ lResult = OnDwmMessage(hWnd, uMsg, wParam, lParam); return true; case 0x31E: /*WM_DWMCOMPOSITIONCHANGED*/ lResult = OnDwmMessage(hWnd, uMsg, wParam, lParam); return true; case WM_WINDOWPOSCHANGED: lResult = OnWindowPosChanged(hWnd, uMsg, wParam, lParam); return true; case WM_SYSCOMMAND: if (wParam == SC_MAXIMIZE || wParam == SC_MINIMIZE || wParam == SC_RESTORE) { mb_NcAnimate = TRUE; //GetWindowText(hWnd, ms_LastCaption, countof(ms_LastCaption)); //SetWindowText(hWnd, L""); } lResult = gpConEmu->OnSysCommand(hWnd, wParam, lParam); if (wParam == SC_MAXIMIZE || wParam == SC_MINIMIZE || wParam == SC_RESTORE) { mb_NcAnimate = FALSE; //SetWindowText(hWnd, ms_LastCaption); } return true; case WM_GETTEXT: //TODO: Во время анимации Maximize/Restore/Minimize заголовок отрисовывается //TODO: системой, в итоге мелькает текст и срезаются табы //TODO: Сделаем, пока, чтобы текст хотя бы не мелькал... if (mb_NcAnimate && gpSet->isTabsInCaption) { if (wParam && lParam) { *(wchar_t*)lParam = 0; } lResult = 0; return true; } break; default: break; } return false; }
void XSLTReport::ProjectReport(HWND hwnd, TCHAR *pProjXML, TCHAR *pXSLTName, DataManager *pDataMan) { BOOL bResult = FALSE; short sResult = FALSE; HRESULT hr; MSXML2::IXMLDOMDocument2 *pStyleSheet=NULL; MSXML2::IXMLDOMDocument2 *pDOMObject=NULL; MSXML2::IXMLDOMDocument2 *pIXMLDOMDocument = NULL; MSXML2::IXSLTemplate *pIXSLTemplate=NULL; MSXML2::IXSLProcessor *pIXSLProcessor=NULL; VARIANT varValue; BSTR xslStr = SysAllocString(pXSLTName); try { hr = CoCreateInstance(__uuidof(MSXML2::XSLTemplate60), NULL, CLSCTX_SERVER, __uuidof(MSXML2::IXSLTemplate), (LPVOID*)(&pIXSLTemplate)); SUCCEEDED(hr) ? 0 : throw hr; if(pIXSLTemplate) { OutputDebugString(_T("xform 1\n")); hr=CoCreateInstance(__uuidof(MSXML2::FreeThreadedDOMDocument60), NULL, CLSCTX_SERVER, __uuidof(MSXML2::IXMLDOMDocument2), (LPVOID*)(&pStyleSheet)); SUCCEEDED(hr) ? 0 : throw hr; if(pStyleSheet) { OutputDebugString(_T("xform 2\n")); hr=pStyleSheet->put_async(VARIANT_FALSE); if(SUCCEEDED(hr)) { VARIANTARG varg; VariantInit(&varg); varg.vt = VT_BSTR; varg.bstrVal = xslStr; hr=pStyleSheet->load(varg, &sResult); if(sResult == VARIANT_FALSE) { OutputError(pStyleSheet); } if(SUCCEEDED(hr) && (sResult==VARIANT_TRUE)) { hr=pIXSLTemplate->putref_stylesheet(pStyleSheet); if(FAILED(hr)) { OutputError(pStyleSheet); OutErrorInfo(pStyleSheet); } if(SUCCEEDED(hr)) { OutputDebugString(_T("xform 4\n")); hr=pIXSLTemplate->createProcessor(&pIXSLProcessor); SUCCEEDED(hr) ? 0 : throw hr; if(pIXSLProcessor) { OutputDebugString(_T("xform 5\n")); hr=CoCreateInstance(__uuidof(MSXML2::FreeThreadedDOMDocument60), NULL, CLSCTX_SERVER, __uuidof(MSXML2::IXMLDOMDocument2), (LPVOID*)(&pIXMLDOMDocument)); SUCCEEDED(hr) ? 0 : throw hr; if(pIXMLDOMDocument) { hr=pIXMLDOMDocument->put_async(VARIANT_FALSE); if(SUCCEEDED(hr)) { BSTR projXML = SysAllocString(pProjXML); hr=pIXMLDOMDocument->loadXML(projXML, &sResult); SysFreeString(projXML); if(sResult == VARIANT_FALSE) { OutputError(pIXMLDOMDocument); } else if(SUCCEEDED(hr) && (sResult==VARIANT_TRUE)) { hr=pIXSLProcessor->put_input(_variant_t(pIXMLDOMDocument)); if(SUCCEEDED(hr)) { StringBuffer sbFriendlyName(512); unsigned long nameBufferLen = 512; GetUserNameEx(NameDisplay, sbFriendlyName, &nameBufferLen); sbFriendlyName.setLength(nameBufferLen); BSTR friendlyName = SysAllocString(sbFriendlyName); BSTR fnameParam = SysAllocString(_T("friendly-name")); BSTR blank = SysAllocString(_T("")); BSTR userParam = SysAllocString(_T("username")); BSTR userValue = SysAllocString(pDataMan->GetUsername()); DayManager *pDayMan = pDataMan->GetDayManagerInstance(); unsigned __int64 activeDate = pDayMan->GetActiveDate(); unsigned __int64 endDate = ModelUtils::UNITS_PER_DAY + activeDate; BSTR dayParam = SysAllocString(_T("day-of-report")); StringBuffer sb(2048); ModelUtils::toHexString(activeDate, sb); BSTR dayValue = SysAllocString(sb); BSTR startParam = SysAllocString(_T("start-of-report")); ModelUtils::toHexString(activeDate, sb); BSTR startValue = SysAllocString(sb); BSTR endParam = SysAllocString(_T("end-of-report")); ModelUtils::toHexString(endDate, sb); BSTR endValue = SysAllocString(sb); hr=pIXSLProcessor->addParameter(fnameParam, _variant_t(friendlyName), blank); hr=pIXSLProcessor->addParameter(userParam, _variant_t(userValue), blank); hr=pIXSLProcessor->addParameter(dayParam, _variant_t(dayValue), blank); hr = pIXSLProcessor->addParameter(startParam, _variant_t(startValue), blank); hr = pIXSLProcessor->addParameter(endParam, _variant_t(endValue), blank); if(SUCCEEDED(hr))bResult=TRUE; SysFreeString(blank); SysFreeString(userParam); SysFreeString(userValue); SysFreeString(dayParam); SysFreeString(dayValue); SysFreeString(startParam); SysFreeString(startValue); SysFreeString(endParam); SysFreeString(endValue); SysFreeString(friendlyName); SysFreeString(fnameParam); hr=pIXSLProcessor->transform(&sResult); if(SUCCEEDED(hr)&&(sResult==VARIANT_TRUE)) { OutputDebugString(_T("xform 11\n")); pIXSLProcessor->get_output( &varValue); /* ::MessageBox(NULL, _bstr_t(varValue), _T("Transformed Output"), MB_OK);*/ SYSTEMTIME st = ModelUtils::I64ToSystemTime(activeDate); sb.flush(); TCHAR *pReportFilename = CreateProjectName(st, pDataMan->GetUsername(), sb); HANDLE hFile = CreateFile(pReportFilename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL); if(hFile != INVALID_HANDLE_VALUE) { // _bstr_t html(varValue); DWORD length = _tcslen(varValue.bstrVal) * sizeof(TCHAR); DWORD written = 0; BOOL b = WriteFile(hFile, varValue.bstrVal, length, &written, NULL); CloseHandle(hFile); if(b && written == length) { ShellExecute(hwnd, _T("open"), pReportFilename, _T(""), _T("C:\\"), SW_SHOWNORMAL); } } } } } } RELEASE(pIXMLDOMDocument); } } } } } RELEASE(pStyleSheet); } RELEASE(pIXSLTemplate); } } catch(...) { OutputDebugString(_T("Caught XSLT Exception....\n")); CHECK_AND_RELEASE(pIXSLTemplate); CHECK_AND_RELEASE(pStyleSheet); CHECK_AND_RELEASE(pIXMLDOMDocument); CHECK_AND_RELEASE(pDOMObject); } SysFreeString(xslStr); }
void CLoginPage::OnSize(UINT nType, int cx, int cy) { //AfxMessageBox(L"CLoginPage::OnSize"); //CXPropertyPage::OnSize(nType, cx, cy); OutputDebugString(L"CLoginPage::OnSize \n"); SIPINFO sipInfo={0}; sipInfo.cbSize=sizeof(SIPINFO); if (!bInitCtrlsPos) return; if (SipGetInfo(&sipInfo)){ if ((sipInfo.fdwFlags&SIPF_ON)==SIPF_ON){ OutputDebugString(L"Keyboard SIPF_ON \n"); GetDlgItem(IDC_STATIC_LOGO)->ShowWindow(SW_HIDE); GetDlgItem(IDC_STATIC_VERSION)->ShowWindow(SW_HIDE); GetDlgItem(IDC_USERNAME)->SetWindowPos(&wndTop,rcUsername.left,rcUsername.top-nResizeTop,0,0, SWP_NOSIZE |SWP_SHOWWINDOW); GetDlgItem(IDC_PASSWORD)->SetWindowPos(&wndTop,rcPassword.left,rcPassword.top-nResizeTop,0,0, SWP_NOSIZE |SWP_SHOWWINDOW); GetDlgItem(IDC_STATIC_PASSWORD)->SetWindowPos(&wndTop,rcStaticPassword.left,rcStaticPassword.top-nResizeTop,0,0, SWP_NOSIZE |SWP_SHOWWINDOW); GetDlgItem(IDC_STATIC_USERNAME)->SetWindowPos(&wndTop,rcStaticUsername.left,rcStaticUsername.top-nResizeTop,0,0, SWP_NOSIZE |SWP_SHOWWINDOW); GetDlgItem(IDC_CONNECT_STATUS)->SetWindowPos(&wndTop,rcConnectStatus.left,rcConnectStatus.top-nResizeTop,0,0, SWP_NOSIZE |SWP_SHOWWINDOW); GetDlgItem(IDC_SIGNIN_BUTTON)->SetWindowPos(&wndTop,rcSigninButton.left,rcSigninButton.top-nResizeTop,0,0, SWP_NOSIZE |SWP_SHOWWINDOW); }else if ((sipInfo.fdwFlags&SIPF_OFF)==SIPF_OFF){ OutputDebugString(L"Keyboard SIPF_OFF \n"); GetDlgItem(IDC_STATIC_LOGO)->ShowWindow(SW_SHOW); GetDlgItem(IDC_STATIC_VERSION)->ShowWindow(SW_SHOW); GetDlgItem(IDC_USERNAME)->SetWindowPos(&wndTop,rcUsername.left,rcUsername.top,0,0, SWP_NOSIZE |SWP_SHOWWINDOW); GetDlgItem(IDC_PASSWORD)->SetWindowPos(&wndTop,rcPassword.left,rcPassword.top,0,0, SWP_NOSIZE |SWP_SHOWWINDOW); GetDlgItem(IDC_STATIC_PASSWORD)->SetWindowPos(&wndTop,rcStaticPassword.left,rcStaticPassword.top,0,0, SWP_NOSIZE |SWP_SHOWWINDOW); GetDlgItem(IDC_STATIC_USERNAME)->SetWindowPos(&wndTop,rcStaticUsername.left,rcStaticUsername.top,0,0, SWP_NOSIZE |SWP_SHOWWINDOW); GetDlgItem(IDC_CONNECT_STATUS)->SetWindowPos(&wndTop,rcConnectStatus.left,rcConnectStatus.top,0,0, SWP_NOSIZE |SWP_SHOWWINDOW); GetDlgItem(IDC_SIGNIN_BUTTON)->SetWindowPos(&wndTop,rcSigninButton.left,rcSigninButton.top,0,0, SWP_NOSIZE |SWP_SHOWWINDOW); } }else{ OutputDebugString(L"SipGetInfo Failed \n"); } }
void rtspStream::GetOneFrame() { // when get one frame if (m_SessionList.size() < 1) return; char tmp[100] = {0}; //the number of frame needs added 1 frame_num ==0 ? pPicIn->i_pts =frame_num++ : pPicIn->i_pts =frame_num++ - 1; //encode int iNal = 0; int dataSize = 0; unsigned char* pData; if( x264_encoder_encode(pX264Handle,&pNals,&iNal,pPicIn,pPicOut) >0) { for (int j = 0; j < iNal; ++j) { dataSize = pNals[j].i_payload; pData = pNals[j].p_payload; //h264 NALU header's bit offset: if key frame the bitoffset is 3,otherwise,4 int bitoffset = pNals[j].i_type != 5 ? 4 : 3; dataSize -=bitoffset; pData+=bitoffset; sprintf(tmp,"the nalu data size is %d\tthe nalu type is %d\n",dataSize,pNals[j].i_type); OutputDebugString(tmp); // get RTP Header for one NALU if (dataSize <RTP_PACKAGE_MAX_SIZE) { PrepareRTPHeader(); int size = dataSize; memset(m_pSendData,0,RTP_PACKAGE_MAX_SIZE+RTP_HEADER_SIZE); memcpy(m_pSendData,m_pRtpHeader,sizeof(RTPHeader)); memcpy(m_pSendData+RTP_HEADER_SIZE,(const char*)pData, size); int sendsize = 0; //send data for (auto i = m_SessionList.begin(); i != m_SessionList.end(); i++) { if (i->second->state == 1) { sendsize = \ sendto(m_SendSocket,(const char*)m_pSendData,size+RTP_HEADER_SIZE,0, (SOCKADDR *) &i->second->clientAddr,sizeof(i->second->clientAddr)); sprintf(tmp,"send size is %d\n",sendsize); OutputDebugString(tmp); } } } else { unsigned char header1 = pData[0]; unsigned char header2 = NULL; pData++; int k = 0, last = 0; k = dataSize / (RTP_PACKAGE_MAX_SIZE) ; last = dataSize % RTP_PACKAGE_MAX_SIZE; int t = 0;//用于指示当前发送的是第几个分片RTP包 int sendSize = 0; unsigned char fu_ind; unsigned char fu_hdr; while(t <= k) { PrepareRTPHeader(); if(!t)//发送一个需要分片的NALU的第一个分片,置FU HEADER的S位,t = 0时进入此逻辑。 { fu_ind = (header1 & 0xE0) | 28; fu_hdr = 0x80 | (header1& 0x1F); header1 = fu_ind; header2 = fu_hdr; sendSize = RTP_PACKAGE_MAX_SIZE+RTP_HEADER_SIZE +2; } //既不是第一个分片,也不是最后一个分片的处理。 else if(t < k && 0 != t) { fu_ind = header1; // FU indicator fu_hdr = header2&~0x80 ; // FU header (no S bit) sendSize = RTP_PACKAGE_MAX_SIZE+RTP_HEADER_SIZE + 2; } //发送一个需要分片的NALU的非第一个分片,清零FU HEADER的S位,如果该分片是该NALU的最后一个分片,置FU HEADER的E位 else if(k == t )//发送的是最后一个分片,注意最后一个分片的长度可能超过1400字节(当 l> 1386时)。 { fu_ind = header1; // FU indicator fu_hdr = header2&~0x80 ; // FU header (no S bit) fu_hdr |= 0x40; sendSize = last +RTP_HEADER_SIZE + 2; } memset(m_pSendData,0,RTP_PACKAGE_MAX_SIZE+RTP_HEADER_SIZE + 2); memcpy(m_pSendData,m_pRtpHeader,sizeof(RTPHeader)); memcpy(m_pSendData+RTP_HEADER_SIZE,&fu_ind,1); memcpy(m_pSendData+RTP_HEADER_SIZE+1,&fu_hdr,1); memcpy(m_pSendData+RTP_HEADER_SIZE+2,(const char*)pData, sendSize - 14); int sendsize1 = 0; //send data for (auto i = m_SessionList.begin(); i != m_SessionList.end(); i++) { if (i->second->state == 1) { sendsize1 = \ sendto(m_SendSocket,(const char*)m_pSendData,sendSize,0, (SOCKADDR *) &i->second->clientAddr,sizeof(i->second->clientAddr)); sprintf(tmp,"send size is %d\n",sendsize1); OutputDebugString(tmp); } } pData+=sendSize-14; t++; } } //timestamp adds one duration m_nTimeStamp += RTP_CLOCK_DURATION/m_nFPS; } } }
bool CGameEngineGL::BInitializeGraphics() { int windowX = SDL_WINDOWPOS_CENTERED; int windowY = SDL_WINDOWPOS_CENTERED; int nWindowWidth, nWindowHeight; if( !m_pHmd ) { nWindowWidth = m_nWindowWidth = 1024; nWindowHeight = m_nWindowHeight = 768; } else { uint32_t unWidth, unHeight; m_pHmd->GetWindowBounds( &windowX, &windowY, &unWidth, &unHeight ); nWindowWidth = unWidth; nWindowHeight = unHeight; m_nWindowWidth = 640; m_nWindowHeight = 480; } SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 ); m_window = SDL_CreateWindow( "SteamworksExample", windowX, windowY, nWindowWidth, nWindowHeight, SDL_WINDOW_OPENGL ); if ( !m_window ) { OutputDebugString( "Couldn't create SDL window: " ); OutputDebugString( SDL_GetError() ); OutputDebugString( "\n" ); return false; } m_context = SDL_GL_CreateContext( m_window ); if ( !m_context ) { OutputDebugString( "Couldn't create OpenGL context: " ); OutputDebugString( SDL_GetError() ); OutputDebugString( "\n" ); return false; } GLenum err = glewInit(); if( err != GLEW_OK ) { fprintf(stderr, "glewInit failed with %s\n", glewGetErrorString( err ) ); return false; } SDL_GL_SetSwapInterval( 1 ); // Clear any errors glGetError(); glClearDepth( 1.0f ); glClearColor( 0.0f, 0.0f, 0.0f, 1.0f ); glEnable( GL_BLEND ); glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); glDisable( GL_CULL_FACE ); glDisable( GL_ALPHA_TEST ); glDisable( GL_STENCIL_TEST ); glDisable( GL_SCISSOR_TEST ); glDisable( GL_LIGHTING ); glDisable( GL_DEPTH_TEST ); glDisable( GL_FOG ); glDepthMask( GL_FALSE ); // We always need these two glEnableClientState( GL_COLOR_ARRAY ); glEnableClientState( GL_VERTEX_ARRAY ); // This we'll enable as needed glDisableClientState( GL_TEXTURE_COORD_ARRAY ); glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef( 0, 0, 0 ); glMatrixMode( GL_TEXTURE ); glLoadIdentity(); glTranslatef( 0, 0, 0 ); glDepthRange( 0.0f, 1.0f ); // create some other VR-related resources if( m_pHmd ) { if( !m_pVRGLHelper->BInit( m_pHmd ) ) { OutputDebugString( "Unable to init VRGLHelper\n" ); return false; } m_pVRGLHelper->InitUIRenderTarget( m_nWindowWidth, m_nWindowHeight ); m_pVRGLHelper->BInitPredistortRenderTarget(); } AdjustViewport(); return true; }
HANDLE WINAPI My_CreateFileW(LPCWSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) { char *buffer = (char *)calloc(BUFSIZE, sizeof(char)); char *access = (char *)calloc(255, sizeof(char)); HANDLE hFile; #ifdef _DEBUG OutputDebugString("[cuckoo] Hook CreateFileW IN\n"); #endif hFile = Real_CreateFileW(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile); if(hFile == INVALID_HANDLE_VALUE) sprintf_s(buffer, BUFSIZE, "\"filesystem\",\"CreateFileW\",\"FAILURE\",\"\",\"lpFileName->%ws\",\"dwDesiredAccess->%s\"\r\n", lpFileName, access); else sprintf_s(buffer, BUFSIZE, "\"filesystem\",\"CreateFileW\",\"SUCCESS\",\"0x%08x\",\"lpFileName->%ws\",\"dwDesiredAccess->%s\"\r\n", hFile, lpFileName, access); #ifdef _DEBUG OutputDebugString(buffer); OutputDebugString("[cuckoo] Hook CreateFileW OUT\n"); #endif // Send path of files being created on the file system to cuckoo // process, in order to be later dumped and stored. if(dwDesiredAccess == GENERIC_WRITE || dwDesiredAccess == GENERIC_ALL || dwDesiredAccess == 0xc0000000) { memset(buffer, 0, BUFSIZE); sprintf_s(buffer, BUFSIZE, "FILE:%ws", lpFileName); } #ifdef _DEBUG OutputDebugString(buffer); OutputDebugString("[cuckoo] Hook CreateFileW OUT\n"); #endif free(access); free(buffer); return hFile; }
//----------------------------------------------------------------------------- // Purpose: Constructor for game engine instance //----------------------------------------------------------------------------- CGameEngineGL::CGameEngineGL( bool bUseVR ) { g_engine = this; m_bEngineReadyForUse = false; m_bShuttingDown = false; m_window = NULL; m_context = NULL; m_nWindowWidth = 0; m_nWindowHeight = 0; m_ulPreviousGameTickCount = 0; m_ulGameTickCount = 0; m_unVoiceChannelCount = 0; m_hTextureWhite = 0; m_nNextFontHandle = 1; m_nNextTextureHandle = 1; m_hLastTexture = 0; m_rgflPointsData = new GLfloat[ 3*POINT_BUFFER_TOTAL_SIZE ]; m_rgflPointsColorData = new GLubyte[ 4*POINT_BUFFER_TOTAL_SIZE ]; m_dwPointsToFlush = 0; m_rgflLinesData = new GLfloat[ 6*LINE_BUFFER_TOTAL_SIZE ]; m_rgflLinesColorData = new GLubyte[ 8*LINE_BUFFER_TOTAL_SIZE ]; m_dwLinesToFlush = 0; m_rgflQuadsData = new GLfloat [ 12*QUAD_BUFFER_TOTAL_SIZE ]; m_rgflQuadsColorData = new GLubyte[ 16*QUAD_BUFFER_TOTAL_SIZE ]; m_rgflQuadsTextureData = new GLfloat[ 8*QUAD_BUFFER_TOTAL_SIZE ]; m_dwQuadsToFlush = 0; m_pVRGLHelper = NULL; m_pHmd = NULL; TTF_Init(); if( bUseVR ) { vr::HmdError error; m_pHmd = vr::VR_Init( &error ); if( !m_pHmd ) { fprintf( stderr, "VR_Init returned error %d\n", error ); OutputDebugString( "!! Initialize Steamworks VR failed\n" ); return; } m_pVRGLHelper = new CSteamVRGLHelper(); } if( !BInitializeGraphics() ) { OutputDebugString( "!! Initializing graphics failed\n" ); return; } if ( !BInitializeAudio() ) { OutputDebugString( "!! Initializing audio failed\n" ); return; } m_bEngineReadyForUse = true; }
BOOL TestStringToDWORD() { CString str ; DWORD dwResult = 0 ; DWORD dwValue = 0x1234567 ; str.Format(_T("%x"), dwValue) ; dwResult = StringToDWORD(str) ; if (dwValue != dwResult) { AfxMessageBox(_T("dwValue = 0x1234567 Error")) ; return FALSE ; } dwValue = 0x1 ; str.Format(_T("%x"), dwValue) ; dwResult = StringToDWORD(str) ; if (dwValue != dwResult) { AfxMessageBox(_T("dwValue = 0x1 Error")) ; return FALSE ; } dwValue = 0x2 ; str.Format(_T("%x"), dwValue) ; dwResult = StringToDWORD(str) ; if (dwValue != dwResult) { AfxMessageBox(_T("dwValue = 0x0 Error")) ; return FALSE ; } dwValue = 0xff ; str.Format(_T("%x"), dwValue) ; dwResult = StringToDWORD(str) ; if (dwValue != dwResult) { AfxMessageBox(_T("dwValue = 0xff Error")) ; return FALSE ; } dwValue = 0xfe ; str.Format(_T("%x"), dwValue) ; dwResult = StringToDWORD(str) ; if (dwValue != dwResult) { AfxMessageBox(_T("dwValue = 0xfe Error")) ; return FALSE ; } dwValue = 0xcc ; str.Format(_T("%x"), dwValue) ; dwResult = StringToDWORD(str) ; if (dwValue != dwResult) { AfxMessageBox(_T("dwValue = 0xcc Error")) ; return FALSE ; } OutputDebugString(_T("TestStringToDWORD pass !\r\n")) ; return TRUE ; }
void HttpWGReader::ReadPersonalPlayerData(LPSTR str, TPUser &player) { Json::Value root; Json::StyledWriter styledWriter; Json::Reader reader; LPCWSTR lpcwDesignString; std::wstring ws; std::string status; CHAR lpId[10]; // ID игрока _itoa_s(HttpWGReader::GetPlayerID(), lpId, 10, 10); CHAR tmp[124]; // Парсинг строки BOOL parsingSuccessful = reader.parse(str, root); if (parsingSuccessful) { string_to_wstring(styledWriter.write(root), ws); lpcwDesignString = ws.c_str(); OutputDebugString(lpcwDesignString); } else { OutputDebugStringA("Parsing ReadSearchPlayers error!!!"); return; } // Проверяем правильное сообщение или считывание status = root.get("status", "error").asString(); if (strcmp(status.c_str(), "ok")) { OutputDebugStringA("\n\nParsing Status ReadPersonalPlayerData error!!!\n\n"); return; } // Начинаем считывание и заполнение класса Player player.SetPersonalRating(atoi(root["data"][lpId]["global_rating"].asString().c_str())); player.SetPlayerNickname(root["data"][lpId]["nickname"].asString().c_str()); player.SetNumberOfFights(atoi(root["data"][lpId]["statistics"]["all"]["battles"].asString().c_str())); int wins = atoi(root["data"][lpId]["statistics"]["all"]["wins"].asString().c_str()); if (player.GetNumberOfFights() > 0) player.SetPercentOfVictories((float)wins / player.GetNumberOfFights() * 100); else player.SetPercentOfVictories(0); int damage = atoi(root["data"][lpId]["statistics"]["all"]["damage_dealt"].asString().c_str()); if(player.GetNumberOfFights() > 0) player.SetAverageDamage(damage / player.GetNumberOfFights()); else player.SetAverageDamage(0); player.SetAverageExperience(atoi(root["data"][lpId]["statistics"]["all"]["battle_avg_xp"].asString().c_str())); player.SetPercentOfHits(atoi(root["data"][lpId]["statistics"]["all"]["hits_percents"].asString().c_str())); player.SetMaxExp(atoi(root["data"][lpId]["statistics"]["max_xp"].asString().c_str())); player.SetMaxDamage(atoi(root["data"][lpId]["statistics"]["max_damage"].asString().c_str())); int live = atoi(root["data"][lpId]["statistics"]["all"]["survived_battles"].asString().c_str()); if (player.GetNumberOfFights() > 0) { if (((float)live / (float)player.GetNumberOfFights() * 1000) >= ((int)((float)live / (float)player.GetNumberOfFights() * 100)) * 10 + 5) player.SetLiveBattle((int)ceil((float)live / (float)player.GetNumberOfFights() * 100)); else player.SetLiveBattle((int)floor((float)live / (float)player.GetNumberOfFights() * 100)); } else player.SetLiveBattle(0); }
bool CGUIWindowFullScreen::OnAction(const CAction &action) { if (g_application.m_pPlayer != NULL && g_application.m_pPlayer->OnAction(action)) return true; switch (action.wID) { case ACTION_SHOW_GUI: { // switch back to the menu OutputDebugString("Switching to GUI\n"); m_gWindowManager.PreviousWindow(); OutputDebugString("Now in GUI\n"); return true; } break; case ACTION_STEP_BACK: Seek(false, false); return true; break; case ACTION_STEP_FORWARD: Seek(true, false); return true; break; case ACTION_BIG_STEP_BACK: Seek(false, true); return true; break; case ACTION_BIG_STEP_FORWARD: Seek(true, true); return true; break; case ACTION_NEXT_SCENE: if (g_application.m_pPlayer->SeekScene(true)) g_infoManager.SetDisplayAfterSeek(); return true; break; case ACTION_PREV_SCENE: if (g_application.m_pPlayer->SeekScene(false)) g_infoManager.SetDisplayAfterSeek(); return true; break; case ACTION_SHOW_OSD_TIME: m_bShowCurrentTime = !m_bShowCurrentTime; if(!m_bShowCurrentTime) g_infoManager.SetDisplayAfterSeek(0); //Force display off g_infoManager.SetShowTime(m_bShowCurrentTime); return true; break; case ACTION_SHOW_OSD: // Show the OSD { CGUIWindowOSD *pOSD = (CGUIWindowOSD *)m_gWindowManager.GetWindow(WINDOW_OSD); if (pOSD) pOSD->DoModal(); return true; } break; case ACTION_SHOW_SUBTITLES: { g_application.m_pPlayer->SetSubtitleVisible(!g_application.m_pPlayer->GetSubtitleVisible()); } return true; break; case ACTION_SHOW_INFO: { CGUIDialogFullScreenInfo* pDialog = (CGUIDialogFullScreenInfo*)m_gWindowManager.GetWindow(WINDOW_DIALOG_FULLSCREEN_INFO); if (pDialog) { pDialog->DoModal(); return true; } break; } case ACTION_NEXT_SUBTITLE: { if (g_application.m_pPlayer->GetSubtitleCount() == 1) return true; g_stSettings.m_currentVideoSettings.m_SubtitleStream++; if (g_stSettings.m_currentVideoSettings.m_SubtitleStream >= g_application.m_pPlayer->GetSubtitleCount()) g_stSettings.m_currentVideoSettings.m_SubtitleStream = 0; g_application.m_pPlayer->SetSubtitle(g_stSettings.m_currentVideoSettings.m_SubtitleStream); return true; } return true; break; case ACTION_SUBTITLE_DELAY_MIN: g_stSettings.m_currentVideoSettings.m_SubtitleDelay -= 0.1f; if (g_stSettings.m_currentVideoSettings.m_SubtitleDelay < -g_advancedSettings.m_videoSubsDelayRange) g_stSettings.m_currentVideoSettings.m_SubtitleDelay = -g_advancedSettings.m_videoSubsDelayRange; if (g_application.m_pPlayer) g_application.m_pPlayer->SetSubTitleDelay(g_stSettings.m_currentVideoSettings.m_SubtitleDelay); return true; break; case ACTION_SUBTITLE_DELAY_PLUS: g_stSettings.m_currentVideoSettings.m_SubtitleDelay += 0.1f; if (g_stSettings.m_currentVideoSettings.m_SubtitleDelay > g_advancedSettings.m_videoSubsDelayRange) g_stSettings.m_currentVideoSettings.m_SubtitleDelay = g_advancedSettings.m_videoSubsDelayRange; if (g_application.m_pPlayer) g_application.m_pPlayer->SetSubTitleDelay(g_stSettings.m_currentVideoSettings.m_SubtitleDelay); return true; break; case ACTION_AUDIO_DELAY_MIN: g_stSettings.m_currentVideoSettings.m_AudioDelay -= 0.1f; if (g_stSettings.m_currentVideoSettings.m_AudioDelay < -g_advancedSettings.m_videoAudioDelayRange) g_stSettings.m_currentVideoSettings.m_AudioDelay = -g_advancedSettings.m_videoAudioDelayRange; if (g_application.m_pPlayer) g_application.m_pPlayer->SetAVDelay(g_stSettings.m_currentVideoSettings.m_AudioDelay); return true; break; case ACTION_AUDIO_DELAY_PLUS: g_stSettings.m_currentVideoSettings.m_AudioDelay += 0.1f; if (g_stSettings.m_currentVideoSettings.m_AudioDelay > g_advancedSettings.m_videoAudioDelayRange) g_stSettings.m_currentVideoSettings.m_AudioDelay = g_advancedSettings.m_videoAudioDelayRange; if (g_application.m_pPlayer) g_application.m_pPlayer->SetAVDelay(g_stSettings.m_currentVideoSettings.m_AudioDelay); return true; break; case ACTION_AUDIO_NEXT_LANGUAGE: if (g_application.m_pPlayer->GetAudioStreamCount() == 1) return true; g_stSettings.m_currentVideoSettings.m_AudioStream++; if (g_stSettings.m_currentVideoSettings.m_AudioStream >= g_application.m_pPlayer->GetAudioStreamCount()) g_stSettings.m_currentVideoSettings.m_AudioStream = 0; g_application.m_pPlayer->SetAudioStream(g_stSettings.m_currentVideoSettings.m_AudioStream); // Set the audio stream to the one selected return true; break; case REMOTE_0: case REMOTE_1: case REMOTE_2: case REMOTE_3: case REMOTE_4: case REMOTE_5: case REMOTE_6: case REMOTE_7: case REMOTE_8: case REMOTE_9: ChangetheTimeCode(action.wID); return true; break; case ACTION_ASPECT_RATIO: { // toggle the aspect ratio mode (only if the info is onscreen) if (m_bShowViewModeInfo) { #ifdef HAS_VIDEO_PLAYBACK g_renderManager.SetViewMode(++g_stSettings.m_currentVideoSettings.m_ViewMode); #endif } m_bShowViewModeInfo = true; m_dwShowViewModeTimeout = timeGetTime(); } return true; break; case ACTION_SMALL_STEP_BACK: { int orgpos = (int)g_application.GetTime(); int jumpsize = g_advancedSettings.m_videoSmallStepBackSeconds; // secs int setpos = (orgpos > jumpsize) ? orgpos - jumpsize : 0; g_application.SeekTime((double)setpos); //Make sure gui items are visible g_infoManager.SetDisplayAfterSeek(); } return true; break; } return CGUIWindow::OnAction(action); }
SpewRetval_t CmdLib_SpewOutputFunc( SpewType_t type, char const *pMsg ) { // Hopefully two threads won't call this simultaneously right at the start! if ( !g_bSpewCSInitted ) { InitializeCriticalSection( &g_SpewCS ); g_bSpewCSInitted = true; } WORD old; SpewRetval_t retVal; EnterCriticalSection( &g_SpewCS ); { if (( type == SPEW_MESSAGE ) || (type == SPEW_LOG )) { Color c = GetSpewOutputColor(); if ( c.r() != 255 || c.g() != 255 || c.b() != 255 ) { // custom color old = SetConsoleTextColor( c.r(), c.g(), c.b(), c.a() ); } else { old = SetConsoleTextColor( 1, 1, 1, 0 ); } retVal = SPEW_CONTINUE; } else if( type == SPEW_WARNING ) { old = SetConsoleTextColor( 1, 1, 0, 1 ); retVal = SPEW_CONTINUE; } else if( type == SPEW_ASSERT ) { old = SetConsoleTextColor( 1, 0, 0, 1 ); retVal = SPEW_DEBUGGER; #ifdef MPI // VMPI workers don't want to bring up dialogs and suchlike. // They need to have a special function installed to handle // the exceptions and write the minidumps. // Install the function after VMPI_Init with a call: // SetupToolsMinidumpHandler( VMPI_ExceptionFilter ); if ( g_bUseMPI && !g_bMPIMaster && !Plat_IsInDebugSession() ) { // Generating an exception and letting the // installed handler handle it ::RaiseException ( 0, // dwExceptionCode EXCEPTION_NONCONTINUABLE, // dwExceptionFlags 0, // nNumberOfArguments, NULL // const ULONG_PTR* lpArguments ); // Never get here (non-continuable exception) VMPI_HandleCrash( pMsg, NULL, true ); exit( 0 ); } #endif } else if( type == SPEW_ERROR ) { old = SetConsoleTextColor( 1, 0, 0, 1 ); retVal = SPEW_ABORT; // doesn't matter.. we exit below so we can return an errorlevel (which dbg.dll doesn't do). } else { old = SetConsoleTextColor( 1, 1, 1, 1 ); retVal = SPEW_CONTINUE; } if ( !g_bSuppressPrintfOutput || type == SPEW_ERROR ) printf( "%s", pMsg ); OutputDebugString( pMsg ); if ( type == SPEW_ERROR ) { printf( "\n" ); OutputDebugString( "\n" ); } if( g_pLogFile ) { CmdLib_FPrintf( g_pLogFile, "%s", pMsg ); g_pFileSystem->Flush( g_pLogFile ); } // Dispatch to other spew hooks. FOR_EACH_LL( g_ExtraSpewHooks, i ) g_ExtraSpewHooks[i]( pMsg ); RestoreConsoleTextColor( old ); } LeaveCriticalSection( &g_SpewCS ); if ( type == SPEW_ERROR ) { CmdLib_Exit( 1 ); } return retVal; }
int osip_trace (char *fi, int li, osip_trace_level_t level, FILE * f, char *chfr, ...) { va_list ap; #ifdef ENABLE_TRACE #if !defined(WIN32) && !defined(SYSTEM_LOGGER_ENABLED) if (logfile == NULL && use_syslog == 0) { /* user did not initialize logger.. */ return 1; } #endif if (f == NULL) f = logfile; if (tracing_table[level] == LOG_FALSE) return 0; VA_START (ap, chfr); #ifdef __VXWORKS_OS__ /* vxworks can't have a local file */ f = stdout; #endif if (f && use_syslog == 0) { if (level == OSIP_FATAL) fprintf (f, "| FATAL | <%s: %i> ", fi, li); else if (level == OSIP_BUG) fprintf (f, "| BUG | <%s: %i> ", fi, li); else if (level == OSIP_ERROR) fprintf (f, "| ERROR | <%s: %i> ", fi, li); else if (level == OSIP_WARNING) fprintf (f, "|WARNING| <%s: %i> ", fi, li); else if (level == OSIP_INFO1) fprintf (f, "| INFO1 | <%s: %i> ", fi, li); else if (level == OSIP_INFO2) fprintf (f, "| INFO2 | <%s: %i> ", fi, li); else if (level == OSIP_INFO3) fprintf (f, "| INFO3 | <%s: %i> ", fi, li); else if (level == OSIP_INFO4) fprintf (f, "| INFO4 | <%s: %i> ", fi, li); vfprintf (f, chfr, ap); fflush (f); } #if defined (HAVE_SYSLOG_H) else if (use_syslog == 1) { char buffer[512]; int in = 0; memset (buffer, 0, sizeof (buffer)); if (level == OSIP_FATAL) in = snprintf (buffer, 511, "| FATAL | <%s: %i> ", fi, li); else if (level == OSIP_BUG) in = snprintf (buffer, 511, "| BUG | <%s: %i> ", fi, li); else if (level == OSIP_ERROR) in = snprintf (buffer, 511, "| ERROR | <%s: %i> ", fi, li); else if (level == OSIP_WARNING) in = snprintf (buffer, 511, "|WARNING| <%s: %i> ", fi, li); else if (level == OSIP_INFO1) in = snprintf (buffer, 511, "| INFO1 | <%s: %i> ", fi, li); else if (level == OSIP_INFO2) in = snprintf (buffer, 511, "| INFO2 | <%s: %i> ", fi, li); else if (level == OSIP_INFO3) in = snprintf (buffer, 511, "| INFO3 | <%s: %i> ", fi, li); else if (level == OSIP_INFO4) in = snprintf (buffer, 511, "| INFO4 | <%s: %i> ", fi, li); vsnprintf (buffer + in, 511 - in, chfr, ap); if (level == OSIP_FATAL) syslog (LOG_ERR, "%s", buffer); else if (level == OSIP_BUG) syslog (LOG_ERR, "%s", buffer); else if (level == OSIP_ERROR) syslog (LOG_ERR, "%s", buffer); else if (level == OSIP_WARNING) syslog (LOG_WARNING, "%s", buffer); else if (level == OSIP_INFO1) syslog (LOG_INFO, "%s", buffer); else if (level == OSIP_INFO2) syslog (LOG_INFO, "%s", buffer); else if (level == OSIP_INFO3) syslog (LOG_DEBUG, "%s", buffer); else if (level == OSIP_INFO4) syslog (LOG_DEBUG, "%s", buffer); } #endif #ifdef SYSTEM_LOGGER_ENABLED else { char buffer[512]; int in = 0; memset (buffer, 0, sizeof (buffer)); if (level == OSIP_FATAL) in = _snprintf (buffer, 511, "| FATAL | <%s: %i> ", fi, li); else if (level == OSIP_BUG) in = _snprintf (buffer, 511, "| BUG | <%s: %i> ", fi, li); else if (level == OSIP_ERROR) in = _snprintf (buffer, 511, "| ERROR | <%s: %i> ", fi, li); else if (level == OSIP_WARNING) in = _snprintf (buffer, 511, "|WARNING| <%s: %i> ", fi, li); else if (level == OSIP_INFO1) in = _snprintf (buffer, 511, "| INFO1 | <%s: %i> ", fi, li); else if (level == OSIP_INFO2) in = _snprintf (buffer, 511, "| INFO2 | <%s: %i> ", fi, li); else if (level == OSIP_INFO3) in = _snprintf (buffer, 511, "| INFO3 | <%s: %i> ", fi, li); else if (level == OSIP_INFO4) in = _snprintf (buffer, 511, "| INFO4 | <%s: %i> ", fi, li); _vsnprintf (buffer + in, 511 - in, chfr, ap); OutputDebugString (buffer); } #endif va_end (ap); #endif return 0; }