//*********************************************************************// // WinMain // - application entry point int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) { // Don't let more than one instance of the application exist if( IsAlreadyRunning() == true ) return -1; // Create the window HWND hWnd = MakeWindow( hInstance ); if( hWnd == 0 ) { MessageBoxW( HWND_DESKTOP, L"ERROR: Failed to create the Main Window.", WINDOW_TITLE, MB_OK | MB_ICONERROR ); return -2; } // Display the window ShowWindow( hWnd, nCmdShow ); UpdateWindow( hWnd ); ///////////////////////////////////////////////////////////////////// // Initialize game // Access the singleton Game* pGame = Game::GetInstance(); // Initialize if( pGame->Initialize( WINDOW_WIDTH, WINDOW_HEIGHT, WINDOW_TITLE ) == false ) return -3; // Run the message loop MSG msg = { }; while( true ) { if( PeekMessageW( &msg, NULL, 0, 0, PM_REMOVE ) == TRUE ) { // Quit the application? if( msg.message == WM_QUIT ) break; // Send the message to the window proc DispatchMessageW( &msg ); } else { ///////////////////////////////////////////////////////////// // Run game int result = pGame->Update(); if( result != 0 ) PostQuitMessage( result ); } } ///////////////////////////////////////////////////////////////////// // Terminate game pGame->Terminate(); pGame = nullptr; Game::DeleteInstance(); // Unregister the window class UnregisterClassW( WINDOW_CLASS_NAME, hInstance ); // Return message's Quit code to the OS return (int)(msg.wParam); }
NS_IMETHODIMP nsFilePicker::ShowW(PRInt16 *aReturnVal) { NS_ENSURE_ARG_POINTER(aReturnVal); // suppress blur events if (mParentWidget) { nsIWidget *tmp = mParentWidget; nsWindow *parent = static_cast<nsWindow *>(tmp); parent->SuppressBlurEvents(PR_TRUE); } PRBool result = PR_FALSE; PRUnichar fileBuffer[FILE_BUFFER_SIZE+1]; wcsncpy(fileBuffer, mDefault.get(), FILE_BUFFER_SIZE); fileBuffer[FILE_BUFFER_SIZE] = '\0'; // null terminate in case copy truncated NS_NAMED_LITERAL_STRING(htmExt, "html"); nsAutoString initialDir; if (mDisplayDirectory) mDisplayDirectory->GetPath(initialDir); // If no display directory, re-use the last one. if(initialDir.IsEmpty()) { // Allocate copy of last used dir. initialDir = mLastUsedUnicodeDirectory; } mUnicodeFile.Truncate(); if (mMode == modeGetFolder) { PRUnichar dirBuffer[MAX_PATH+1]; wcsncpy(dirBuffer, initialDir.get(), MAX_PATH); BROWSEINFOW browserInfo; browserInfo.hwndOwner = (HWND) (mParentWidget.get() ? mParentWidget->GetNativeData(NS_NATIVE_TMP_WINDOW) : 0); browserInfo.pidlRoot = nsnull; browserInfo.pszDisplayName = (LPWSTR)dirBuffer; browserInfo.lpszTitle = mTitle.get(); browserInfo.ulFlags = BIF_USENEWUI | BIF_RETURNONLYFSDIRS; if (initialDir.Length()) { // the dialog is modal so that |initialDir.get()| will be valid in // BrowserCallbackProc. Thus, we don't need to clone it. browserInfo.lParam = (LPARAM) initialDir.get(); browserInfo.lpfn = &BrowseCallbackProc; } else { browserInfo.lParam = nsnull; browserInfo.lpfn = nsnull; } browserInfo.iImage = nsnull; LPITEMIDLIST list = ::SHBrowseForFolderW(&browserInfo); if (list != NULL) { result = ::SHGetPathFromIDListW(list, (LPWSTR)fileBuffer); if (result) { mUnicodeFile.Assign(fileBuffer); } // free PIDL CoTaskMemFree(list); } } else { OPENFILENAMEW ofn; memset(&ofn, 0, sizeof(ofn)); ofn.lStructSize = sizeof(ofn); nsString filterBuffer = mFilterList; if (!initialDir.IsEmpty()) { ofn.lpstrInitialDir = initialDir.get(); } ofn.lpstrTitle = (LPCWSTR)mTitle.get(); ofn.lpstrFilter = (LPCWSTR)filterBuffer.get(); ofn.nFilterIndex = mSelectedType; ofn.hwndOwner = (HWND) (mParentWidget.get() ? mParentWidget->GetNativeData(NS_NATIVE_TMP_WINDOW) : 0); ofn.lpstrFile = fileBuffer; ofn.nMaxFile = FILE_BUFFER_SIZE; ofn.Flags = OFN_NOCHANGEDIR | OFN_SHAREAWARE | OFN_LONGNAMES | OFN_OVERWRITEPROMPT | OFN_HIDEREADONLY | OFN_PATHMUSTEXIST; // Handle add to recent docs settings nsCOMPtr<nsIPrivateBrowsingService> pbs = do_GetService(NS_PRIVATE_BROWSING_SERVICE_CONTRACTID); PRBool privacyModeEnabled = PR_FALSE; if (pbs) { pbs->GetPrivateBrowsingEnabled(&privacyModeEnabled); } if (privacyModeEnabled || !mAddToRecentDocs) { ofn.Flags |= OFN_DONTADDTORECENT; } if (!mDefaultExtension.IsEmpty()) { ofn.lpstrDefExt = mDefaultExtension.get(); } else { // Get file extension from suggested filename // to detect if we are saving an html file //XXX: nsIFile SHOULD HAVE A GetExtension() METHOD! PRInt32 extIndex = mDefault.RFind("."); if ( extIndex >= 0) { nsAutoString ext; mDefault.Right(ext, mDefault.Length() - extIndex); // Should we test for ".cgi", ".asp", ".jsp" and other // "generated" html pages? if ( ext.LowerCaseEqualsLiteral(".htm") || ext.LowerCaseEqualsLiteral(".html") || ext.LowerCaseEqualsLiteral(".shtml") ) { // This is supposed to append ".htm" if user doesn't supply an extension //XXX Actually, behavior is sort of weird: // often appends ".html" even if you have an extension // It obeys your extension if you put quotes around name ofn.lpstrDefExt = htmExt.get(); } } } MOZ_SEH_TRY { if (mMode == modeOpen) { // FILE MUST EXIST! ofn.Flags |= OFN_FILEMUSTEXIST; result = ::GetOpenFileNameW(&ofn); } else if (mMode == modeOpenMultiple) { ofn.Flags |= OFN_FILEMUSTEXIST | OFN_ALLOWMULTISELECT | OFN_EXPLORER; result = ::GetOpenFileNameW(&ofn); } else if (mMode == modeSave) { ofn.Flags |= OFN_NOREADONLYRETURN; // Don't follow shortcuts when saving a shortcut, this can be used // to trick users (bug 271732) NS_ConvertUTF16toUTF8 ext(mDefault); ext.Trim(" .", PR_FALSE, PR_TRUE); // watch out for trailing space and dots ToLowerCase(ext); if (StringEndsWith(ext, NS_LITERAL_CSTRING(".lnk")) || StringEndsWith(ext, NS_LITERAL_CSTRING(".pif")) || StringEndsWith(ext, NS_LITERAL_CSTRING(".url"))) ofn.Flags |= OFN_NODEREFERENCELINKS; result = ::GetSaveFileNameW(&ofn); if (!result) { // Error, find out what kind. if (::GetLastError() == ERROR_INVALID_PARAMETER || ::CommDlgExtendedError() == FNERR_INVALIDFILENAME ) { // probably the default file name is too long or contains illegal characters! // Try again, without a starting file name. ofn.lpstrFile[0] = 0; result = ::GetSaveFileNameW(&ofn); } } } else { NS_ERROR("unsupported mode"); } } MOZ_SEH_EXCEPT(PR_TRUE) { MessageBoxW(ofn.hwndOwner, 0, L"The filepicker was unexpectedly closed by Windows.", MB_ICONERROR); result = PR_FALSE; } if (result) { // Remember what filter type the user selected mSelectedType = (PRInt16)ofn.nFilterIndex; // Set user-selected location of file or directory if (mMode == modeOpenMultiple) { // from msdn.microsoft.com, "Open and Save As Dialog Boxes" section: // If you specify OFN_EXPLORER, // The directory and file name strings are NULL separated, // with an extra NULL character after the last file name. // This format enables the Explorer-style dialog boxes // to return long file names that include spaces. PRUnichar *current = fileBuffer; nsAutoString dirName(current); // sometimes dirName contains a trailing slash // and sometimes it doesn't. if (current[dirName.Length() - 1] != '\\') dirName.Append((PRUnichar)'\\'); nsresult rv; while (current && *current && *(current + nsCRT::strlen(current) + 1)) { current = current + nsCRT::strlen(current) + 1; nsCOMPtr<nsILocalFile> file = do_CreateInstance("@mozilla.org/file/local;1", &rv); NS_ENSURE_SUCCESS(rv,rv); rv = file->InitWithPath(dirName + nsDependentString(current)); NS_ENSURE_SUCCESS(rv,rv); rv = mFiles.AppendObject(file); NS_ENSURE_SUCCESS(rv,rv); } // handle the case where the user selected just one // file. according to msdn.microsoft.com: // If you specify OFN_ALLOWMULTISELECT and the user selects // only one file, the lpstrFile string does not have // a separator between the path and file name. if (current && *current && (current == fileBuffer)) { nsCOMPtr<nsILocalFile> file = do_CreateInstance("@mozilla.org/file/local;1", &rv); NS_ENSURE_SUCCESS(rv,rv); rv = file->InitWithPath(nsDependentString(current)); NS_ENSURE_SUCCESS(rv,rv); rv = mFiles.AppendObject(file); NS_ENSURE_SUCCESS(rv,rv); } } else { // I think it also needs a conversion here (to unicode since appending to nsString) // but doing that generates garbage file name, weird. mUnicodeFile.Assign(fileBuffer); } } if (ofn.hwndOwner) { ::DestroyWindow(ofn.hwndOwner); } } if (result) { PRInt16 returnOKorReplace = returnOK; // Remember last used directory. nsCOMPtr<nsILocalFile> file(do_CreateInstance("@mozilla.org/file/local;1")); NS_ENSURE_TRUE(file, NS_ERROR_FAILURE); // XXX InitWithPath() will convert UCS2 to FS path !!! corrupts unicode file->InitWithPath(mUnicodeFile); nsCOMPtr<nsIFile> dir; if (NS_SUCCEEDED(file->GetParent(getter_AddRefs(dir)))) { mDisplayDirectory = do_QueryInterface(dir); if (mDisplayDirectory) { if (mLastUsedUnicodeDirectory) { NS_Free(mLastUsedUnicodeDirectory); mLastUsedUnicodeDirectory = nsnull; } nsAutoString newDir; mDisplayDirectory->GetPath(newDir); if(!newDir.IsEmpty()) mLastUsedUnicodeDirectory = ToNewUnicode(newDir); } } if (mMode == modeSave) { // Windows does not return resultReplace, // we must check if file already exists PRBool exists = PR_FALSE; file->Exists(&exists); if (exists) returnOKorReplace = returnReplace; } *aReturnVal = returnOKorReplace; } else { *aReturnVal = returnCancel; } if (mParentWidget) { nsIWidget *tmp = mParentWidget; nsWindow *parent = static_cast<nsWindow *>(tmp); parent->SuppressBlurEvents(PR_FALSE); } return NS_OK; }
static DWORD WINAPI ThreadFunc(LPVOID Context) { CComPtr<IBindStatusCallback> dl; WCHAR path[MAX_PATH]; PWSTR p, q; HWND Dlg = (HWND) Context; ULONG dwContentLen, dwBytesWritten, dwBytesRead, dwStatus; ULONG dwCurrentBytesRead = 0; ULONG dwStatusLen = sizeof(dwStatus); BOOL bCancelled = FALSE; BOOL bTempfile = FALSE; BOOL bCab = FALSE; HINTERNET hOpen = NULL; HINTERNET hFile = NULL; HANDLE hOut = INVALID_HANDLE_VALUE; unsigned char lpBuffer[4096]; PCWSTR lpszAgent = L"RApps/1.0"; URL_COMPONENTS urlComponents; size_t urlLength, filenameLength; /* build the path for the download */ p = wcsrchr(AppInfo->szUrlDownload, L'/'); q = wcsrchr(AppInfo->szUrlDownload, L'?'); /* do we have a final slash separator? */ if (!p) goto end; /* prepare the tentative length of the filename, maybe we've to remove part of it later on */ filenameLength = wcslen(p) * sizeof(WCHAR); /* do we have query arguments in the target URL after the filename? account for them (e.g. https://example.org/myfile.exe?no_adware_plz) */ if (q && q > p && (q - p) > 0) filenameLength -= wcslen(q - 1) * sizeof(WCHAR); /* is this URL an update package for RAPPS? if so store it in a different place */ if (wcscmp(AppInfo->szUrlDownload, APPLICATION_DATABASE_URL) == 0) { bCab = TRUE; if (!GetStorageDirectory(path, _countof(path))) goto end; } else { if (FAILED(StringCbCopyW(path, sizeof(path), SettingsInfo.szDownloadDir))) goto end; } /* is the path valid? can we access it? */ if (GetFileAttributesW(path) == INVALID_FILE_ATTRIBUTES) { if (!CreateDirectoryW(path, NULL)) goto end; } /* append a \ to the provided file system path, and the filename portion from the URL after that */ if (FAILED(StringCbCatW(path, sizeof(path), L"\\"))) goto end; if (FAILED(StringCbCatNW(path, sizeof(path), p + 1, filenameLength))) goto end; if (!bCab && AppInfo->szSHA1[0] != 0 && GetFileAttributesW(path) != INVALID_FILE_ATTRIBUTES) { /* only open it in case of total correctness */ if (VerifyInteg(AppInfo->szSHA1, path)) goto run; } /* download it */ bTempfile = TRUE; CDownloadDialog_Constructor(Dlg, &bCancelled, IID_PPV_ARG(IBindStatusCallback, &dl)); if (dl == NULL) goto end; /* FIXME: this should just be using the system-wide proxy settings */ switch(SettingsInfo.Proxy) { case 0: /* preconfig */ hOpen = InternetOpenW(lpszAgent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); break; case 1: /* direct (no proxy) */ hOpen = InternetOpenW(lpszAgent, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0); break; case 2: /* use proxy */ hOpen = InternetOpenW(lpszAgent, INTERNET_OPEN_TYPE_PROXY, SettingsInfo.szProxyServer, SettingsInfo.szNoProxyFor, 0); break; default: /* preconfig */ hOpen = InternetOpenW(lpszAgent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); break; } if (!hOpen) goto end; hFile = InternetOpenUrlW(hOpen, AppInfo->szUrlDownload, NULL, 0, INTERNET_FLAG_PRAGMA_NOCACHE|INTERNET_FLAG_KEEP_CONNECTION, 0); if (!hFile) goto end; if (!HttpQueryInfoW(hFile, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &dwStatus, &dwStatusLen, NULL)) goto end; if(dwStatus != HTTP_STATUS_OK) { WCHAR szMsgText[MAX_STR_LEN]; if (!LoadStringW(hInst, IDS_UNABLE_TO_DOWNLOAD, szMsgText, sizeof(szMsgText) / sizeof(WCHAR))) goto end; MessageBoxW(hMainWnd, szMsgText, NULL, MB_OK | MB_ICONERROR); goto end; } dwStatusLen = sizeof(dwStatus); memset(&urlComponents, 0, sizeof(urlComponents)); urlComponents.dwStructSize = sizeof(urlComponents); if(FAILED(StringCbLengthW(AppInfo->szUrlDownload, sizeof(AppInfo->szUrlDownload), &urlLength))) goto end; urlLength /= sizeof(WCHAR); urlComponents.dwSchemeLength = urlLength + 1; urlComponents.lpszScheme = (LPWSTR)malloc(urlComponents.dwSchemeLength * sizeof(WCHAR)); urlComponents.dwHostNameLength = urlLength + 1; urlComponents.lpszHostName = (LPWSTR)malloc(urlComponents.dwHostNameLength * sizeof(WCHAR)); if(!InternetCrackUrlW(AppInfo->szUrlDownload, urlLength+1, ICU_DECODE | ICU_ESCAPE, &urlComponents)) goto end; if(urlComponents.nScheme == INTERNET_SCHEME_HTTP || urlComponents.nScheme == INTERNET_SCHEME_HTTPS) HttpQueryInfo(hFile, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &dwContentLen, &dwStatus, 0); if(urlComponents.nScheme == INTERNET_SCHEME_FTP) dwContentLen = FtpGetFileSize(hFile, &dwStatus); #ifdef USE_CERT_PINNING /* are we using HTTPS to download the RAPPS update package? check if the certificate is original */ if ((urlComponents.nScheme == INTERNET_SCHEME_HTTPS) && (wcscmp(AppInfo->szUrlDownload, APPLICATION_DATABASE_URL) == 0) && (!CertIsValid(hOpen, urlComponents.lpszHostName))) { WCHAR szMsgText[MAX_STR_LEN]; if (!LoadStringW(hInst, IDS_CERT_DOES_NOT_MATCH, szMsgText, sizeof(szMsgText) / sizeof(WCHAR))) goto end; MessageBoxW(Dlg, szMsgText, NULL, MB_OK | MB_ICONERROR); goto end; } #endif free(urlComponents.lpszScheme); free(urlComponents.lpszHostName); hOut = CreateFileW(path, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, 0, NULL); if (hOut == INVALID_HANDLE_VALUE) goto end; do { if (!InternetReadFile(hFile, lpBuffer, _countof(lpBuffer), &dwBytesRead)) { WCHAR szMsgText[MAX_STR_LEN]; if (!LoadStringW(hInst, IDS_INTERRUPTED_DOWNLOAD, szMsgText, _countof(szMsgText))) goto end; MessageBoxW(hMainWnd, szMsgText, NULL, MB_OK | MB_ICONERROR); goto end; } if (!WriteFile(hOut, &lpBuffer[0], dwBytesRead, &dwBytesWritten, NULL)) { WCHAR szMsgText[MAX_STR_LEN]; if (!LoadStringW(hInst, IDS_UNABLE_TO_WRITE, szMsgText, _countof(szMsgText))) goto end; MessageBoxW(hMainWnd, szMsgText, NULL, MB_OK | MB_ICONERROR); goto end; } dwCurrentBytesRead += dwBytesRead; dl->OnProgress(dwCurrentBytesRead, dwContentLen, 0, AppInfo->szUrlDownload); } while (dwBytesRead && !bCancelled); CloseHandle(hOut); hOut = INVALID_HANDLE_VALUE; if (bCancelled) goto end; /* if this thing isn't a RAPPS update and it has a SHA-1 checksum verify its integrity by using the native advapi32.A_SHA1 functions */ if (!bCab && AppInfo->szSHA1[0] != 0) { WCHAR szMsgText[MAX_STR_LEN]; /* change a few strings in the download dialog to reflect the verification process */ LoadStringW(hInst, IDS_INTEG_CHECK_TITLE, szMsgText, _countof(szMsgText)); SetWindowText(Dlg, szMsgText); SendMessageW(GetDlgItem(Dlg, IDC_DOWNLOAD_STATUS), WM_SETTEXT, 0, (LPARAM)path); /* this may take a while, depending on the file size */ if (!VerifyInteg(AppInfo->szSHA1, path)) { if (!LoadStringW(hInst, IDS_INTEG_CHECK_FAIL, szMsgText, _countof(szMsgText))) goto end; MessageBoxW(Dlg, szMsgText, NULL, MB_OK | MB_ICONERROR); goto end; } } ShowWindow(Dlg, SW_HIDE); run: /* run it */ if (!bCab) ShellExecuteW( NULL, L"open", path, NULL, NULL, SW_SHOWNORMAL ); end: if (hOut != INVALID_HANDLE_VALUE) CloseHandle(hOut); InternetCloseHandle(hFile); InternetCloseHandle(hOpen); if (bTempfile) { if (bCancelled || (SettingsInfo.bDelInstaller && !bCab)) DeleteFileW(path); } EndDialog(Dlg, 0); return 0; }
static BOOL StartShell(VOID) { WCHAR Shell[MAX_PATH]; WCHAR szMsg[RC_STRING_MAX_SIZE]; DWORD Type, Size; DWORD Value = 0; LONG rc; HKEY hKey; TRACE("()\n"); /* Safe Mode shell run */ rc = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Control\\SafeBoot\\Option", 0, KEY_QUERY_VALUE, &hKey); if (rc == ERROR_SUCCESS) { Size = sizeof(Value); rc = RegQueryValueExW(hKey, L"UseAlternateShell", NULL, &Type, (LPBYTE)&Value, &Size); RegCloseKey(hKey); if (rc == ERROR_SUCCESS) { if (Type == REG_DWORD) { if (Value) { /* Safe Mode Alternate Shell required */ rc = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Control\\SafeBoot", 0, KEY_READ, &hKey); if (rc == ERROR_SUCCESS) { Size = sizeof(Shell); rc = RegQueryValueExW(hKey, L"AlternateShell", NULL, &Type, (LPBYTE)Shell, &Size); RegCloseKey(hKey); if (rc == ERROR_SUCCESS) { if ((Type == REG_SZ) || (Type == REG_EXPAND_SZ)) { TRACE("Key located - %s\n", debugstr_w(Shell)); /* Try to run alternate shell */ if (TryToStartShell(Shell)) { TRACE("Alternate shell started (Safe Mode)\n"); return TRUE; } } else { WARN("Wrong type %lu (expected %u or %u)\n", Type, REG_SZ, REG_EXPAND_SZ); } } else { WARN("Alternate shell in Safe Mode required but not specified."); } } } } else { WARN("Wrong type %lu (expected %u)\n", Type, REG_DWORD); } } } /* Try to run shell in user key */ if (GetShell(Shell, HKEY_CURRENT_USER) && TryToStartShell(Shell)) { TRACE("Started shell from HKEY_CURRENT_USER\n"); return TRUE; } /* Try to run shell in local machine key */ if (GetShell(Shell, HKEY_LOCAL_MACHINE) && TryToStartShell(Shell)) { TRACE("Started shell from HKEY_LOCAL_MACHINE\n"); return TRUE; } /* Try default shell */ if (IsConsoleShell()) { if (GetSystemDirectoryW(Shell, ARRAYSIZE(Shell) - 8)) wcscat(Shell, L"\\cmd.exe"); else wcscpy(Shell, L"cmd.exe"); } else { if (GetWindowsDirectoryW(Shell, ARRAYSIZE(Shell) - 13)) wcscat(Shell, L"\\explorer.exe"); else wcscpy(Shell, L"explorer.exe"); } if (!TryToStartShell(Shell)) { WARN("Failed to start default shell %s\n", debugstr_w(Shell)); LoadStringW(GetModuleHandle(NULL), IDS_SHELL_FAIL, szMsg, ARRAYSIZE(szMsg)); MessageBoxW(NULL, szMsg, NULL, MB_OK); return FALSE; } return TRUE; }
DWORD WINAPI InstallLiveCD(IN HINSTANCE hInstance) { STARTUPINFOW StartupInfo; PROCESS_INFORMATION ProcessInformation; BOOL bRes; if (!CommonInstall()) goto error; /* Register components */ _SEH2_TRY { if (!SetupInstallFromInfSectionW(NULL, hSysSetupInf, L"RegistrationPhase2", SPINST_ALL, 0, NULL, 0, NULL, NULL, NULL, NULL)) { DPRINT1("SetupInstallFromInfSectionW failed!\n"); } RegisterTypeLibraries(hSysSetupInf, L"TypeLibraries"); } _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER) { DPRINT1("Catching exception\n"); } _SEH2_END; SetupCloseInfFile(hSysSetupInf); /* Run the shell */ ZeroMemory(&StartupInfo, sizeof(StartupInfo)); StartupInfo.cb = sizeof(StartupInfo); bRes = CreateProcessW( L"userinit.exe", NULL, NULL, NULL, FALSE, 0, NULL, NULL, &StartupInfo, &ProcessInformation); if (!bRes) goto error; CloseHandle(ProcessInformation.hThread); CloseHandle(ProcessInformation.hProcess); return 0; error: MessageBoxW( NULL, L"Failed to load LiveCD! You can shutdown your computer, or press ENTER to reboot.", L"ReactOS LiveCD", MB_OK); return 0; }
void MessageBox(const wchar_t* caption, const wchar_t* message) { MessageBoxW(0, message, caption, MB_OK | MB_ICONINFORMATION); }
//---------------------------------------------------------------------------------------------------- bool EEPoints2D::InitializePoints2D() { if (!s_isPoints2DInitialized) { HRESULT result; ID3D10Blob *errorMessage = NULL; ID3D10Blob *vertexShaderBuffer = NULL; ID3D10Blob *pixelShaderBuffer = NULL; result = D3DX11CompileFromFileW(L"EEShader\\EEPoints2DShader.hlsl", NULL, NULL, "PointsVS", "vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &vertexShaderBuffer, &errorMessage, NULL); if (FAILED(result)) { if (errorMessage) { MessageBoxA(NULL, (char*)errorMessage->GetBufferPointer(), "ShaderCompileError", MB_YESNO); SAFE_RELEASE(errorMessage); SAFE_RELEASE(vertexShaderBuffer); SAFE_RELEASE(pixelShaderBuffer); } else { MessageBoxW(NULL, L"CompileShader´íÎó!", L"´íÎó", MB_OK); SAFE_RELEASE(errorMessage); SAFE_RELEASE(vertexShaderBuffer); SAFE_RELEASE(pixelShaderBuffer); } return FALSE; } result = D3DX11CompileFromFileW(L"EEShader\\EEPoints2DShader.hlsl", NULL, NULL, "PointsPS", "ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &pixelShaderBuffer, &errorMessage, NULL); if (FAILED(result)) { if (errorMessage) { MessageBoxA(NULL, (char*)errorMessage->GetBufferPointer(), "ShaderCompileError", MB_YESNO); SAFE_RELEASE(errorMessage); SAFE_RELEASE(vertexShaderBuffer); SAFE_RELEASE(pixelShaderBuffer); } else { MessageBoxW(NULL, L"CompileShader´íÎó!", L"´íÎó", MB_OK); SAFE_RELEASE(errorMessage); SAFE_RELEASE(vertexShaderBuffer); SAFE_RELEASE(pixelShaderBuffer); } return FALSE; } result = EECore::s_EECore->GetDevice()->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, &s_pointsVS); if (FAILED(result)) { SAFE_RELEASE(errorMessage); SAFE_RELEASE(vertexShaderBuffer); SAFE_RELEASE(pixelShaderBuffer); return false; } result = EECore::s_EECore->GetDevice()->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &s_pointsPS); if (FAILED(result)) { SAFE_RELEASE(errorMessage); SAFE_RELEASE(vertexShaderBuffer); SAFE_RELEASE(pixelShaderBuffer); return false; } D3D11_INPUT_ELEMENT_DESC inputDesc[1] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; result = EECore::s_EECore->GetDevice()->CreateInputLayout(inputDesc, 1, vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), &s_pointsIL); if (FAILED(result)) { SAFE_RELEASE(errorMessage); SAFE_RELEASE(vertexShaderBuffer); SAFE_RELEASE(pixelShaderBuffer); return false; } SAFE_RELEASE(errorMessage); SAFE_RELEASE(vertexShaderBuffer); SAFE_RELEASE(pixelShaderBuffer); s_isPoints2DInitialized = true; } return true; }
static BOOL ImportRegistryFile(HWND hWnd) { BOOL bRet = FALSE; OPENFILENAME ofn; WCHAR Caption[128], szTitle[512], szText[512]; HKEY hKeyRoot; LPCWSTR pszKeyPath; /* Figure out in which key path we are importing */ pszKeyPath = GetItemPath(g_pChildWnd->hTreeWnd, 0, &hKeyRoot); InitOpenFileName(hWnd, &ofn); LoadStringW(hInst, IDS_IMPORT_REG_FILE, Caption, COUNT_OF(Caption)); ofn.lpstrTitle = Caption; ofn.Flags |= OFN_ENABLESIZING; /* ofn.lCustData = ;*/ if (GetOpenFileName(&ofn)) { /* Look at the extension of the file to determine its type */ if (ofn.nFileExtension >= 1 && _wcsicmp(ofn.lpstrFile + ofn.nFileExtension, L"reg") == 0) /* REGEDIT4 or Windows Registry Editor Version 5.00 */ { /* Open the file */ FILE* fp = _wfopen(ofn.lpstrFile, L"r"); /* Import it */ if (fp == NULL || !import_registry_file(fp)) { /* Error opening the file */ LoadStringW(hInst, IDS_APP_TITLE, szTitle, COUNT_OF(szTitle)); LoadStringW(hInst, IDS_IMPORT_ERROR, szText, COUNT_OF(szText)); InfoMessageBox(hWnd, MB_OK | MB_ICONERROR, szTitle, szText, ofn.lpstrFile); bRet = FALSE; } else { /* Show successful import */ LoadStringW(hInst, IDS_APP_TITLE, szTitle, COUNT_OF(szTitle)); LoadStringW(hInst, IDS_IMPORT_OK, szText, COUNT_OF(szText)); InfoMessageBox(hWnd, MB_OK | MB_ICONINFORMATION, szTitle, szText, ofn.lpstrFile); bRet = TRUE; } /* Close the file */ if (fp) fclose(fp); } else /* Registry Hive Files */ { LoadStringW(hInst, IDS_QUERY_IMPORT_HIVE_CAPTION, szTitle, COUNT_OF(szTitle)); LoadStringW(hInst, IDS_QUERY_IMPORT_HIVE_MSG, szText, COUNT_OF(szText)); /* Display a confirmation message */ if (MessageBoxW(g_pChildWnd->hWnd, szText, szTitle, MB_ICONWARNING | MB_YESNO) == IDYES) { LONG lResult; HKEY hSubKey; /* Open the subkey */ lResult = RegOpenKeyExW(hKeyRoot, pszKeyPath, 0, KEY_WRITE, &hSubKey); if (lResult == ERROR_SUCCESS) { /* Enable the 'restore' privilege, restore the hive then disable the privilege */ EnablePrivilege(SE_RESTORE_NAME, NULL, TRUE); lResult = RegRestoreKey(hSubKey, ofn.lpstrFile, REG_FORCE_RESTORE); EnablePrivilege(SE_RESTORE_NAME, NULL, FALSE); /* Flush the subkey and close it */ RegFlushKey(hSubKey); RegCloseKey(hSubKey); } /* Set the return value */ bRet = (lResult == ERROR_SUCCESS); /* Display error, if any */ if (!bRet) ErrorMessageBox(hWnd, Caption, lResult); } } } else { CheckCommDlgError(hWnd); } /* refresh tree and list views */ RefreshTreeView(g_pChildWnd->hTreeWnd); pszKeyPath = GetItemPath(g_pChildWnd->hTreeWnd, 0, &hKeyRoot); RefreshListView(g_pChildWnd->hListWnd, hKeyRoot, pszKeyPath); return bRet; }
static INT_PTR CALLBACK SettingsDlgProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam) { switch (Msg) { case WM_INITDIALOG: { NewSettingsInfo = SettingsInfo; InitSettingsControls(hDlg, &SettingsInfo); } break; case WM_COMMAND: { switch (LOWORD(wParam)) { case IDC_CHOOSE: ChooseFolder(hDlg); break; case IDC_SAVE_WINDOW_POS: IS_CHECKED(NewSettingsInfo.bSaveWndPos, IDC_SAVE_WINDOW_POS); break; case IDC_UPDATE_AVLIST: IS_CHECKED(NewSettingsInfo.bUpdateAtStart, IDC_UPDATE_AVLIST); break; case IDC_LOG_ENABLED: IS_CHECKED(NewSettingsInfo.bLogEnabled, IDC_LOG_ENABLED); break; case IDC_DEL_AFTER_INSTALL: IS_CHECKED(NewSettingsInfo.bDelInstaller, IDC_DEL_AFTER_INSTALL); break; case IDC_PROXY_DEFAULT: NewSettingsInfo.Proxy = 0; EnableWindow(GetDlgItem(hDlg, IDC_PROXY_SERVER), FALSE); EnableWindow(GetDlgItem(hDlg, IDC_NO_PROXY_FOR), FALSE); break; case IDC_NO_PROXY: NewSettingsInfo.Proxy = 1; EnableWindow(GetDlgItem(hDlg, IDC_PROXY_SERVER), FALSE); EnableWindow(GetDlgItem(hDlg, IDC_NO_PROXY_FOR), FALSE); break; case IDC_USE_PROXY: NewSettingsInfo.Proxy = 2; EnableWindow(GetDlgItem(hDlg, IDC_PROXY_SERVER), TRUE); EnableWindow(GetDlgItem(hDlg, IDC_NO_PROXY_FOR), TRUE); break; case IDC_DEFAULT_SETTINGS: FillDefaultSettings(&NewSettingsInfo); InitSettingsControls(hDlg, &NewSettingsInfo); break; case IDOK: { WCHAR szDir[MAX_PATH]; WCHAR szProxy[MAX_PATH]; WCHAR szNoProxy[MAX_PATH]; DWORD dwAttr; GetWindowTextW(GetDlgItem(hDlg, IDC_DOWNLOAD_DIR_EDIT), szDir, MAX_PATH); GetWindowTextW(GetDlgItem(hDlg, IDC_PROXY_SERVER), szProxy, MAX_PATH); StringCbCopyW(NewSettingsInfo.szProxyServer, sizeof(NewSettingsInfo.szProxyServer), szProxy); GetWindowTextW(GetDlgItem(hDlg, IDC_NO_PROXY_FOR), szNoProxy, MAX_PATH); StringCbCopyW(NewSettingsInfo.szNoProxyFor, sizeof(NewSettingsInfo.szNoProxyFor), szNoProxy); dwAttr = GetFileAttributesW(szDir); if (dwAttr != INVALID_FILE_ATTRIBUTES && (dwAttr & FILE_ATTRIBUTE_DIRECTORY)) { StringCbCopyW(NewSettingsInfo.szDownloadDir, sizeof(NewSettingsInfo.szDownloadDir), szDir); } else { WCHAR szMsgText[MAX_STR_LEN]; LoadStringW(hInst, IDS_CHOOSE_FOLDER_ERROR, szMsgText, sizeof(szMsgText) / sizeof(WCHAR)); if (MessageBoxW(hDlg, szMsgText, NULL, MB_YESNO) == IDYES) { if (CreateDirectoryW(szDir, NULL)) { EndDialog(hDlg, LOWORD(wParam)); } } else { SetFocus(GetDlgItem(hDlg, IDC_DOWNLOAD_DIR_EDIT)); break; } } SettingsInfo = NewSettingsInfo; SaveSettings(GetParent(hDlg)); EndDialog(hDlg, LOWORD(wParam)); } break; case IDCANCEL: EndDialog(hDlg, LOWORD(wParam)); break; } } break; } return FALSE; }
DWORD WINAPI FTHelper2::FaceTrackingThread() { FT_CAMERA_CONFIG videoConfig; FT_CAMERA_CONFIG depthConfig; FT_CAMERA_CONFIG* pDepthConfig = NULL; // Try to get the Kinect camera to work HRESULT hr = m_KinectSensor.Init(m_depthType, m_depthRes, m_bNearMode, FALSE, m_colorType, m_colorRes, m_bSeatedSkeleton); if (SUCCEEDED(hr)) { m_KinectSensorPresent = TRUE; m_KinectSensor.GetVideoConfiguration(&videoConfig); m_KinectSensor.GetDepthConfiguration(&depthConfig); pDepthConfig = &depthConfig; } else { m_KinectSensorPresent = FALSE; MessageBoxW(m_hWnd, L"Could not initialize the Kinect sensor.\n", L"Face Tracker Initialization Error\n", MB_OK); return 1; } m_UserContext = new FTHelperContext[m_nbUsers]; if (m_UserContext != 0) { memset(m_UserContext, 0, sizeof(FTHelperContext)*m_nbUsers); } else { MessageBoxW(m_hWnd, L"Could not allocate user context array.\n", L"Face Tracker Initialization Error\n", MB_OK); return 2; } for (UINT i=0; i<m_nbUsers; i++) { // Try to start the face tracker. m_UserContext[i].m_pFaceTracker = FTCreateFaceTracker(_opt); if (!m_UserContext[i].m_pFaceTracker) { MessageBoxW(m_hWnd, L"Could not create the face tracker.\n", L"Face Tracker Initialization Error\n", MB_OK); return 3; } hr = m_UserContext[i].m_pFaceTracker->Initialize(&videoConfig, pDepthConfig, NULL, NULL); if (FAILED(hr)) { WCHAR path[512], buffer[1024]; GetCurrentDirectoryW(ARRAYSIZE(path), path); wsprintf(buffer, L"Could not initialize face tracker (%s) for user %d.\n", path, i); MessageBoxW(m_hWnd, buffer, L"Face Tracker Initialization Error\n", MB_OK); return 4; } m_UserContext[i].m_pFaceTracker->CreateFTResult(&m_UserContext[i].m_pFTResult); if (!m_UserContext[i].m_pFTResult) { MessageBoxW(m_hWnd, L"Could not initialize the face tracker result for user %d.\n", L"Face Tracker Initialization Error\n", MB_OK); return 5; } m_UserContext[i].m_LastTrackSucceeded = false; } // Initialize the RGB image. m_colorImage = FTCreateImage(); if (!m_colorImage || FAILED(hr = m_colorImage->Allocate(videoConfig.Width, videoConfig.Height, FTIMAGEFORMAT_UINT8_B8G8R8X8))) { return 6; } if (pDepthConfig) { m_depthImage = FTCreateImage(); if (!m_depthImage || FAILED(hr = m_depthImage->Allocate(depthConfig.Width, depthConfig.Height, FTIMAGEFORMAT_UINT16_D13P3))) { return 7; } } SetCenterOfImage(NULL); while (m_ApplicationIsRunning) { CheckCameraInput(); InvalidateRect(m_hWnd, NULL, FALSE); UpdateWindow(m_hWnd); Sleep(16); } return 0; }
/******************************************************************************* * * FUNCTION: _CmdWndProc(HWND, unsigned, WORD, LONG) * * PURPOSE: Processes WM_COMMAND messages for the main frame window. * */ static BOOL _CmdWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { HKEY hKeyRoot = 0, hKey = 0; LPCWSTR keyPath; LPCWSTR valueName; BOOL result = TRUE; REGSAM regsam = KEY_READ; LONG lRet; int item; UNREFERENCED_PARAMETER(lParam); UNREFERENCED_PARAMETER(message); switch (LOWORD(wParam)) { case ID_REGISTRY_LOADHIVE: LoadHive(hWnd); return TRUE; case ID_REGISTRY_UNLOADHIVE: UnloadHive(hWnd); return TRUE; case ID_REGISTRY_IMPORTREGISTRYFILE: ImportRegistryFile(hWnd); return TRUE; case ID_REGISTRY_EXPORTREGISTRYFILE: ExportRegistryFile(hWnd); return TRUE; case ID_REGISTRY_CONNECTNETWORKREGISTRY: { IDsObjectPicker *ObjectPicker; WCHAR szComputerName[MAX_COMPUTERNAME_LENGTH + 1]; HRESULT hRet; hRet = CoInitialize(NULL); if (SUCCEEDED(hRet)) { hRet = InitializeRemoteRegistryPicker(&ObjectPicker); if (SUCCEEDED(hRet)) { hRet = InvokeRemoteRegistryPickerDialog(ObjectPicker, hWnd, szComputerName, COUNT_OF(szComputerName)); if (hRet == S_OK) { /* FIXME - connect to the registry */ } FreeObjectPicker(ObjectPicker); } CoUninitialize(); } return TRUE; } case ID_REGISTRY_DISCONNECTNETWORKREGISTRY: return TRUE; case ID_REGISTRY_PRINT: PrintRegistryHive(hWnd, L""); return TRUE; case ID_REGISTRY_EXIT: DestroyWindow(hWnd); return TRUE; case ID_VIEW_STATUSBAR: toggle_child(hWnd, LOWORD(wParam), hStatusBar); return TRUE; case ID_HELP_HELPTOPICS: WinHelpW(hWnd, getAppName(), HELP_FINDER, 0); return TRUE; case ID_HELP_ABOUT: ShowAboutBox(hWnd); return TRUE; case ID_VIEW_SPLIT: { RECT rt; POINT pt, pts; GetClientRect(g_pChildWnd->hWnd, &rt); pt.x = rt.left + g_pChildWnd->nSplitPos; pt.y = (rt.bottom / 2); pts = pt; if(ClientToScreen(g_pChildWnd->hWnd, &pts)) { SetCursorPos(pts.x, pts.y); SetCursor(LoadCursorW(0, IDC_SIZEWE)); SendMessageW(g_pChildWnd->hWnd, WM_LBUTTONDOWN, 0, MAKELPARAM(pt.x, pt.y)); } return TRUE; } case ID_EDIT_RENAME: case ID_EDIT_MODIFY: case ID_EDIT_MODIFY_BIN: case ID_EDIT_DELETE: regsam |= KEY_WRITE; break; } keyPath = GetItemPath(g_pChildWnd->hTreeWnd, 0, &hKeyRoot); valueName = GetValueName(g_pChildWnd->hListWnd, -1); if (keyPath) { lRet = RegOpenKeyExW(hKeyRoot, keyPath, 0, regsam, &hKey); if (lRet != ERROR_SUCCESS) hKey = 0; } switch (LOWORD(wParam)) { case ID_EDIT_MODIFY: if (valueName && ModifyValue(hWnd, hKey, valueName, FALSE)) RefreshListView(g_pChildWnd->hListWnd, hKeyRoot, keyPath); break; case ID_EDIT_MODIFY_BIN: if (valueName && ModifyValue(hWnd, hKey, valueName, TRUE)) RefreshListView(g_pChildWnd->hListWnd, hKeyRoot, keyPath); break; case ID_EDIT_RENAME: if (GetFocus() == g_pChildWnd->hListWnd) { if(ListView_GetSelectedCount(g_pChildWnd->hListWnd) == 1) { item = ListView_GetNextItem(g_pChildWnd->hListWnd, -1, LVNI_SELECTED); if(item > -1) { (void)ListView_EditLabel(g_pChildWnd->hListWnd, item); } } } else if (GetFocus() == g_pChildWnd->hTreeWnd) { /* Get focused entry of treeview (if any) */ HTREEITEM hItem = TreeView_GetSelection(g_pChildWnd->hTreeWnd); if (hItem != NULL) (void)TreeView_EditLabel(g_pChildWnd->hTreeWnd, hItem); } break; case ID_EDIT_DELETE: { if (GetFocus() == g_pChildWnd->hListWnd) { UINT nSelected = ListView_GetSelectedCount(g_pChildWnd->hListWnd); if(nSelected >= 1) { WCHAR msg[128], caption[128]; LoadStringW(hInst, IDS_QUERY_DELETE_CONFIRM, caption, COUNT_OF(caption)); LoadStringW(hInst, (nSelected == 1 ? IDS_QUERY_DELETE_ONE : IDS_QUERY_DELETE_MORE), msg, COUNT_OF(msg)); if(MessageBoxW(g_pChildWnd->hWnd, msg, caption, MB_ICONQUESTION | MB_YESNO) == IDYES) { int ni, errs; item = -1; errs = 0; while((ni = ListView_GetNextItem(g_pChildWnd->hListWnd, item, LVNI_SELECTED)) > -1) { valueName = GetValueName(g_pChildWnd->hListWnd, item); if(RegDeleteValueW(hKey, valueName) != ERROR_SUCCESS) { errs++; } item = ni; } RefreshListView(g_pChildWnd->hListWnd, hKeyRoot, keyPath); if(errs > 0) { LoadStringW(hInst, IDS_ERR_DELVAL_CAPTION, caption, COUNT_OF(caption)); LoadStringW(hInst, IDS_ERR_DELETEVALUE, msg, COUNT_OF(msg)); MessageBoxW(g_pChildWnd->hWnd, msg, caption, MB_ICONSTOP); } } } } else if (GetFocus() == g_pChildWnd->hTreeWnd) { if (keyPath == 0 || *keyPath == 0) { MessageBeep(MB_ICONHAND); } else if (DeleteKey(hWnd, hKeyRoot, keyPath)) { DeleteNode(g_pChildWnd->hTreeWnd, 0); RefreshTreeView(g_pChildWnd->hTreeWnd); } } break; } case ID_EDIT_NEW_STRINGVALUE: CreateNewValue(hKeyRoot, keyPath, REG_SZ); break; case ID_EDIT_NEW_BINARYVALUE: CreateNewValue(hKeyRoot, keyPath, REG_BINARY); break; case ID_EDIT_NEW_DWORDVALUE: CreateNewValue(hKeyRoot, keyPath, REG_DWORD); break; case ID_EDIT_NEW_MULTISTRINGVALUE: CreateNewValue(hKeyRoot, keyPath, REG_MULTI_SZ); break; case ID_EDIT_NEW_EXPANDABLESTRINGVALUE: CreateNewValue(hKeyRoot, keyPath, REG_EXPAND_SZ); break; case ID_EDIT_FIND: FindDialog(hWnd); break; case ID_EDIT_FINDNEXT: FindNext(hWnd); break; case ID_EDIT_COPYKEYNAME: CopyKeyName(hWnd, hKeyRoot, keyPath); break; case ID_EDIT_PERMISSIONS: RegKeyEditPermissions(hWnd, hKeyRoot, NULL, keyPath); break; case ID_REGISTRY_PRINTERSETUP: /*PRINTDLG pd;*/ /*PrintDlg(&pd);*/ /*PAGESETUPDLG psd;*/ /*PageSetupDlg(&psd);*/ break; case ID_REGISTRY_OPENLOCAL: break; case ID_VIEW_REFRESH: RefreshTreeView(g_pChildWnd->hTreeWnd); keyPath = GetItemPath(g_pChildWnd->hTreeWnd, 0, &hKeyRoot); RefreshListView(g_pChildWnd->hListWnd, hKeyRoot, keyPath); break; /*case ID_OPTIONS_TOOLBAR:*/ /* toggle_child(hWnd, LOWORD(wParam), hToolBar);*/ /* break;*/ case ID_EDIT_NEW_KEY: CreateNewKey(g_pChildWnd->hTreeWnd, TreeView_GetSelection(g_pChildWnd->hTreeWnd)); break; default: if ((LOWORD(wParam) >= ID_FAVORITES_MIN) && (LOWORD(wParam) <= ID_FAVORITES_MAX)) { HMENU hMenu; MENUITEMINFOW mii; WCHAR szFavorite[512]; hMenu = GetSubMenu(GetMenu(hWnd), FAVORITES_MENU_POSITION); memset(&mii, 0, sizeof(mii)); mii.cbSize = sizeof(mii); mii.fMask = MIIM_TYPE; mii.fType = MFT_STRING; mii.dwTypeData = szFavorite; mii.cch = COUNT_OF(szFavorite); if (GetMenuItemInfo(hMenu, LOWORD(wParam) - ID_FAVORITES_MIN, TRUE, &mii)) { ChooseFavorite(szFavorite); } } else { result = FALSE; } break; } if(hKey) RegCloseKey(hKey); return result; }
static BOOL DoUnlock( IN HWND hwndDlg, IN PGINA_CONTEXT pgContext, OUT LPINT Action) { WCHAR Buffer1[256]; WCHAR Buffer2[256]; LPWSTR UserName = NULL; LPWSTR Password = NULL; BOOL res = FALSE; if (GetTextboxText(hwndDlg, IDC_USERNAME, &UserName) && *UserName == '\0') { HeapFree(GetProcessHeap(), 0, UserName); return FALSE; } if (GetTextboxText(hwndDlg, IDC_PASSWORD, &Password)) { if (UserName != NULL && Password != NULL && wcscmp(UserName, pgContext->UserName) == 0 && wcscmp(Password, pgContext->Password) == 0) { *Action = WLX_SAS_ACTION_UNLOCK_WKSTA; res = TRUE; } else if (wcscmp(UserName, pgContext->UserName) == 0 && wcscmp(Password, pgContext->Password) != 0) { /* Wrong Password */ LoadStringW(pgContext->hDllInstance, IDS_LOCKEDWRONGPASSWORD, Buffer2, 256); LoadStringW(pgContext->hDllInstance, IDS_COMPUTERLOCKED, Buffer1, 256); MessageBoxW(hwndDlg, Buffer2, Buffer1, MB_OK | MB_ICONERROR); } else { /* Wrong user name */ if (DoAdminUnlock(pgContext, UserName, NULL, Password)) { *Action = WLX_SAS_ACTION_UNLOCK_WKSTA; res = TRUE; } else { LoadStringW(pgContext->hDllInstance, IDS_LOCKEDWRONGUSER, Buffer1, 256); wsprintfW(Buffer2, Buffer1, pgContext->Domain, pgContext->UserName); LoadStringW(pgContext->hDllInstance, IDS_COMPUTERLOCKED, Buffer1, 256); MessageBoxW(hwndDlg, Buffer2, Buffer1, MB_OK | MB_ICONERROR); } } } if (UserName != NULL) HeapFree(GetProcessHeap(), 0, UserName); if (Password != NULL) HeapFree(GetProcessHeap(), 0, Password); return res; }
static void Fatal(DWORD dw, wchar_t* message, ...) { void *lpDisplayBuf, *lpMsgBuf; if(dw == 0) { // If no return code was specified, we assume that the message // contains a function name that failed. In that case, we retrieve // the system error message for the last-error code dw = GetLastError(); FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (wchar_t*) &lpMsgBuf, 0, NULL ); // Allocate our buffer for the error message. lpDisplayBuf = (void*)LocalAlloc( LMEM_ZEROINIT, (lstrlenW((const wchar_t*)lpMsgBuf) + lstrlenW((const wchar_t*)message) + 47) * sizeof(wchar_t) ); _snwprintf( (wchar_t*)lpDisplayBuf, LocalSize(lpDisplayBuf) / sizeof(wchar_t), L"FATAL: %s failed with error %d: %s", message, dw, lpMsgBuf ); } else { // Otherwise, we assume that the error message is a format string. va_list args = NULL; // Allocate buffer for our resulting format string. lpMsgBuf = (void*)LocalAlloc( LMEM_ZEROINIT, (lstrlenW((const wchar_t*)message) + 8) * sizeof(wchar_t) ); _snwprintf( (wchar_t*)lpMsgBuf, LocalSize(lpMsgBuf) / sizeof(wchar_t), L"FATAL: %s", message ); // Might as well use the maximum allowed buffer, since there's no way I know of the // get the size of the resulting buff. lpDisplayBuf = (void*)LocalAlloc(LMEM_ZEROINIT, 4096 * sizeof(wchar_t)); memset(lpDisplayBuf, 0, 4096 * sizeof(wchar_t)); va_start(args, lpMsgBuf); _vsnwprintf( (wchar_t*)lpDisplayBuf, 4096, lpMsgBuf, args ); va_end(args); } MessageBoxW(NULL, (const wchar_t*)lpDisplayBuf, L"Fatal Error", MB_OK | MB_ICONERROR); LocalFree(lpMsgBuf); LocalFree(lpDisplayBuf); ExitProcess(dw); }
BOOL HandleCommandMessage(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { int wmID, wmEvent; wmID = LOWORD(wParam); wmEvent = HIWORD(wParam); switch (wmEvent) { case BN_CLICKED: switch (wmID) { case IDC_ADD: { SaveLocalizationText(); // save any current changes to the database plString buttonText; wchar_t buff[256]; GetDlgItemText(gEditDlg, IDC_ADD, buff, 256); buttonText = plString::FromWchar(buff); if (buttonText == "Add Element") { plAddElementDlg dlg(gCurrentPath); if (dlg.DoPick(gEditDlg)) { plString path = dlg.GetValue(); // path is age.set.name if (!pfLocalizationDataMgr::Instance().AddElement(path)) MessageBox(gEditDlg, L"Couldn't add new element because one already exists with that name!", L"Error", MB_ICONERROR | MB_OK); else { gCurrentPath = ""; plLocTreeView::ClearTreeView(gTreeView); plLocTreeView::FillTreeViewFromData(gTreeView, path); UpdateEditDlg(path); } } } else if (buttonText == "Add Localization") { plAddLocalizationDlg dlg(gCurrentPath); if (dlg.DoPick(gEditDlg)) { plString newLanguage = dlg.GetValue(); plString ageName, setName, elementName, elementLanguage; SplitLocalizationPath(gCurrentPath, ageName, setName, elementName, elementLanguage); plString key = plString::Format("%s.%s.%s", ageName.c_str(), setName.c_str(), elementName.c_str()); if (!pfLocalizationDataMgr::Instance().AddLocalization(key, newLanguage)) MessageBox(gEditDlg, L"Couldn't add additional localization!", L"Error", MB_ICONERROR | MB_OK); else { plString path = plString::Format("%s.%s", key.c_str(), newLanguage.c_str()); gCurrentPath = ""; plLocTreeView::ClearTreeView(gTreeView); plLocTreeView::FillTreeViewFromData(gTreeView, path); UpdateEditDlg(path); } } } return FALSE; } case IDC_DELETE: { SaveLocalizationText(); // save any current changes to the database plString messageText = plString::Format("Are you sure that you want to delete %s?", gCurrentPath.c_str()); int res = MessageBoxW(gEditDlg, messageText.ToWchar(), L"Delete", MB_ICONQUESTION | MB_YESNO); if (res == IDYES) { plString buttonText; wchar_t buff[256]; GetDlgItemText(gEditDlg, IDC_DELETE, buff, 256); buttonText = plString::FromWchar(buff); if (buttonText == "Delete Element") { if (!pfLocalizationDataMgr::Instance().DeleteElement(gCurrentPath)) MessageBox(gEditDlg, L"Couldn't delete element!", L"Error", MB_ICONERROR | MB_OK); else { plString path = gCurrentPath; gCurrentPath = ""; plLocTreeView::ClearTreeView(gTreeView); plLocTreeView::FillTreeViewFromData(gTreeView, path); UpdateEditDlg(path); } } else if (buttonText == "Delete Localization") { plString ageName, setName, elementName, elementLanguage; SplitLocalizationPath(gCurrentPath, ageName, setName, elementName, elementLanguage); plString key = plString::Format("%s.%s.%s", ageName.c_str(), setName.c_str(), elementName.c_str()); if (!pfLocalizationDataMgr::Instance().DeleteLocalization(key, elementLanguage)) MessageBox(gEditDlg, L"Couldn't delete localization!", L"Error", MB_ICONERROR | MB_OK); else { plString path = gCurrentPath; gCurrentPath = ""; plLocTreeView::ClearTreeView(gTreeView); plLocTreeView::FillTreeViewFromData(gTreeView, path); UpdateEditDlg(path); } } } } return FALSE; } } return (BOOL)DefWindowProc(hWnd, msg, wParam, lParam); }
int DoInjectHooks(LPWSTR asCmdArg) { gbInShutdown = TRUE; // чтобы не возникло вопросов при выходе gnRunMode = RM_SETHOOK64; LPWSTR pszNext = asCmdArg; LPWSTR pszEnd = NULL; BOOL lbForceGui = FALSE; PROCESS_INFORMATION pi = {NULL}; pi.hProcess = (HANDLE)wcstoul(pszNext, &pszEnd, 16); if (pi.hProcess && pszEnd && *pszEnd) { pszNext = pszEnd+1; pi.dwProcessId = wcstoul(pszNext, &pszEnd, 10); } if (pi.dwProcessId && pszEnd && *pszEnd) { pszNext = pszEnd+1; pi.hThread = (HANDLE)wcstoul(pszNext, &pszEnd, 16); } if (pi.hThread && pszEnd && *pszEnd) { pszNext = pszEnd+1; pi.dwThreadId = wcstoul(pszNext, &pszEnd, 10); } if (pi.dwThreadId && pszEnd && *pszEnd) { pszNext = pszEnd+1; lbForceGui = wcstoul(pszNext, &pszEnd, 10); } #ifdef SHOW_INJECT_MSGBOX wchar_t szDbgMsg[512], szTitle[128]; PROCESSENTRY32 pinf; GetProcessInfo(pi.dwProcessId, &pinf); _wsprintf(szTitle, SKIPLEN(countof(szTitle)) L"ConEmuCD PID=%u", GetCurrentProcessId()); _wsprintf(szDbgMsg, SKIPLEN(countof(szDbgMsg)) L"InjectsTo PID=%s {%s}\nConEmuCD PID=%u", asCmdArg ? asCmdArg : L"", pinf.szExeFile, GetCurrentProcessId()); MessageBoxW(NULL, szDbgMsg, szTitle, MB_SYSTEMMODAL); #endif if (pi.hProcess && pi.hThread && pi.dwProcessId && pi.dwThreadId) { // Аргумент abForceGui не использовался CINJECTHK_EXIT_CODES iHookRc = InjectHooks(pi, /*lbForceGui,*/ gbLogProcess); if (iHookRc == CIH_OK/*0*/) { return CERR_HOOKS_WAS_SET; } // Ошибку (пока во всяком случае) лучше показать, для отлова возможных проблем DWORD nErrCode = GetLastError(); //_ASSERTE(iHookRc == 0); -- ассерт не нужен, есть MsgBox wchar_t szDbgMsg[255], szTitle[128]; _wsprintf(szTitle, SKIPLEN(countof(szTitle)) L"ConEmuC, PID=%u", GetCurrentProcessId()); _wsprintf(szDbgMsg, SKIPLEN(countof(szDbgMsg)) L"ConEmuC.X, PID=%u\nInjecting hooks into PID=%u\nFAILED, code=%i:0x%08X", GetCurrentProcessId(), pi.dwProcessId, iHookRc, nErrCode); MessageBoxW(NULL, szDbgMsg, szTitle, MB_SYSTEMMODAL); } else { //_ASSERTE(pi.hProcess && pi.hThread && pi.dwProcessId && pi.dwThreadId); wchar_t szDbgMsg[512], szTitle[128]; _wsprintf(szTitle, SKIPLEN(countof(szTitle)) L"ConEmuC, PID=%u", GetCurrentProcessId()); _wsprintf(szDbgMsg, SKIPLEN(countof(szDbgMsg)) L"ConEmuC.X, PID=%u\nCmdLine parsing FAILED (%u,%u,%u,%u,%u)!\n%s", GetCurrentProcessId(), LODWORD(pi.hProcess), LODWORD(pi.hThread), pi.dwProcessId, pi.dwThreadId, lbForceGui, //-V205 asCmdArg); MessageBoxW(NULL, szDbgMsg, szTitle, MB_SYSTEMMODAL); } return CERR_HOOKS_FAILED; }
// IDYES - Close All consoles // IDNO - Close active console only // IDCANCEL - As is int ConfirmCloseConsoles(const ConfirmCloseParam& Parm) { DontEnable de; if (Parm.rpLeaveConEmuOpened) *Parm.rpLeaveConEmuOpened = false; // Use TaskDialog? if (gOSVer.dwMajorVersion >= 6) { // must be already initialized: CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE); wchar_t szMessage[128]; lstrcpyn(szMessage, Parm.asSingleConsole ? Parm.asSingleConsole : Parm.bForceKill ? L"Confirm killing?" : L"Confirm closing?", countof(szMessage)); wchar_t szWWW[MAX_PATH]; _wsprintf(szWWW, SKIPLEN(countof(szWWW)) L"<a href=\"%s\">%s</a>", gsHomePage, gsHomePage); wchar_t szCloseAll[MAX_PATH*2]; wchar_t *pszText; if (Parm.asSingleConsole) { wcscpy_c(szCloseAll, L"Yes\n"); pszText = szCloseAll + _tcslen(szCloseAll); lstrcpyn(pszText, Parm.asSingleTitle, min(MAX_PATH,(countof(szCloseAll)-(pszText-szCloseAll)))); pszText += _tcslen(pszText); } else { _wsprintf(szCloseAll, SKIPLEN(countof(szCloseAll)) (Parm.bGroup && (Parm.nConsoles>1)) ? ((Parm.bGroup == ConfirmCloseParam::eGroup) ? L"Close group (%u console%s)" : L"Close (%u console%s)") : L"Close all %u console%s.", Parm.nConsoles, (Parm.nConsoles>1)?L"s":L""); pszText = szCloseAll + _tcslen(szCloseAll); } if ((Parm.asSingleConsole == NULL) || (Parm.nOperations || Parm.nUnsavedEditors)) { //if (nOperations) { _wsprintf(pszText, SKIPLEN(countof(szCloseAll)-(pszText-szCloseAll)) L"\nIncomplete operations: %i", Parm.nOperations); pszText += _tcslen(pszText); } //if (nUnsavedEditors) { _wsprintf(pszText, SKIPLEN(countof(szCloseAll)-(pszText-szCloseAll)) L"\nUnsaved editor windows: %i", Parm.nUnsavedEditors); pszText += _tcslen(pszText); } } wchar_t szCloseOne[MAX_PATH]; wcscpy_c(szCloseOne, L"Close active console only"); if (Parm.nConsoles > 1) { CVConGuard VCon; int iCon = gpConEmu->GetActiveVCon(&VCon); if (iCon >= 0) { pszText = szCloseOne + _tcslen(szCloseOne); _wsprintf(pszText, SKIPLEN(countof(szCloseOne)-(pszText-szCloseOne)) L"\n#%u: ", (iCon+1)); pszText += _tcslen(pszText); lstrcpyn(pszText, VCon->RCon()->GetTitle(true), countof(szCloseOne)-(pszText-szCloseOne)); } } const wchar_t* szCancel = L"Cancel\nDon't close anything"; int nButtonPressed = 0; TASKDIALOGCONFIG config = {sizeof(config)}; TASKDIALOG_BUTTON buttons[] = { { IDYES, szCloseAll }, { IDNO, szCloseOne }, { IDCANCEL, szCancel }, }; config.cButtons = countof(buttons); if (Parm.nConsoles <= 1) { buttons[1] = buttons[2]; config.cButtons--; } config.hwndParent = ghWnd; config.hInstance = NULL /*g_hInstance*/; config.dwFlags = TDF_USE_HICON_MAIN|TDF_USE_COMMAND_LINKS|TDF_ALLOW_DIALOG_CANCELLATION |TDF_ENABLE_HYPERLINKS; //|TDIF_SIZE_TO_CONTENT|TDF_CAN_BE_MINIMIZED; //config.pszMainIcon = MAKEINTRESOURCE(IDI_ICON1); config.hMainIcon = hClassIcon; config.pszWindowTitle = gpConEmu->GetDefaultTitle(); config.pszMainInstruction = szMessage; //config.pszContent = L"..."; config.pButtons = buttons; config.nDefaultButton = IDYES; config.pszFooter = szWWW; config.pfCallback = TaskDlgCallback; //{ // config.dwFlags |= TDF_VERIFICATION_FLAG_CHECKED; // config.pszVerificationText = L"Text on checkbox"; //} if (!TaskDialogIndirect_f) { HMODULE hDll = GetModuleHandle(L"comctl32.dll"); if (!hDll) { hDll = LoadLibrary(L"comctl32.dll"); } TaskDialogIndirect_f = (TaskDialogIndirect_t)(hDll?GetProcAddress(hDll, "TaskDialogIndirect"):NULL); } BOOL lbCheckBox = TRUE; if (TaskDialogIndirect_f) { HRESULT hr = TaskDialogIndirect_f(&config, &nButtonPressed, NULL, &lbCheckBox); if (hr == S_OK) { //TODO: lbCheckBox? switch (nButtonPressed) { case IDCANCEL: // user cancelled the dialog case IDYES: case IDNO: return nButtonPressed; default: _ASSERTE(nButtonPressed==IDCANCEL||nButtonPressed==IDYES||nButtonPressed==IDNO); break; // should never happen } } } } // »наче - через стандартный MessageBox wchar_t szText[512], *pszText; if (Parm.asSingleConsole) { lstrcpyn(szText, Parm.asSingleConsole ? Parm.asSingleConsole : Parm.bForceKill ? L"Confirm killing?" : L"Confirm closing?", min(128,countof(szText))); wcscat_c(szText, L"\r\n\r\n"); int nLen = lstrlen(szText); lstrcpyn(szText+nLen, Parm.asSingleTitle, countof(szText)-nLen); } else { _wsprintf(szText, SKIPLEN(countof(szText)) L"About to close %u console%s.\r\n", Parm.nConsoles, (Parm.nConsoles>1)?L"s":L""); } pszText = szText+_tcslen(szText); if (Parm.nOperations || Parm.nUnsavedEditors) { *(pszText++) = L'\r'; *(pszText++) = L'\n'; *(pszText) = 0; if (Parm.nOperations) { _wsprintf(pszText, SKIPLEN(countof(szText)-(pszText-szText)) L"Incomplete operations: %i\r\n", Parm.nOperations); pszText += _tcslen(pszText); } if (Parm.nUnsavedEditors) { _wsprintf(pszText, SKIPLEN(countof(szText)-(pszText-szText)) L"Unsaved editor windows: %i\r\n", Parm.nUnsavedEditors); pszText += _tcslen(pszText); } } if (Parm.nConsoles > 1) { //if (rpPanes) // wcscat_c(szText, L"\r\nProceed with close group?"); //else wcscat_c(szText, L"\r\nPress button <No> to close active console only\r\n" L"\r\nProceed with close ConEmu?"); } int nBtn = MessageBoxW(ghWnd, szText, gpConEmu->GetDefaultTitle(), (/*rpPanes ? MB_OKCANCEL :*/ (Parm.nConsoles>1) ? MB_YESNOCANCEL : MB_OKCANCEL)|MB_ICONEXCLAMATION); if (nBtn == IDOK) { nBtn = IDYES; // дл¤ однозначности } return nBtn; }
int DoInjectRemote(LPWSTR asCmdArg, bool abDefTermOnly) { gbInShutdown = TRUE; // чтобы не возникло вопросов при выходе gnRunMode = RM_SETHOOK64; LPWSTR pszNext = asCmdArg; LPWSTR pszEnd = NULL; DWORD nRemotePID = wcstoul(pszNext, &pszEnd, 10); wchar_t szStr[16]; wchar_t szTitle[128]; wchar_t szInfo[120]; wchar_t szParentPID[32]; #ifdef SHOW_INJECTREM_MSGBOX wchar_t szDbgMsg[512], szTitle[128]; PROCESSENTRY32 pinf; GetProcessInfo(nRemotePID, &pinf); _wsprintf(szTitle, SKIPLEN(countof(szTitle)) L"ConEmuCD PID=%u", GetCurrentProcessId()); _wsprintf(szDbgMsg, SKIPLEN(countof(szDbgMsg)) L"Hooking PID=%s {%s}\nConEmuCD PID=%u. Continue with injects?", asCmdArg ? asCmdArg : L"", pinf.szExeFile, GetCurrentProcessId()); if (MessageBoxW(NULL, szDbgMsg, szTitle, MB_SYSTEMMODAL|MB_OKCANCEL) != IDOK) { return CERR_HOOKS_FAILED; } #endif if (nRemotePID) { #if defined(SHOW_ATTACH_MSGBOX) if (!IsDebuggerPresent()) { wchar_t szTitle[100]; _wsprintf(szTitle, SKIPLEN(countof(szTitle)) L"%s PID=%u /INJECT", gsModuleName, gnSelfPID); const wchar_t* pszCmdLine = GetCommandLineW(); MessageBox(NULL,pszCmdLine,szTitle,MB_SYSTEMMODAL); } #endif CEStr lsName, lsPath; { CProcessData processes; processes.GetProcessName(nRemotePID, lsName.GetBuffer(MAX_PATH), MAX_PATH, lsPath.GetBuffer(MAX_PATH*2), MAX_PATH*2, NULL); CEStr lsLog(L"Remote: PID=", _ultow(nRemotePID, szStr, 10), L" Name=`", lsName, L"` Path=`", lsPath, L"`"); LogString(lsLog); } // Go to hook // InjectRemote waits for thread termination DWORD nErrCode = 0; CINFILTRATE_EXIT_CODES iHookRc = InjectRemote(nRemotePID, abDefTermOnly, &nErrCode); _wsprintf(szInfo, SKIPCOUNT(szInfo) L"InjectRemote result: %i (%s)", iHookRc, (iHookRc == CIR_OK) ? L"CIR_OK" : (iHookRc == CIR_AlreadyInjected) ? L"CIR_AlreadyInjected" : L"?"); LogString(szInfo); if (iHookRc == CIR_OK/*0*/ || iHookRc == CIR_AlreadyInjected/*1*/) { return iHookRc ? CERR_HOOKS_WAS_ALREADY_SET : CERR_HOOKS_WAS_SET; } DWORD nSelfPID = GetCurrentProcessId(); PROCESSENTRY32 self = {sizeof(self)}, parent = {sizeof(parent)}; // Not optimal, needs refactoring if (GetProcessInfo(nSelfPID, &self)) GetProcessInfo(self.th32ParentProcessID, &parent); // Ошибку (пока во всяком случае) лучше показать, для отлова возможных проблем //_ASSERTE(iHookRc == 0); -- ассерт не нужен, есть MsgBox _wsprintf(szTitle, SKIPLEN(countof(szTitle)) L"%s %s, PID=%u", gsModuleName, gsVersion, nSelfPID); _wsprintf(szInfo, SKIPCOUNT(szInfo) L"Injecting remote FAILED, code=%i:0x%08X\n" L"%s %s, PID=%u\n" L"RemotePID=%u ", iHookRc, nErrCode, gsModuleName, gsVersion, nSelfPID, nRemotePID); _wsprintf(szParentPID, SKIPCOUNT(szParentPID) L"\n" L"ParentPID=%u ", self.th32ParentProcessID); CEStr lsError(lstrmerge( szInfo, lsPath.IsEmpty() ? lsName.IsEmpty() ? L"<Unknown>" : lsName.ms_Val : lsPath.ms_Val, szParentPID, parent.szExeFile)); LogString(lsError); MessageBoxW(NULL, lsError, szTitle, MB_SYSTEMMODAL); } else { //_ASSERTE(pi.hProcess && pi.hThread && pi.dwProcessId && pi.dwThreadId); wchar_t szDbgMsg[512], szTitle[128]; _wsprintf(szTitle, SKIPLEN(countof(szTitle)) L"ConEmuC, PID=%u", GetCurrentProcessId()); _wsprintf(szDbgMsg, SKIPLEN(countof(szDbgMsg)) L"ConEmuC.X, PID=%u\nCmdLine parsing FAILED (%u)!\n%s", GetCurrentProcessId(), nRemotePID, asCmdArg); LogString(szDbgMsg); MessageBoxW(NULL, szDbgMsg, szTitle, MB_SYSTEMMODAL); } return CERR_HOOKS_FAILED; }
/************************************************************************** * MAPISendMail (MAPI32.211) * * Send a mail. * * PARAMS * session [I] Handle to a MAPI session. * uiparam [I] Parent window handle. * message [I] Pointer to a MAPIMessage structure. * flags [I] Flags. * reserved [I] Reserved, pass 0. * * RETURNS * Success: SUCCESS_SUCCESS * Failure: MAPI_E_FAILURE * */ ULONG WINAPI MAPISendMail( LHANDLE session, ULONG_PTR uiparam, lpMapiMessage message, FLAGS flags, ULONG reserved ) { WCHAR msg_title[READ_BUF_SIZE], error_msg[READ_BUF_SIZE]; /* Check to see if we have a Simple MAPI provider loaded */ if (mapiFunctions.MAPISendMail) return mapiFunctions.MAPISendMail(session, uiparam, message, flags, reserved); /* Check if we have an Extended MAPI provider - if so, use our wrapper */ if (MAPIInitialize(NULL) == S_OK) { MapiMessageW messageW; ULONG ret; ZeroMemory(&messageW, sizeof(MapiMessageW)); /* Convert the entries we need to Unicode */ messageW.lpszSubject = convert_to_unicode(message->lpszSubject); messageW.lpszNoteText = convert_to_unicode(message->lpszNoteText); messageW.nFileCount = message->nFileCount; if (message->nFileCount && message->lpFiles) { lpMapiFileDescW filesW; unsigned int i; filesW = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(MapiFileDescW) * message->nFileCount); for (i = 0; i < message->nFileCount; i++) { filesW[i].lpszPathName = convert_to_unicode(message->lpFiles[i].lpszPathName); filesW[i].lpszFileName = convert_to_unicode(message->lpFiles[i].lpszFileName); } messageW.lpFiles = filesW; } ret = sendmail_extended_mapi(session, uiparam, &messageW, flags); /* Now free everything we allocated */ if (message->nFileCount && message->lpFiles) { unsigned int i; for (i = 0; i < message->nFileCount; i++) { HeapFree(GetProcessHeap(), 0, messageW.lpFiles[i].lpszPathName); HeapFree(GetProcessHeap(), 0, messageW.lpFiles[i].lpszFileName); } HeapFree(GetProcessHeap(), 0, messageW.lpFiles); } HeapFree(GetProcessHeap(), 0, messageW.lpszSubject); HeapFree(GetProcessHeap(), 0, messageW.lpszNoteText); return ret; } /* Display an error message since we apparently have no mail clients */ LoadStringW(hInstMAPI32, IDS_NO_MAPI_CLIENT, error_msg, sizeof(error_msg) / sizeof(WCHAR)); LoadStringW(hInstMAPI32, IDS_SEND_MAIL, msg_title, sizeof(msg_title) / sizeof(WCHAR)); MessageBoxW((HWND) uiparam, error_msg, msg_title, MB_ICONEXCLAMATION); return MAPI_E_NOT_SUPPORTED; }
DWORD WINAPI WorkingThread ( void* pParam ) { HRESULT hResult = S_OK; PVOID pClientContext = pParam; PVOID pMessage; PMKLIF_EVENT_HDR pEventHdr; ULONG MessageSize; MKLIF_REPLY_EVENT Verdict; hResult = MKL_BuildMultipleWait( pClientContext, 1 ); if ( SUCCEEDED( hResult ) ) while(TRUE) { hResult = MKL_GetSingleMessage( pClientContext, &pMessage, &MessageSize, &pEventHdr, 1000, &gbStop ); if (!SUCCEEDED( hResult) ) { MessageBoxW( NULL, L"MKL_GetSingleMessage", L"Error", MB_OK ); break; } else { PWCHAR wcFullFileName = NULL; PWCHAR wcVirtFullFileName = NULL; __try { WCHAR VolumeDosName[4], VirtVolumeDosName[4]; ULONG wcFileNameSize = 0; ULONG wcFullFileNameSize = 0; ULONG wcVirtFileNameSize = 0; ULONG wcVirtFullFileNameSize = 0; //DebugBreak(); memset( &Verdict, 0, sizeof(Verdict) ); Verdict.m_VerdictFlags = efVerdict_Pending; Verdict.m_ExpTime = 3600; PSINGLE_PARAM pFileName = MKL_GetEventParam( pMessage, MessageSize, _PARAM_OBJECT_URL_W, FALSE ); PSINGLE_PARAM pVolumeName = MKL_GetEventParam( pMessage, MessageSize, _PARAM_OBJECT_VOLUME_NAME_W, FALSE ); PSINGLE_PARAM pVirtFileName = MKL_GetEventParam( pMessage, MessageSize, _PARAM_OBJECT_URL_DEST_W, FALSE ); PSINGLE_PARAM pVirtVolumeName = MKL_GetEventParam( pMessage, MessageSize, _PARAM_OBJECT_VOLUME_NAME_DEST_W, FALSE ); PSINGLE_PARAM pParamSID = MKL_GetEventParam( pMessage, MessageSize, _PARAM_OBJECT_SID, FALSE ); PSINGLE_PARAM pAction = MKL_GetEventParam( pMessage, MessageSize, _PARAM_OBJECT_ACCESSATTR, FALSE ); hResult = MKL_ReplyMessage( pClientContext, pMessage, &Verdict ); Verdict.m_VerdictFlags = efVerdict_Default; Verdict.m_ExpTime = 0; if ( pVolumeName ) { hResult = MKL_GetVolumeName(pClientContext, (PWCHAR) pVolumeName->ParamValue, VolumeDosName, sizeof(VolumeDosName) / sizeof(WCHAR)); if ( IS_ERROR( hResult ) ) { MessageBoxW( NULL, L"MKL_GetVolumeName - pVolumeName", L"Error", MB_OK ); __leave; } } if ( pVirtVolumeName ) { hResult = MKL_GetVolumeName(pClientContext, (PWCHAR) pVirtVolumeName->ParamValue, VirtVolumeDosName, sizeof(VirtVolumeDosName) / sizeof(WCHAR)); if ( IS_ERROR( hResult ) ) { MessageBoxW( NULL, L"MKL_GetVolumeName - pVirtVolumeName", L"Error", MB_OK ); __leave; } } wcFileNameSize = pFileName->ParamSize - pVolumeName->ParamSize; wcFullFileNameSize = sizeof(VolumeDosName) + wcFileNameSize + sizeof(WCHAR); wcFullFileName = (WCHAR *) new char [ wcFullFileNameSize ]; if ( !wcFullFileName ) { MessageBoxW( NULL, L"Allocate memory is Error", L"Error", MB_OK ); __leave; } memset( wcFullFileName, 0, wcFullFileNameSize ); wcsncat(wcFullFileName, VolumeDosName, (sizeof(VolumeDosName)-sizeof(WCHAR))/sizeof(WCHAR) ); wcsncat( wcFullFileName, (WCHAR*)((char*)pFileName->ParamValue+pVolumeName->ParamSize - sizeof(WCHAR) ), (pFileName->ParamSize - pVolumeName->ParamSize)/sizeof(WCHAR) ); wcVirtFileNameSize = pVirtFileName->ParamSize - pVirtVolumeName->ParamSize; wcVirtFullFileNameSize = sizeof(VirtVolumeDosName) + wcVirtFileNameSize + sizeof(WCHAR); wcVirtFullFileName = (WCHAR *) new char [ wcVirtFullFileNameSize ]; if ( !wcVirtFullFileName ) { MessageBoxW( NULL, L"Allocate memory is Error", L"Error", MB_OK ); __leave; } memset( wcVirtFullFileName, 0, wcVirtFullFileNameSize ); wcsncat(wcVirtFullFileName, VirtVolumeDosName, (sizeof(VirtVolumeDosName)-sizeof(WCHAR))/sizeof(WCHAR) ); wcsncat( wcVirtFullFileName, (WCHAR*)((char*)pVirtFileName->ParamValue+pVirtVolumeName->ParamSize - sizeof(WCHAR) ), (pVirtFileName->ParamSize - pVirtVolumeName->ParamSize)/sizeof(WCHAR) ); Verdict.m_ExpTime = 0; switch( *(VIRT_ACTION*)pAction->ParamValue ) { case VA_MakeDir: Verdict.m_VerdictFlags = MyMakeDirectory( wcVirtFullFileName ); break; case VA_CopyFile: Verdict.m_VerdictFlags = MyCopyFile( wcVirtFullFileName, wcFullFileName ); break; default: break; } } __finally { if ( wcVirtFullFileName ) { delete [] wcVirtFullFileName; wcVirtFullFileName = NULL; } if ( wcFullFileName ) { delete [] wcFullFileName; wcVirtFullFileName = NULL; } MKL_SetVerdict(pClientContext, pMessage, &Verdict ); MKL_FreeSingleMessage( pClientContext, &pMessage ); } } } // if ( pClientContext ) // { // MKL_ChangeClientActiveStatus( pClientContext, FALSE ); // MKL_DelAllFilters( pClientContext ); // MKL_ClientUnregister( (PVOID*)&pClientContext ); // // pClientContext = NULL; // } return 0; }
/************************************************************************** * MAPISendMailW (MAPI32.256) * * Send a mail. * * PARAMS * session [I] Handle to a MAPI session. * uiparam [I] Parent window handle. * message [I] Pointer to a MAPIMessageW structure. * flags [I] Flags. * reserved [I] Reserved, pass 0. * * RETURNS * Success: SUCCESS_SUCCESS * Failure: MAPI_E_FAILURE * */ ULONG WINAPI MAPISendMailW(LHANDLE session, ULONG_PTR uiparam, lpMapiMessageW message, FLAGS flags, ULONG reserved) { WCHAR msg_title[READ_BUF_SIZE], error_msg[READ_BUF_SIZE]; /* Check to see if we have a Simple MAPI provider loaded */ if (mapiFunctions.MAPISendMailW) return mapiFunctions.MAPISendMailW(session, uiparam, message, flags, reserved); /* Check if we have an Extended MAPI provider - if so, use our wrapper */ if (MAPIInitialize(NULL) == S_OK) return sendmail_extended_mapi(session, uiparam, message, flags); if (mapiFunctions.MAPISendMail) { MapiMessage messageA; ULONG ret; if (flags & MAPI_FORCE_UNICODE) return MAPI_E_UNICODE_NOT_SUPPORTED; /* Convert to ANSI and send to MAPISendMail */ ZeroMemory(&messageA, sizeof(MapiMessage)); messageA.lpszSubject = convert_from_unicode(message->lpszSubject); messageA.lpszNoteText = convert_from_unicode(message->lpszNoteText); messageA.lpszMessageType = convert_from_unicode(message->lpszMessageType); messageA.lpszDateReceived = convert_from_unicode(message->lpszDateReceived); messageA.lpszConversationID = convert_from_unicode(message->lpszConversationID); messageA.flFlags = message->flFlags; messageA.lpOriginator = convert_recipient_from_unicode(message->lpOriginator, NULL); messageA.nRecipCount = message->nRecipCount; messageA.nFileCount = message->nFileCount; if (message->nRecipCount && message->lpRecips) { lpMapiRecipDesc recipsA; unsigned int i; recipsA = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(MapiRecipDesc) * message->nRecipCount); for (i = 0; i < message->nRecipCount; i++) { convert_recipient_from_unicode(&message->lpRecips[i], &recipsA[i]); } messageA.lpRecips = recipsA; } if (message->nFileCount && message->lpFiles) { lpMapiFileDesc filesA; unsigned int i; filesA = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(MapiFileDesc) * message->nFileCount); for (i = 0; i < message->nFileCount; i++) { filesA[i].flFlags = message->lpFiles[i].flFlags; filesA[i].nPosition = message->lpFiles[i].nPosition; filesA[i].lpszPathName = convert_from_unicode(message->lpFiles[i].lpszPathName); filesA[i].lpszFileName = convert_from_unicode(message->lpFiles[i].lpszFileName); filesA[i].lpFileType = message->lpFiles[i].lpFileType; } messageA.lpFiles = filesA; } ret = mapiFunctions.MAPISendMail(session, uiparam, &messageA, flags, reserved); /* Now free everything we allocated */ if (message->lpOriginator) { HeapFree(GetProcessHeap(), 0, messageA.lpOriginator->lpszName); HeapFree(GetProcessHeap(), 0, messageA.lpOriginator->lpszAddress); HeapFree(GetProcessHeap(), 0, messageA.lpOriginator); } if (message->nRecipCount && message->lpRecips) { unsigned int i; for (i = 0; i < message->nRecipCount; i++) { HeapFree(GetProcessHeap(), 0, messageA.lpRecips[i].lpszName); HeapFree(GetProcessHeap(), 0, messageA.lpRecips[i].lpszAddress); } HeapFree(GetProcessHeap(), 0, messageA.lpRecips); } if (message->nFileCount && message->lpFiles) { unsigned int i; for (i = 0; i < message->nFileCount; i++) { HeapFree(GetProcessHeap(), 0, messageA.lpFiles[i].lpszPathName); HeapFree(GetProcessHeap(), 0, messageA.lpFiles[i].lpszFileName); } HeapFree(GetProcessHeap(), 0, messageA.lpFiles); } HeapFree(GetProcessHeap(), 0, messageA.lpszSubject); HeapFree(GetProcessHeap(), 0, messageA.lpszNoteText); HeapFree(GetProcessHeap(), 0, messageA.lpszDateReceived); HeapFree(GetProcessHeap(), 0, messageA.lpszConversationID); return ret; } /* Display an error message since we apparently have no mail clients */ LoadStringW(hInstMAPI32, IDS_NO_MAPI_CLIENT, error_msg, sizeof(error_msg) / sizeof(WCHAR)); LoadStringW(hInstMAPI32, IDS_SEND_MAIL, msg_title, sizeof(msg_title) / sizeof(WCHAR)); MessageBoxW((HWND) uiparam, error_msg, msg_title, MB_ICONEXCLAMATION); return MAPI_E_NOT_SUPPORTED; }
static ULONG UserpMessageBox( PWSTR Text, PWSTR Caption, ULONG ValidResponseOptions, ULONG Severity) { ULONG Type, MessageBoxResponse; /* Set the message box type */ switch (ValidResponseOptions) { case OptionAbortRetryIgnore: Type = MB_ABORTRETRYIGNORE; break; case OptionOk: Type = MB_OK; break; case OptionOkCancel: Type = MB_OKCANCEL; break; case OptionRetryCancel: Type = MB_RETRYCANCEL; break; case OptionYesNo: Type = MB_YESNO; break; case OptionYesNoCancel: Type = MB_YESNOCANCEL; break; case OptionShutdownSystem: Type = MB_RETRYCANCEL; // FIXME??? break; /* Anything else is invalid */ default: return ResponseNotHandled; } /* Set severity */ if (Severity == STATUS_SEVERITY_INFORMATIONAL) Type |= MB_ICONINFORMATION; else if (Severity == STATUS_SEVERITY_WARNING) Type |= MB_ICONWARNING; else if (Severity == STATUS_SEVERITY_ERROR) Type |= MB_ICONERROR; Type |= MB_SYSTEMMODAL | MB_SETFOREGROUND; DPRINT("Text = '%S', Caption = '%S', Severity = %d, Type = 0x%lx\n", Text, Caption, Severity, Type); /* Display a message box */ MessageBoxResponse = MessageBoxW(0, Text, Caption, Type); /* Return response value */ switch (MessageBoxResponse) { case IDOK: return ResponseOk; case IDCANCEL: return ResponseCancel; case IDYES: return ResponseYes; case IDNO: return ResponseNo; case IDABORT: return ResponseAbort; case IDIGNORE: return ResponseIgnore; case IDRETRY: return ResponseRetry; case IDTRYAGAIN: return ResponseTryAgain; case IDCONTINUE: return ResponseContinue; } return ResponseNotHandled; }
void readMesh(IOReadBase* pRead, iModelData* pModelData) { bool skeletallyAnimated; pRead->Read(&skeletallyAnimated,sizeof(bool)); // Find all substreams if (!pRead->IsEof()) { CSubMesh sharedSubMesh; unsigned short streamID; unsigned int uLength; pRead->Read(&streamID,sizeof(unsigned short)); pRead->Read(&uLength,sizeof(unsigned int)); while(!pRead->IsEof() && (streamID == M_GEOMETRY || streamID == M_SUBMESH || streamID == M_MESH_SKELETON_LINK || streamID == M_MESH_BONE_ASSIGNMENT || streamID == M_MESH_LOD || streamID == M_MESH_BOUNDS || streamID == M_SUBMESH_NAME_TABLE || streamID == M_EDGE_LISTS || streamID == M_POSES || streamID == M_ANIMATIONS || streamID == M_TABLE_EXTREMES)) { switch(streamID) { case M_GEOMETRY: { //MessageBoxW(NULL, L"M_GEOMETRY", L"readMesh",0); readGeometry(pRead, sharedSubMesh); } break; case M_SUBMESH: readSubMesh(pRead, pModelData, sharedSubMesh); break; case M_MESH_SKELETON_LINK: { std::string skelName = readString(pRead); // if(listener) // listener->processSkeletonName(pMesh, &skelName); // // pMesh->setSkeletonName(skelName); //readSkeletonLink(stream, pMesh, listener); } break; case M_MESH_BONE_ASSIGNMENT: //readMeshBoneAssignment(stream, pMesh); { VertexBoneAssignment assign; // unsigned int vertexIndex; pRead->Read(&(assign.vertexIndex),sizeof(unsigned int)); // unsigned short boneIndex; pRead->Read(&(assign.boneIndex),sizeof(unsigned short)); // float weight; pRead->Read(&(assign.weight),sizeof(float)); //sub->addBoneAssignment(assign); } break; case M_MESH_LOD: MessageBoxW(NULL,L"M_MESH_LOD",0,0); //readMeshLodInfo(stream, pMesh); break; case M_MESH_BOUNDS: //readBoundsInfo(stream, pMesh); { Vec3D min, max; // float minx, miny, minz pRead->Read(&min,sizeof(Vec3D)); // float maxx, maxy, maxz pRead->Read(&max,sizeof(Vec3D)); //AxisAlignedBox box(min, max); //pMesh->_setBounds(box, true); // float radius float radius; pRead->Read(&radius,sizeof(float)); //pMesh->_setBoundingSphereRadius(radius); } break; case M_SUBMESH_NAME_TABLE: MessageBoxW(NULL,L"M_SUBMESH_NAME_TABLE",0,0); //readSubMeshNameTable(stream, pMesh); break; case M_EDGE_LISTS: MessageBoxW(NULL,L"M_EDGE_LISTS",0,0); //readEdgeList(stream, pMesh); break; case M_POSES: MessageBoxW(NULL,L"M_POSES",0,0); //readPoses(stream, pMesh); break; case M_ANIMATIONS: MessageBoxW(NULL,L"M_ANIMATIONS",0,0); //readAnimations(stream, pMesh); break; case M_TABLE_EXTREMES: MessageBoxW(NULL,L"M_TABLE_EXTREMES",0,0); //readExtremes(stream, pMesh); break; } if (!pRead->IsEof()) { pRead->Read(&streamID,sizeof(unsigned short)); pRead->Read(&uLength,sizeof(unsigned int)); } } if (!pRead->IsEof()) { // Backpedal back to start of non-submesh stream pRead->Move(-STREAM_OVERHEAD_SIZE); } } }
////////////////////////////////////////////////////////////////////////// // CImpIDispatch bool CallCpp(LPCWSTR pszParam) { return MessageBoxW(GetActiveWindow(),pszParam,L"jscall",MB_OKCANCEL)==IDOK?true:false; }
void readGeometryVertexBuffer(IOReadBase* pRead, CSubMesh& subMesh,std::vector<GeometryVertexElement>& setElement,unsigned int vertexCount) { unsigned short bindIndex, vertexSize; // unsigned short bindIndex; // Index to bind this buffer to pRead->Read(&bindIndex,sizeof(unsigned short)); // unsigned short vertexSize; // Per-vertex size, must agree with declaration at this index pRead->Read(&vertexSize,sizeof(unsigned short)); // Check for vertex data header unsigned short streamID; unsigned int uLength; pRead->Read(&streamID,sizeof(unsigned short)); pRead->Read(&uLength,sizeof(unsigned int)); if (streamID != M_GEOMETRY_VERTEX_BUFFER_DATA) { MessageBoxW(NULL, L"Can't find vertex buffer data area", L"MeshSerializerImpl::readGeometryVertexBuffer",0); } for (size_t i=0;i<vertexCount;++i) { for (size_t n=0;n<setElement.size();++n) { if (setElement[n].source==bindIndex) { switch(setElement[n].vSemantic) { case VES_POSITION: { Vec3D vPos; pRead->Read(&vPos,sizeof(Vec3D)); vPos.x=-vPos.x; subMesh.addPos(vPos); } break; case VES_BLEND_WEIGHTS: { unsigned int uWeight; pRead->Read(&uWeight,sizeof(unsigned int)); subMesh.addWeight(uWeight); } break; case VES_BLEND_INDICES: { unsigned int uBone; pRead->Read(&uBone,sizeof(unsigned int)); subMesh.addBone(uBone); } break; case VES_NORMAL: { Vec3D vNormal; pRead->Read(&vNormal,sizeof(Vec3D)); vNormal.x=-vNormal.x; subMesh.addNormal(vNormal); } break; case VES_DIFFUSE: { Color32 color; pRead->Read(&color,sizeof(Color32)); subMesh.addColor(color); } break; case VES_SPECULAR: { Color32 color; pRead->Read(&color,sizeof(Color32)); //subMesh.addColor(color); } break; case VES_TEXTURE_COORDINATES: { Vec2D vUV; pRead->Read(&vUV,sizeof(Vec2D)); subMesh.addTexcoord(vUV); } break; case VES_BINORMAL: { Vec3D vBiNormal; pRead->Read(&vBiNormal,sizeof(Vec3D)); //pMesh->addBiNormal(vBiNormal); } break; case VES_TANGENT: { Vec3D vTangent; pRead->Read(&vTangent,sizeof(Vec3D)); //pMesh->addTangent(vTangent); } break; default: break; } } } } //pRead->read(pBuf, dest->vertexCount * vertexSize); }
VOID OnCommand(WPARAM wParam, LPARAM lParam) { WORD wCommand = LOWORD(wParam); if (lParam == (LPARAM) m_SearchBar->m_hWnd) { WCHAR szBuf[MAX_STR_LEN]; switch (HIWORD(wParam)) { case EN_SETFOCUS: { WCHAR szWndText[MAX_STR_LEN]; LoadStringW(hInst, IDS_SEARCH_TEXT, szBuf, _countof(szBuf)); m_SearchBar->GetWindowTextW(szWndText, MAX_STR_LEN); if (wcscmp(szBuf, szWndText) == 0) { SearchEnabled = FALSE; m_SearchBar->SetWindowTextW(L""); } } break; case EN_KILLFOCUS: { m_SearchBar->GetWindowTextW(szBuf, MAX_STR_LEN); if (wcslen(szBuf) < 1) { LoadStringW(hInst, IDS_SEARCH_TEXT, szBuf, _countof(szBuf)); SearchEnabled = FALSE; m_SearchBar->SetWindowTextW(szBuf); } } break; case EN_CHANGE: { WCHAR szWndText[MAX_STR_LEN]; if (!SearchEnabled) { SearchEnabled = TRUE; break; } LoadStringW(hInst, IDS_SEARCH_TEXT, szBuf, _countof(szBuf)); m_SearchBar->GetWindowTextW(szWndText, MAX_STR_LEN); if (wcscmp(szBuf, szWndText) != 0) { StringCbCopy(szSearchPattern, sizeof(szSearchPattern), szWndText); } else { szSearchPattern[0] = UNICODE_NULL; } DWORD dwDelay; SystemParametersInfo(SPI_GETMENUSHOWDELAY, 0, &dwDelay, 0); SetTimer(SEARCH_TIMER_ID, dwDelay); } break; } return; } switch (wCommand) { case ID_OPEN_LINK: ShellExecuteW(m_hWnd, L"open", pLink, NULL, NULL, SW_SHOWNOACTIVATE); HeapFree(GetProcessHeap(), 0, pLink); break; case ID_COPY_LINK: CopyTextToClipboard(pLink); HeapFree(GetProcessHeap(), 0, pLink); break; case ID_SETTINGS: CreateSettingsDlg(m_hWnd); break; case ID_EXIT: PostMessageW(WM_CLOSE, 0, 0); break; case ID_INSTALL: if (DownloadApplication(-1)) /* TODO: Implement install dialog * if (InstallApplication(-1)) */ UpdateApplicationsList(-1); break; case ID_UNINSTALL: if (UninstallApplication(-1, FALSE)) UpdateApplicationsList(-1); break; case ID_MODIFY: if (UninstallApplication(-1, TRUE)) UpdateApplicationsList(-1); break; case ID_REGREMOVE: RemoveAppFromRegistry(-1); break; case ID_REFRESH: UpdateApplicationsList(-1); break; case ID_RESETDB: UpdateAppsDB(); UpdateApplicationsList(-1); break; case ID_HELP: MessageBoxW(L"Help not implemented yet", NULL, MB_OK); break; case ID_ABOUT: ShowAboutDialog(); break; } }
void readSubMesh(IOReadBase* pRead, iModelData* pModelData, const CSubMesh& sharedSubMesh) { iLodMesh* pMesh = &pModelData->getMesh(); std::string strMaterialName = readString(pRead); int nSubID=pMesh->getSubCount(); pModelData->setRenderPass(nSubID,nSubID,strMaterialName); // if(listener) // listener->processMaterialName(pMesh, &materialName); // sm->setMaterialName(materialName); // bool useSharedVertices bool useSharedVertices; pRead->Read(&useSharedVertices,sizeof(bool)); CSubMesh& subMesh=pMesh->addSubMesh(); if (useSharedVertices) { subMesh.pos =sharedSubMesh.pos; subMesh.weight =sharedSubMesh.weight; subMesh.bone =sharedSubMesh.bone; subMesh.normal =sharedSubMesh.normal; subMesh.color =sharedSubMesh.color; subMesh.texcoord =sharedSubMesh.texcoord; subMesh.texcoord2 =sharedSubMesh.texcoord2; } // sm->indexData->indexStart = 0; unsigned int indexCount = 0; pRead->Read(&indexCount,sizeof(unsigned int)); //sm->indexData->indexCount = indexCount; // bool indexes32Bit bool idx32bit; pRead->Read(&idx32bit,sizeof(bool)); if (idx32bit) { MessageBoxW(0,L"Can't read idx32bit",L"Error",0); VertexIndex vertexIndex; for (size_t i=0;i<indexCount;++i) { unsigned int uVertexIndex; pRead->Read(&uVertexIndex,sizeof(unsigned int)); vertexIndex.p=uVertexIndex; vertexIndex.n=uVertexIndex; vertexIndex.c=uVertexIndex; vertexIndex.uv1=uVertexIndex; vertexIndex.b=uVertexIndex; vertexIndex.w=uVertexIndex; subMesh.m_setVertexIndex.push_back(vertexIndex); } } else // 16-bit { VertexIndex vertexIndex; for (size_t i=0;i<indexCount;++i) { unsigned short uVertexIndex; pRead->Read(&uVertexIndex,sizeof(unsigned short)); vertexIndex.p=uVertexIndex; vertexIndex.n=uVertexIndex; vertexIndex.c=uVertexIndex; vertexIndex.uv1=uVertexIndex; vertexIndex.b=uVertexIndex; vertexIndex.w=uVertexIndex; subMesh.m_setVertexIndex.push_back(vertexIndex); } } // M_GEOMETRY stream (Optional: present only if useSharedVertices = false) if (!useSharedVertices) { unsigned short streamID; unsigned int uLength; pRead->Read(&streamID,sizeof(unsigned short)); pRead->Read(&uLength,sizeof(unsigned int)); if (streamID != M_GEOMETRY) { MessageBoxW(0,L"Missing geometry data in mesh file",L"readSubMesh",0); } readGeometry(pRead, subMesh); } // Find all bone assignments, submesh operation, and texture aliases (if present) if (!pRead->IsEof()) { unsigned short streamID; unsigned int uLength; pRead->Read(&streamID,sizeof(unsigned short)); pRead->Read(&uLength,sizeof(unsigned int)); while(!pRead->IsEof() && (streamID == M_SUBMESH_BONE_ASSIGNMENT || streamID == M_SUBMESH_OPERATION || streamID == M_SUBMESH_TEXTURE_ALIAS)) { switch(streamID) { case M_SUBMESH_OPERATION: // readSubMeshOperation(stream, pMesh, sm); // unsigned short operationType unsigned short opType; pRead->Read(&opType,sizeof(unsigned short)); //sm->operationType = static_cast<RenderOperation::OperationType>(opType); break; case M_SUBMESH_BONE_ASSIGNMENT: { //readSubMeshBoneAssignment(stream, pMesh, sm); VertexBoneAssignment assign; // unsigned int vertexIndex; pRead->Read(&(assign.vertexIndex),sizeof(unsigned int)); // unsigned short boneIndex; pRead->Read(&(assign.boneIndex),sizeof(unsigned short)); // float weight; pRead->Read(&(assign.weight),sizeof(float)); break; unsigned long uBone = 0; unsigned long uWeight = 0; // get subMesh.getBone(assign.vertexIndex,uBone); subMesh.getWeight(assign.vertexIndex,uWeight); // add for (size_t i=0;i<4;++i) { if (((unsigned char*)&uWeight)[i]==0) { ((unsigned char*)&uWeight)[i] = assign.weight*255; ((unsigned char*)&uBone)[i] = assign.boneIndex; break; } } // set subMesh.setBone(assign.vertexIndex,uBone); subMesh.setWeight(assign.vertexIndex,uWeight); //sub->addBoneAssignment(assign); } break; case M_SUBMESH_TEXTURE_ALIAS: //readSubMeshTextureAlias(stream, pMesh, sm); std::string aliasName = readString(pRead); std::string textureName = readString(pRead); //sub->addTextureAlias(aliasName, textureName); break; } if (!pRead->IsEof()) { pRead->Read(&streamID,sizeof(unsigned short)); pRead->Read(&uLength,sizeof(unsigned int)); } } if (!pRead->IsEof()) { // Backpedal back to start of non-submesh stream pRead->Move(-STREAM_OVERHEAD_SIZE); } } }
Win32CallstackResolver::Win32CallstackResolver(char *moduleDB, size_t DBSize, string pdbSearchPaths, volatile bool *killSignal) { wstring configPath = StringFormat::UTF82Wide(FileIO::GetAppFolderFilename("config.ini")); { FILE *f = NULL; _wfopen_s(&f, configPath.c_str(), L"a"); if(f) fclose(f); } DWORD sz = 2048; wchar_t *inputBuf = new wchar_t[sz]; for(;;) { DWORD read = GetPrivateProfileStringW(L"renderdoc", L"ignores", NULL, inputBuf, sz, configPath.c_str()); if(read == sz - 1) { sz *= 2; delete[] inputBuf; inputBuf = new wchar_t[sz]; continue; } break; } wstring ignores = inputBuf; delete[] inputBuf; split(ignores, pdbIgnores, L';'); wstring widepdbsearch = StringFormat::UTF82Wide(pdbSearchPaths); split(widepdbsearch, pdbRememberedPaths, L';'); pdblocateProcess = NULL; pdblocatePipe = NULL; OpenPdblocateHandle(); if(memcmp(moduleDB, "WN32CALL", 8)) { RDCWARN("Can't load callstack resolve for this log. Possibly from another platform?"); return; } char *chunks = moduleDB + 8; char *end = chunks + DBSize - 8; EnumModChunk *chunk = (EnumModChunk *)(chunks); WCHAR *modName = (WCHAR *)(chunks + sizeof(EnumModChunk)); if(pdblocatePipe == NULL) return; // loop over all our modules for(; chunks < end; chunks += sizeof(EnumModChunk) + (chunk->imageNameLen) * sizeof(WCHAR)) { chunk = (EnumModChunk *)chunks; modName = (WCHAR *)(chunks + sizeof(EnumModChunk)); if(killSignal && *killSignal) break; Module m; m.name = modName; m.base = chunk->base; m.size = chunk->size; m.moduleId = 0; if(find(pdbIgnores.begin(), pdbIgnores.end(), m.name) != pdbIgnores.end()) { RDCWARN("Not attempting to get symbols for %ls", m.name.c_str()); modules.push_back(m); continue; } // get default pdb (this also looks up symbol server etc) // relies on pdblocate. Always done in unicode std::wstring defaultPdb = LookupModule(modName, chunk->guid, chunk->age); // strip newline if(defaultPdb != L"" && defaultPdb[defaultPdb.length() - 1] == '\n') defaultPdb.pop_back(); // if we didn't even get a default pdb we'll have to prompt first time through bool failed = false; if(defaultPdb == L"") { defaultPdb = strlower(basename(m.name)); size_t it = defaultPdb.find(L".dll"); if(it != wstring::npos) { defaultPdb[it + 1] = L'p'; defaultPdb[it + 2] = L'd'; defaultPdb[it + 3] = L'b'; } it = defaultPdb.find(L".exe"); if(it != wstring::npos) { defaultPdb[it + 1] = L'p'; defaultPdb[it + 2] = L'd'; defaultPdb[it + 3] = L'b'; } failed = true; } std::wstring pdbName = defaultPdb; int fallbackIdx = -1; while(m.moduleId == 0) { if(failed) { fallbackIdx++; // try one of the folders we've been given, just in case the symbols // are there if(fallbackIdx < (int)pdbRememberedPaths.size()) { pdbName = pdbRememberedPaths[fallbackIdx] + L"\\" + basename(pdbName); } else { pdbName = dirname(defaultPdb) + L"\\" + basename(defaultPdb); // prompt for new pdbName, unless it's renderdoc or dbghelp if(pdbName.find(L"renderdoc.") != wstring::npos || pdbName.find(L"dbghelp.") != wstring::npos || pdbName.find(L"symsrv.") != wstring::npos) pdbName = L""; else pdbName = pdbBrowse(pdbName); // user cancelled, just don't load this pdb if(pdbName == L"") break; } failed = false; } m.moduleId = GetModuleID(pdbName, chunk->guid, chunk->age); if(m.moduleId == 0) { failed = true; } else { if(fallbackIdx >= (int)pdbRememberedPaths.size()) { wstring dir = dirname(pdbName); if(find(pdbRememberedPaths.begin(), pdbRememberedPaths.end(), dir) == pdbRememberedPaths.end()) { pdbRememberedPaths.push_back(dir); } } } } // didn't load the pdb? go to the next module. if(m.moduleId == 0) { modules.push_back(m); // still add the module, with 0 module id RDCWARN("Couldn't get symbols for %ls", m.name.c_str()); // silently ignore renderdoc.dll and dbghelp.dll without asking to permanently ignore if(m.name.find(L"renderdoc") != wstring::npos || m.name.find(L"dbghelp") != wstring::npos) continue; wchar_t text[1024]; wsprintf(text, L"Do you want to permanently ignore this file?\nPath: %ls", m.name.c_str()); int ret = MessageBoxW(NULL, text, L"Ignore this pdb?", MB_YESNO); if(ret == IDYES) pdbIgnores.push_back(m.name); continue; } SetModuleBaseAddress(m.moduleId, chunk->base); RDCLOG("Loaded Symbols for %ls", m.name.c_str()); modules.push_back(m); } sort(pdbIgnores.begin(), pdbIgnores.end()); pdbIgnores.erase(unique(pdbIgnores.begin(), pdbIgnores.end()), pdbIgnores.end()); merge(pdbIgnores, ignores, L';'); WritePrivateProfileStringW(L"renderdoc", L"ignores", ignores.c_str(), configPath.c_str()); }
static VOID MainWndCommand(PMAIN_WND_INFO Info, WORD CmdId, HWND hControl) { UNREFERENCED_PARAMETER(hControl); switch (CmdId) { case ID_PROP: { if (Info->SelectedItem != NO_ITEM_SELECTED) { Info->bDlgOpen = TRUE; OpenPropSheet(Info); Info->bDlgOpen = FALSE; SetMenuAndButtonStates(Info); } } break; case ID_REFRESH: { RefreshServiceList(Info); Info->SelectedItem = NO_ITEM_SELECTED; /* disable menus and buttons */ SetMenuAndButtonStates(Info); /* clear the service in the status bar */ SendMessage(Info->hStatus, SB_SETTEXT, 1, L'\0'); } break; case ID_EXPORT: { ExportFile(Info); SetFocus(Info->hListView); } break; case ID_CREATE: { INT ret; ret = DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_DLG_CREATE), Info->hMainWnd, CreateDialogProc, (LPARAM)Info); if (ret == IDOK) RefreshServiceList(Info); SetFocus(Info->hListView); } break; case ID_DELETE: { if (Info->pCurrentService->ServiceStatusProcess.dwCurrentState != SERVICE_RUNNING) { DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_DLG_DELETE), Info->hMainWnd, DeleteDialogProc, (LPARAM)Info); } else { WCHAR Buf[60]; LoadString(hInstance, IDS_DELETE_STOP, Buf, sizeof(Buf) / sizeof(WCHAR)); DisplayString(Buf); } SetFocus(Info->hListView); } break; case ID_START: { RunActionWithProgress(Info->hMainWnd, Info->pCurrentService->lpServiceName, Info->pCurrentService->lpDisplayName, ACTION_START, NULL); //FIXME: Add start params UpdateServiceStatus(Info->pCurrentService); ChangeListViewText(Info, Info->pCurrentService, LVSTATUS); SetMenuAndButtonStates(Info); SetFocus(Info->hListView); } break; case ID_STOP: RunActionWithProgress(Info->hMainWnd, Info->pCurrentService->lpServiceName, Info->pCurrentService->lpDisplayName, ACTION_STOP, NULL); UpdateServiceStatus(Info->pCurrentService); ChangeListViewText(Info, Info->pCurrentService, LVSTATUS); SetMenuAndButtonStates(Info); SetFocus(Info->hListView); break; case ID_PAUSE: RunActionWithProgress(Info->hMainWnd, Info->pCurrentService->lpServiceName, Info->pCurrentService->lpDisplayName, ACTION_PAUSE, NULL); UpdateServiceStatus(Info->pCurrentService); ChangeListViewText(Info, Info->pCurrentService, LVSTATUS); SetMenuAndButtonStates(Info); SetFocus(Info->hListView); break; case ID_RESUME: RunActionWithProgress(Info->hMainWnd, Info->pCurrentService->lpServiceName, Info->pCurrentService->lpDisplayName, ACTION_RESUME, NULL); UpdateServiceStatus(Info->pCurrentService); ChangeListViewText(Info, Info->pCurrentService, LVSTATUS); SetMenuAndButtonStates(Info); SetFocus(Info->hListView); break; case ID_RESTART: RunActionWithProgress(Info->hMainWnd, Info->pCurrentService->lpServiceName, Info->pCurrentService->lpDisplayName, ACTION_RESTART, NULL); UpdateServiceStatus(Info->pCurrentService); ChangeListViewText(Info, Info->pCurrentService, LVSTATUS); SetMenuAndButtonStates(Info); SetFocus(Info->hListView); break; case ID_HELP: MessageBoxW(NULL, L"Help is not yet implemented\n", L"Note!", MB_OK | MB_ICONINFORMATION); SetFocus(Info->hListView); break; case ID_EXIT: PostMessage(Info->hMainWnd, WM_CLOSE, 0, 0); break; case ID_VIEW_LARGE: SetListViewStyle(Info->hListView, LVS_ICON); ListView_Arrange(Info->hListView, LVA_DEFAULT); CheckMenuRadioItem(GetMenu(Info->hMainWnd), ID_VIEW_LARGE, ID_VIEW_DETAILS, ID_VIEW_LARGE, MF_BYCOMMAND); break; case ID_VIEW_SMALL: SetListViewStyle(Info->hListView, LVS_SMALLICON); ListView_Arrange(Info->hListView, LVA_DEFAULT); CheckMenuRadioItem(GetMenu(Info->hMainWnd), ID_VIEW_LARGE, ID_VIEW_DETAILS, ID_VIEW_SMALL, MF_BYCOMMAND); break; case ID_VIEW_LIST: SetListViewStyle(Info->hListView, LVS_LIST); CheckMenuRadioItem(GetMenu(Info->hMainWnd), ID_VIEW_LARGE, ID_VIEW_DETAILS, ID_VIEW_LIST, MF_BYCOMMAND); break; case ID_VIEW_DETAILS: SetListViewStyle(Info->hListView, LVS_REPORT); CheckMenuRadioItem(GetMenu(Info->hMainWnd), ID_VIEW_LARGE, ID_VIEW_DETAILS, ID_VIEW_DETAILS, MF_BYCOMMAND); break; case ID_VIEW_CUST: break; case ID_ABOUT: DialogBox(hInstance, MAKEINTRESOURCE(IDD_ABOUTBOX), Info->hMainWnd, AboutDialogProc); SetFocus(Info->hListView); break; } }
// Entry point where control comes on an unhandled exception static LONG WINAPI TopLevelExceptionFilter(PEXCEPTION_POINTERS pExceptionInfo) { static bool bBeenHere = FALSE; if(!bBeenHere) { UINT fuOldErrorMode; bBeenHere = TRUE; fuOldErrorMode = SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX); hReportFile = CreateFileW( szLogFileName, GENERIC_WRITE, 0, 0, OPEN_ALWAYS, FILE_FLAG_WRITE_THROUGH, 0 ); if (hReportFile == INVALID_HANDLE_VALUE) { // Retrieve the system error message for the last-error code LPVOID lpMsgBuf; DWORD dw = GetLastError(); TCHAR szBuffer[4196]; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, NULL ); wsprintf(szBuffer, _T("Exception handler failed with error %d: %s\n"), dw, lpMsgBuf); MessageBox((HWND)MB_ICONEXCLAMATION, szBuffer, _T("Error"), MB_OK); LocalFree(lpMsgBuf); debug(LOG_ERROR, "Exception handler failed to create file!"); } #ifdef HAVE_BFD bfd_set_error_handler((bfd_error_handler_type) rprintf); #endif /* HAVE_BFD */ if (hReportFile) { wchar_t szBuffer[4196]; int err; SetFilePointer(hReportFile, 0, 0, FILE_END); // FIXME: We don't return from the below function call GenerateExceptionReport(pExceptionInfo); CloseHandle(hReportFile); wsprintfW(szBuffer, L"Warzone has crashed.\r\nSee %s for more details\r\n", szLogFileName); err = MessageBoxW((HWND)MB_ICONERROR, szBuffer, L"Warzone Crashed!", MB_OK | MB_ICONERROR); if (err == 0) { LPVOID lpMsgBuf; DWORD dw = GetLastError(); wchar_t szBuffer[4196]; FormatMessageW( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR) &lpMsgBuf, 0, NULL ); wsprintfW(szBuffer, L"Exception handler failed with error %d: %s\n", dw, lpMsgBuf); MessageBoxW((HWND)MB_ICONEXCLAMATION, szBuffer, L"Error", MB_OK); LocalFree(lpMsgBuf); debug(LOG_ERROR, "Exception handler failed to create file!"); } hReportFile = 0; } SetErrorMode(fuOldErrorMode); } if(prevExceptionFilter) return prevExceptionFilter(pExceptionInfo); else return EXCEPTION_CONTINUE_SEARCH; }
HRESULT CNewMenu::CreateNewItem(SHELLNEW_ITEM *pItem, LPCMINVOKECOMMANDINFO lpcmi) { WCHAR wszBuf[MAX_PATH]; WCHAR wszPath[MAX_PATH]; HRESULT hr; /* Get folder path */ hr = SHGetPathFromIDListW(m_pidlFolder, wszPath); if (FAILED_UNEXPECTEDLY(hr)) return hr; switch (pItem->Type) { case SHELLNEW_TYPE_COMMAND: { LPWSTR Ptr, pwszCmd; WCHAR wszTemp[MAX_PATH]; STARTUPINFOW si; PROCESS_INFORMATION pi; if (!ExpandEnvironmentStringsW((LPWSTR)pItem->pData, wszBuf, MAX_PATH)) { TRACE("ExpandEnvironmentStrings failed\n"); break; } /* Expand command parameter, FIXME: there can be more modifiers */ Ptr = wcsstr(wszBuf, L"%1"); if (Ptr) { Ptr[1] = 's'; StringCbPrintfW(wszTemp, sizeof(wszTemp), wszBuf, wszPath); pwszCmd = wszTemp; } else pwszCmd = wszBuf; /* Create process */ ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); if (CreateProcessW(NULL, pwszCmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) { CloseHandle(pi.hProcess); CloseHandle(pi.hThread); } else ERR("Failed to create process\n"); break; } case SHELLNEW_TYPE_DATA: case SHELLNEW_TYPE_FILENAME: case SHELLNEW_TYPE_NULLFILE: { BOOL bSuccess = TRUE; LPWSTR pwszFilename = NULL; size_t cchFilenameMax = 0; /* Build new file name */ LoadStringW(shell32_hInstance, FCIDM_SHVIEW_NEW, wszBuf, _countof(wszBuf)); StringCchCatExW(wszPath, _countof(wszPath), L"\\", &pwszFilename, &cchFilenameMax, 0); StringCchPrintfW(pwszFilename, cchFilenameMax, L"%s %s%s", wszBuf, pItem->pwszDesc, pItem->pwszExt); /* Find unique name */ for (UINT i = 2; PathFileExistsW(wszPath); ++i) { StringCchPrintfW(pwszFilename, cchFilenameMax, L"%s %s (%u)%s", wszBuf, pItem->pwszDesc, i, pItem->pwszExt); TRACE("New Filename %ls\n", pwszFilename); } /* Create new file */ HANDLE hFile = CreateFileW(wszPath, GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile != INVALID_HANDLE_VALUE) { if (pItem->Type == SHELLNEW_TYPE_DATA) { /* Write a content */ DWORD cbWritten; WriteFile(hFile, pItem->pData, pItem->cbData, &cbWritten, NULL); } /* Close file now */ CloseHandle(hFile); } else bSuccess = FALSE; if (pItem->Type == SHELLNEW_TYPE_FILENAME) { /* Copy file */ if (!CopyFileW((LPWSTR)pItem->pData, wszPath, FALSE)) ERR("Copy file failed: %ls\n", (LPWSTR)pItem->pData); } /* Show message if we failed */ if (bSuccess) { TRACE("Notifying fs %s\n", debugstr_w(wszPath)); SelectNewItem(lpcmi, SHCNE_CREATE, SHCNF_PATHW, wszPath); } else { StringCbPrintfW(wszBuf, sizeof(wszBuf), L"Cannot create file: %s", pwszFilename); MessageBoxW(NULL, wszBuf, L"Cannot create file", MB_OK|MB_ICONERROR); // FIXME } break; } case SHELLNEW_TYPE_INVALID: ERR("Invalid type\n"); break; } return S_OK; }