////////////////////////////////////////////////////////////////////////////// // Help - Displays list of commands ////////////////////////////////////////////////////////////////////////////// void Help() { _cwprintf(L"COMMANDS:\r\n"); _cwprintf(L" dir Get the list of files on server\r\n"); _cwprintf(L" get Retrieve a file from the server\r\n"); _cwprintf(L" quit Exits program\r\n"); }
////////////////////////////////////////////////////////////////////////////// // Usage - Displays command-line options ////////////////////////////////////////////////////////////////////////////// void Usage(LPCWSTR pszAdditionalInformation) { _cwprintf(L"FileServiceClient.exe <files-directory> [<device-address>]\r\n"); _cwprintf(L"Ex: FileServiceClient.exe c:\\temp urn:uuid:2BA7FF9A-CC7D-4781-B744-9347C5AC5A28\r\n"); if( NULL != pszAdditionalInformation ) { _cwprintf( L"%s\r\n", pszAdditionalInformation ); } }
////////////////////////////////////////////////////////////////////////////// // print_result - Display an HRESULT ////////////////////////////////////////////////////////////////////////////// void print_result(HRESULT hr) { if (hr == S_OK) { _cwprintf(L"[S_OK]\r\n"); } else { _cwprintf(L"[ERROR: %x]\r\n", hr); } }
// 音频处理 void ThisApp::speech_process() { // 置信阈值 const float ConfidenceThreshold = 0.3f; SPEVENT curEvent = { SPEI_UNDEFINED, SPET_LPARAM_IS_UNDEFINED, 0, 0, 0, 0 }; ULONG fetched = 0; HRESULT hr = S_OK; // 获取事件 m_pSpeechContext->GetEvents(1, &curEvent, &fetched); while (fetched > 0) { // 确定是识别事件 switch (curEvent.eEventId) { case SPEI_RECOGNITION: // 保证位对象 if (SPET_LPARAM_IS_OBJECT == curEvent.elParamType) { ISpRecoResult* result = reinterpret_cast<ISpRecoResult*>(curEvent.lParam); SPPHRASE* pPhrase = nullptr; // 获取识别短语 hr = result->GetPhrase(&pPhrase); if (SUCCEEDED(hr)) { #ifdef _DEBUG // DEBUG时显示识别字符串 WCHAR* pwszFirstWord; result->GetText(SP_GETWHOLEPHRASE, SP_GETWHOLEPHRASE, TRUE, &pwszFirstWord, nullptr); _cwprintf(pwszFirstWord); ::CoTaskMemFree(pwszFirstWord); #endif pPhrase->pProperties; const SPPHRASEELEMENT* pointer = pPhrase->pElements + 1; if ((pPhrase->pProperties != nullptr) && (pPhrase->pProperties->pFirstChild != nullptr)) { const SPPHRASEPROPERTY* pSemanticTag = pPhrase->pProperties->pFirstChild; #ifdef _DEBUG _cwprintf(L" 置信度:%d%%\n", (int)(pSemanticTag->SREngineConfidence*100.f)); #endif if (pSemanticTag->SREngineConfidence > ConfidenceThreshold) { speech_behavior(pSemanticTag); } } ::CoTaskMemFree(pPhrase); } } break; } m_pSpeechContext->GetEvents(1, &curEvent, &fetched); } return; }
////////////////////////////////////////////////////////////////////////////// // print_result - Display HRESULTs ////////////////////////////////////////////////////////////////////////////// void print_result(HRESULT hr) { if( S_OK == hr ) { _cwprintf(L"[S_OK]\r\n"); } else if( S_FALSE == hr ) { _cwprintf(L"[S_FALSE]\r\n"); } else { _cwprintf(L"[ERROR: %x]\r\n", hr); } }
// 创建字体格式 IDWriteTextFormat* TextFormatCache::CreateTextFormat(const TextFormat& font){ #ifdef _DEBUG TextFormatCache::Map::iterator itr = s_mapTextCache.find(font); if (itr != s_mapTextCache.end()){ _cwprintf(L"目标字体已存在.\n"); return itr->second; } if (!s_ppDWriteFactory){ _cwprintf(L"s_ppDWriteFactory未初始化.\n"); return NULL; } if (!(*s_ppDWriteFactory)){ _cwprintf(L"DWriteFactory未初始化.\n"); return NULL; } #endif IDWriteTextFormat* pTF; (*s_ppDWriteFactory)->CreateTextFormat( font.font_name.c_str(), s_pCollection, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, font.font_size * (96.0f / 72.f), L"", //locale &pTF ); if (pTF){ pTF->SetTextAlignment(font.font_alignment); } #ifdef _DEBUG else _cwprintf(L"IDWriteTextFormat 创建失败.\n"); #endif s_mapTextCache.insert(Map::value_type(font, pTF)); return pTF; }
////////////////////////////////////////////////////////////////////////////// // AsyncOperationComplete - Called when the GetFile operation is complete ////////////////////////////////////////////////////////////////////////////// HRESULT STDMETHODCALLTYPE CGetFileAsyncCallback::AsyncOperationComplete( IWSDAsyncResult* pAsyncResult, IUnknown* pAsyncState) { UNREFERENCED_PARAMETER(pAsyncState); GET_FILE_RESPONSE* pResponse = NULL; HRESULT hr = S_OK; // // When the GetFile operation completes, we enter this callback. It's // then our responsibility to call EndGetFile to actually retrieve // the results. // _cwprintf(L"Asynchronous GetFile operation completed.\r\n"); hr = m_pFileServiceSecureProxy->EndGetFile( pAsyncResult, &pResponse ); // Call into our helper method to save the attachment to disk if( S_OK == hr && NULL != pResponse ) { hr = ReceiveBinary( pResponse->Attachment, m_szFile ); } else { _cwprintf(L" GetFile operation failed or returned NULL response: "); print_result( hr ); } // cleanup if( NULL != pResponse ) { WSDFreeLinkedMemory( pResponse ); pResponse = NULL; } return hr; }
////////////////////////////////////////////////////////////////////////////// // GetFileList - Invoke the GetFileList (i.e., "dir") service method ////////////////////////////////////////////////////////////////////////////// HRESULT GetFileList( IFileServiceSecureProxy* pFileServiceSecureProxy) { GET_FILE_LIST_RESPONSE* pResponse = NULL; HRESULT hr = S_OK; if( NULL == pFileServiceSecureProxy ) { return E_INVALIDARG; } // Invoke GetFileList method on service _cwprintf(L"Invoking GetFileList method on service... "); hr = pFileServiceSecureProxy->GetFileList( &pResponse ); print_result( hr ); // Print results if( S_OK == hr && NULL != pResponse ) { PWCHAR_LIST *pList = pResponse->FileList; while( pList ) { _cwprintf(L"%s\r\n", (NULL == pList->Element ? L"(null)" : pList->Element)); pList = pList->Next; } } // cleanup if( NULL != pResponse ) { WSDFreeLinkedMemory( pResponse ); pResponse = NULL; } return hr; }
////////////////////////////////////////////////////////////////////////////// // FileChangeEvent - Invoked when the service sends this event ////////////////////////////////////////////////////////////////////////////// HRESULT STDMETHODCALLTYPE CFileServiceSecureEventNotify::FileChangeEvent( FILE_CHANGE_EVENT* pFileChangeEvent) { if( NULL == pFileChangeEvent ) { return E_INVALIDARG; } // Simply print the event and return _cwprintf(L"\r\nReceived event: [%s: %s]\r\n", pFileChangeEvent->EventType, pFileChangeEvent->FileName); return S_OK; }
// 创建TF IDWriteTextFormat* TextFormatCache::CreateTextFormat(const TextFormatParameter* pParameter){ IDWriteTextFormat* pTextFormat(nullptr); #ifdef _DEBUG if (!s_ppDWriteFactory){ _cwprintf(L"s_ppDWriteFactory未初始化.\n"); return NULL; } if (!(*s_ppDWriteFactory)){ _cwprintf(L"DWriteFactory未初始化.\n"); return NULL; } #endif (*s_ppDWriteFactory)->CreateTextFormat( pParameter->font_name, s_pCollection, pParameter->font_weight, pParameter->font_style, pParameter->font_stretch, pParameter->font_size * (96.0f / 72.f), L"", //locale &pTextFormat ); if (pTextFormat){ #ifdef _DEBUG HRESULT hr(S_OK); // 设置行对齐 if (SUCCEEDED(hr)) hr = pTextFormat->SetTextAlignment(pParameter->text_alignmen); // 设置列对齐 if (SUCCEEDED(hr)) hr = pTextFormat->SetParagraphAlignment(pParameter->paragraph_alignment); // 设置自动换行 if (SUCCEEDED(hr)) hr = pTextFormat->SetWordWrapping(pParameter->word_wrapping); // 设置制表符宽度 if (SUCCEEDED(hr)) hr = pTextFormat->SetIncrementalTabStop(pParameter->incremental_tabstop); // 段落排列方向 //if (SUCCEEDED(hr)) //hr = pTextFormat->SetFlowDirection(DWRITE_FLOW_DIRECTION_BOTTOM_TO_TOP); // 设置行距 if (SUCCEEDED(hr)) hr = pTextFormat->SetLineSpacing(pParameter->line_spacing_method, pParameter->line_spacing, pParameter->baseline); if (FAILED(hr)){ MessageBoxW(nullptr, L"<TextFormatCache::CreateTextFormat>: OK to created but failed to set\n" L"创建成功但是设置失败", L"Error", MB_OK); SafeRelease(pTextFormat); return nullptr; } #else // 设置行对齐 pTextFormat->SetTextAlignment(pParameter->text_alignmen); // 设置列对齐 pTextFormat->SetParagraphAlignment(pParameter->paragraph_alignment); // 设置自动换行 pTextFormat->SetWordWrapping(pParameter->word_wrapping); // 设置制表符宽度 pTextFormat->SetIncrementalTabStop(pParameter->incremental_tabstop); // 段落排列方向 //pTextFormat->SetFlowDirection(pParameter->flow_direction); // 设置行距 pTextFormat->SetLineSpacing(pParameter->line_spacing_method, pParameter->line_spacing, pParameter->baseline); #endif return pTextFormat; } return nullptr; //s_aryTextFormat[idx]->SetTrimming(); }
////////////////////////////////////////////////////////////////////////////// // CStockQuoteService::GetLastTradePrice // Service method which can be called by remote clients. This method // takes the stock quote listed in the parameters structure and returns // a structure with a stock price. ////////////////////////////////////////////////////////////////////////////// STDMETHODIMP CStockQuoteService::GetLastTradePrice( TRADE_PRICE_REQUEST* parameters, TRADE_PRICE** ppTradePrice) { TRADE_PRICE* pTradePrice = NULL; HRESULT hr = S_OK; _cwprintf(L"Client invoking GetLastTradePrice method\r\n"); // Validate parameters if( NULL == parameters ) { return E_INVALIDARG; } if( NULL == parameters->tickerSymbol ) { return E_INVALIDARG; } if( NULL == ppTradePrice ) { return E_POINTER; } *ppTradePrice = NULL; // Allocate response structure with WSDAllocateLinkedMemory. The // Deallocator for this port type's stub functions is WSDFreeLinkedMemory. _cwprintf(L" Allocating response structure... "); pTradePrice = (TRADE_PRICE*)WSDAllocateLinkedMemory( NULL, sizeof(TRADE_PRICE) ); if( NULL == pTradePrice ) { hr = E_OUTOFMEMORY; } print_result( hr ); // Fill response structure if( S_OK == hr ) { _cwprintf(L" Calling into StockLookup function... "); pTradePrice->price = StockLookup(parameters->tickerSymbol); print_result( hr ); } if( S_OK == hr ) { *ppTradePrice = pTradePrice; pTradePrice = NULL; _cwprintf(L" Response has been prepared.\r\n"); } _cwprintf(L" Service method exit code: "); print_result( hr ); // cleanup if( NULL != pTradePrice ) { WSDFreeLinkedMemory( pTradePrice ); pTradePrice = NULL; } return hr; }
////////////////////////////////////////////////////////////////////////////// // Usage ////////////////////////////////////////////////////////////////////////////// void Usage() { _cwprintf(L"StockQuoteClient.exe <device-address>\r\n"); _cwprintf(L"Ex: StockQuoteClient.exe urn:uuid:41F8BE9C-CF75-48f7-9294-1B2DC8698214\r\n"); }
////////////////////////////////////////////////////////////////////////////// // Usage ////////////////////////////////////////////////////////////////////////////// void Usage() { _cwprintf(L"StockQuoteService.exe [<device address>]\r\n"); _cwprintf(L"Ex: StockQuoteService.exe urn:uuid:41F8BE9C-CF75-48f7-9294-1B2DC8698214\r\n"); }
////////////////////////////////////////////////////////////////////////////// // ReceiveBinary - Creates a local file in the files-directory // from the inbound attachment ////////////////////////////////////////////////////////////////////////////// HRESULT CGetFileAsyncCallback::ReceiveBinary( IWSDAttachment* pAttachment, LPCWSTR pszLocalFileName) { HRESULT hr = S_OK; IWSDInboundAttachment* pStream = NULL; BYTE buffer[8192]; ULONG cbBytesRead = 0; ULONG cbBytesLeft = 0; DWORD cbBytesWritten = 0; ULONG cbBytesTotal = 0; HANDLE hFile = NULL; DWORD dwErr = 0; // Validate parameters if( NULL == pAttachment ) { return E_INVALIDARG; } if( NULL == pszLocalFileName ) { return E_INVALIDARG; } if( 0 == wcscmp( pszLocalFileName, L"" ) ) { return E_INVALIDARG; } // Make sure this attachment is an inbound attachment, and get that // interface hr = pAttachment->QueryInterface( __uuidof(IWSDInboundAttachment), (void**)&pStream); // Create a file to write attachment data into if( S_OK == hr ) { _cwprintf(L" Creating local file %s... ", pszLocalFileName); hFile = ::CreateFileW( pszLocalFileName, FILE_WRITE_DATA, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); if ( INVALID_HANDLE_VALUE == hFile ) { hFile = NULL; dwErr = ::GetLastError(); hr = HRESULT_FROM_WIN32( dwErr ); } print_result( hr ); } // Read from the inbound attachment and write to file until finished while( S_OK == hr ) { _cwprintf(L" Reading attachment data... "); hr = pStream->Read( buffer, sizeof(buffer), &cbBytesRead ); cbBytesLeft = cbBytesRead; // pStream->Read will return S_FALSE on the last read if the buffer // was not completely filled. Hang onto the S_FALSE until the // end of this loop while( (S_OK == hr || S_FALSE == hr) && 0 < cbBytesLeft ) { if( 0 == WriteFile( hFile, buffer + (cbBytesRead - cbBytesLeft), cbBytesLeft, &cbBytesWritten, NULL ) ) { dwErr = ::GetLastError(); hr = HRESULT_FROM_WIN32( dwErr ); } if( S_OK == hr || S_FALSE == hr ) { cbBytesLeft -= cbBytesWritten; } } print_result( hr ); cbBytesTotal += (cbBytesRead - cbBytesLeft); // If that was the last read, reset hr and bail out if( S_FALSE == hr ) { hr = S_OK; break; } } // Print success message if we got the file without any problems if( S_OK == hr ) { _cwprintf( L"%s recieved (%d bytes).\r\n", pszLocalFileName, cbBytesTotal ); } else { _cwprintf( L"Error receiving %s. Only recieved (%d bytes).\r\n", pszLocalFileName, cbBytesTotal ); } // cleanup if( NULL != hFile ) { ::CloseHandle( hFile ); hFile = NULL; } if( NULL != pStream ) { pStream->Release(); pStream = NULL; } return hr; }
// 初始化ThisApp HRESULT ThisApp::Initialize(){ WNDCLASS wc; ZeroMemory(&wc, sizeof(wc)); wc.hbrBackground = (HBRUSH)(COLOR_3DFACE + 1); wc.style = CS_HREDRAW | CS_VREDRAW; wc.cbWndExtra = DLGWINDOWEXTRA; wc.hInstance = HINST_THISCOMPONENT; wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hIcon = LoadIconW(HINST_THISCOMPONENT, MAKEINTRESOURCE(IDI_APP_ICON)); wc.lpfnWndProc = ThisApp::WndProc; wc.lpszClassName = AppInfo::APP_WINDOW_CLASS_NAME; wc.cbWndExtra = sizeof(LONG_PTR); RegisterClass(&wc); // 读取ini文件 RECT window_rect = { 0, 0, AppInfo::SHOW_WIDTH, AppInfo::SHOW_HEIGHT }; wchar_t title[32]; DWORD rc = GetPrivateProfileStringW(L"Game", L"title", L"", title, sizeof title, L".\\Game.ini"); if (rc){ char buffer[8]; if (GetPrivateProfileStringA("Game", "width", "", buffer, sizeof buffer, ".\\Game.ini")) window_rect.right = atoi(buffer); if (GetPrivateProfileStringA("Game", "height", "", buffer, sizeof buffer, ".\\Game.ini")) window_rect.bottom = atoi(buffer); } else wcscpy_s(title, AppInfo::APP_WINDOW_TITLE_NAME); // 调整窗口大小 DWORD window_style = WS_CAPTION | WS_VISIBLE | WS_POPUP | WS_SYSMENU | WS_MINIMIZEBOX; AdjustWindowRect(&window_rect, window_style, FALSE); window_rect.right -= window_rect.left; window_rect.bottom -= window_rect.top; window_rect.left = (GetSystemMetrics(SM_CXFULLSCREEN) - window_rect.right) / 2; window_rect.top = (GetSystemMetrics(SM_CYFULLSCREEN) - window_rect.right) / 2; //window_rect.right += window_rect.left; //window_rect.bottom += window_rect.top; // 创建窗口 m_hwnd = CreateWindowW(wc.lpszClassName, title, window_style, window_rect.left, window_rect.top, window_rect.right, window_rect.bottom, 0, 0, HINST_THISCOMPONENT, this); // 显示窗口 if (m_hwnd){ ::GetClientRect(m_hwnd, &window_rect); #ifdef _DEBUG _cwprintf(L"Window: %4d, %4d\n", window_rect.right, window_rect.bottom); #endif ClientToScreen(m_hwnd, (LPPOINT)(&window_rect)); window_rect.right += window_rect.left; window_rect.bottom += window_rect.top; ShowWindow(m_hwnd, SW_NORMAL); UpdateWindow(m_hwnd); // 设定并初始化渲染 HRESULT hr = m_imageRender.SetHwnd(m_hwnd); if (SUCCEEDED(hr)){ // 成功的话,创建渲染线程 m_pRenderThread = (std::thread*)MPool.Alloc(sizeof std::thread); // 检查指针 hr = m_pRenderThread ? S_OK : E_OUTOFMEMORY; } if (SUCCEEDED(hr)){ // 显式析构 new(m_pRenderThread) std::thread(ImageRender::RenderThread, &m_imageRender); // 成功的话,创建游戏逻辑线程 m_pGameLogicThread = (std::thread*)MPool.Alloc(sizeof std::thread); // 检查指针 hr = m_pGameLogicThread ? S_OK : E_OUTOFMEMORY; // 隐藏鼠标 //::ShowCursor(FALSE); //ClipCursor(&window_rect); } if (SUCCEEDED(hr)){ // 显式析构 new(m_pGameLogicThread)std::thread(Game::LogicThread, m_hwnd); // 初始化输入接口 hr = KMInput.Init(HINST_THISCOMPONENT, m_hwnd); } return hr; } return E_FAIL; }
LRESULT CALLBACK ThisApp::WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam){ // 处理标识 bool handled = false; // return code LRESULT rcode = 0; ThisApp* pThis; if (WM_CREATE == message) { /*pThis = reinterpret_cast<MainWindow*>(lParam); SetWindowLongPtr(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(pThis));*/ LPCREATESTRUCT pcs = (LPCREATESTRUCT)lParam; pThis = (ThisApp *)pcs->lpCreateParams; ::SetWindowLongPtrW( hwnd, GWLP_USERDATA, PtrToUlong(pThis) ); } else { pThis = reinterpret_cast<ThisApp *>(static_cast<LONG_PTR>( ::GetWindowLongPtrW( hwnd, GWLP_USERDATA ))); } // 消息处理 if (pThis){ switch (message){ case WM_DESTROY: rcode = 1; handled = true; PostQuitMessage(0); break; case WM_SETFOCUS: #ifdef _DEBUG _cwprintf(L"WM_SETFOCUS\n"); #endif break; case WM_KILLFOCUS: #ifdef _DEBUG _cwprintf(L"WM_KILLFOCUS\n"); #endif break; case WM_CLOSE: { __try{ rb_raise(rb_eSystemExit, "System Exit"); } __except (EXCEPTION_EXECUTE_HANDLER){} } pThis->m_imageRender.ExitRender(); Game::Exit(); pThis->m_pGameLogicThread->join(); pThis->m_pRenderThread->join(); rcode = 1; handled = true; DestroyWindow(hwnd); break; }//s }//i if (!handled){ rcode = DefWindowProc(hwnd, message, wParam, lParam); } return rcode; };
////////////////////////////////////////////////////////////////////////////// // GetFile - Invoke the GetFile service method ////////////////////////////////////////////////////////////////////////////// HRESULT GetFile( IFileServiceSecureProxy* pFileServiceSecureProxy, LPCWSTR pszFileName, LPCWSTR pszReceiveDirectory) { GET_FILE_REQUEST params; HRESULT hr = S_OK; CGetFileAsyncCallback* pGetFileCallback = NULL; IWSDAsyncResult* pAsyncResult = NULL; if( NULL == pszFileName ) { return E_INVALIDARG; } _cwprintf(L"Invoking GetFile method on service (file=%s)...\r\n", pszFileName); // Prepare parameters for service method params.filePath = pszFileName; // // Set up the async callback function. // pGetFileCallback->AsyncOperationComplete will get called when the stream // has finished downloading, and will save the results into a local file. // pGetFileCallback = new CGetFileAsyncCallback(); if( NULL == pGetFileCallback ) { hr = E_OUTOFMEMORY; } if( S_OK == hr ) { _cwprintf(L" Initializing callback structure... "); hr = pGetFileCallback->Init( pFileServiceSecureProxy, pszFileName, pszReceiveDirectory ); print_result( hr ); } // Invoke GetFile method on service if( S_OK == hr ) { _cwprintf(L" Starting GetFile operation... "); hr = pFileServiceSecureProxy->BeginGetFile( ¶ms, NULL, pGetFileCallback, &pAsyncResult ); print_result( hr ); } // cleanup if( NULL != pGetFileCallback ) { // Release pGetFileCallback now--if it was successful, // BeginGetFile has added its own reference pGetFileCallback->Release(); pGetFileCallback = NULL; } if( NULL != pAsyncResult ) { // pGetFileCallback will hold a reference to our async result // object, so we can release our reference now. pAsyncResult->Release(); pAsyncResult = NULL; } return hr; }