DWORD CALLBACK AboutIniBoxProc(HWND hDlg, DWORD uMsg, DWORD wParam, DWORD /*lParam*/) { static wchar_t RDBHomePage[300], CHTHomePage[300], RDXHomePage[300]; switch (uMsg) { case WM_INITDIALOG: { wchar_t String[200]; //Title SetWindowTextW(hDlg, wGS(INI_TITLE).c_str()); //Language SetDlgItemTextW(hDlg, IDC_LAN, wGS(INI_CURRENT_LANG).c_str()); set_about_field(hDlg, IDC_LAN_AUTHOR, wGS(INI_AUTHOR).c_str(), wGS(LANGUAGE_AUTHOR).c_str()); set_about_field(hDlg, IDC_LAN_VERSION, wGS(INI_VERSION).c_str(), wGS(LANGUAGE_VERSION).c_str()); set_about_field(hDlg, IDC_LAN_DATE, wGS(INI_DATE).c_str(), wGS(LANGUAGE_DATE).c_str()); if (wcslen(wGS(LANGUAGE_NAME).c_str()) == 0) { EnableWindow(GetDlgItem(hDlg, IDC_LAN), FALSE); EnableWindow(GetDlgItem(hDlg, IDC_LAN_AUTHOR), FALSE); EnableWindow(GetDlgItem(hDlg, IDC_LAN_VERSION), FALSE); EnableWindow(GetDlgItem(hDlg, IDC_LAN_DATE), FALSE); } //RDB CIniFile RdbIniFile(g_Settings->LoadStringVal(SupportFile_RomDatabase).c_str()); wcsncpy(String, RdbIniFile.GetString("Meta", "Author", "").ToUTF16().c_str(), sizeof(String) / sizeof(String[0])); if (wcslen(String) == 0) { EnableWindow(GetDlgItem(hDlg, IDC_RDB), FALSE); EnableWindow(GetDlgItem(hDlg, IDC_RDB_AUTHOR), FALSE); EnableWindow(GetDlgItem(hDlg, IDC_RDB_VERSION), FALSE); EnableWindow(GetDlgItem(hDlg, IDC_RDB_DATE), FALSE); EnableWindow(GetDlgItem(hDlg, IDC_RDB_HOME), FALSE); } set_about_field(hDlg, IDC_RDB_AUTHOR, wGS(INI_AUTHOR).c_str(), String); wcsncpy(String, RdbIniFile.GetString("Meta", "Version", "").ToUTF16().c_str(), sizeof(String) / sizeof(String[0])); set_about_field(hDlg, IDC_RDB_VERSION, wGS(INI_VERSION).c_str(), String); wcsncpy(String, RdbIniFile.GetString("Meta", "Date", "").ToUTF16().c_str(), sizeof(String) / sizeof(String[0])); set_about_field(hDlg, IDC_RDB_DATE, wGS(INI_DATE).c_str(), String); wcsncpy(RDBHomePage, RdbIniFile.GetString("Meta", "Homepage", "").ToUTF16().c_str(), sizeof(RDBHomePage) / sizeof(RDBHomePage[0])); SetDlgItemTextW(hDlg, IDC_RDB_HOME, wGS(INI_HOMEPAGE).c_str()); if (wcslen(RDBHomePage) == 0) { EnableWindow(GetDlgItem(hDlg, IDC_RDB_HOME), FALSE); } //Cheat SetDlgItemTextW(hDlg, IDC_CHT, wGS(INI_CURRENT_CHT).c_str()); CIniFile CheatIniFile(g_Settings->LoadStringVal(SupportFile_Cheats).c_str()); wcsncpy(String, CheatIniFile.GetString("Meta", "Author", "").ToUTF16().c_str(), sizeof(String) / sizeof(String[0])); if (wcslen(String) == 0) { EnableWindow(GetDlgItem(hDlg, IDC_CHT), FALSE); EnableWindow(GetDlgItem(hDlg, IDC_CHT_AUTHOR), FALSE); EnableWindow(GetDlgItem(hDlg, IDC_CHT_VERSION), FALSE); EnableWindow(GetDlgItem(hDlg, IDC_CHT_DATE), FALSE); EnableWindow(GetDlgItem(hDlg, IDC_CHT_HOME), FALSE); } set_about_field(hDlg, IDC_CHT_AUTHOR, wGS(INI_AUTHOR).c_str(), String); wcsncpy(String, CheatIniFile.GetString("Meta", "Version", "").ToUTF16().c_str(), sizeof(String) / sizeof(String[0])); set_about_field(hDlg, IDC_CHT_VERSION, wGS(INI_VERSION).c_str(), String); wcsncpy(String, CheatIniFile.GetString("Meta", "Date", "").ToUTF16().c_str(), sizeof(String) / sizeof(String[0])); set_about_field(hDlg, IDC_CHT_DATE, wGS(INI_DATE).c_str(), String); wcsncpy(CHTHomePage, CheatIniFile.GetString("Meta", "Homepage", "").ToUTF16().c_str(), sizeof(CHTHomePage) / sizeof(CHTHomePage[0])); SetDlgItemTextW(hDlg, IDC_CHT_HOME, wGS(INI_HOMEPAGE).c_str()); if (wcslen(CHTHomePage) == 0) { EnableWindow(GetDlgItem(hDlg, IDC_CHT_HOME), FALSE); } //Extended Info SetDlgItemTextW(hDlg, IDC_RDX, wGS(INI_CURRENT_RDX).c_str()); CIniFile RdxIniFile(g_Settings->LoadStringVal(SupportFile_ExtInfo).c_str()); wcsncpy(String, RdxIniFile.GetString("Meta", "Author", "").ToUTF16().c_str(), sizeof(String) / sizeof(String[0])); if (wcslen(String) == 0) { EnableWindow(GetDlgItem(hDlg, IDC_RDX), FALSE); EnableWindow(GetDlgItem(hDlg, IDC_RDX_AUTHOR), FALSE); EnableWindow(GetDlgItem(hDlg, IDC_RDX_VERSION), FALSE); EnableWindow(GetDlgItem(hDlg, IDC_RDX_DATE), FALSE); EnableWindow(GetDlgItem(hDlg, IDC_RDX_HOME), FALSE); } set_about_field(hDlg, IDC_RDX_AUTHOR, wGS(INI_AUTHOR).c_str(), String); wcsncpy(String, RdxIniFile.GetString("Meta", "Version", "").ToUTF16().c_str(), sizeof(String) / sizeof(String[0])); set_about_field(hDlg, IDC_RDX_VERSION, wGS(INI_VERSION).c_str(), String); wcsncpy(String, RdxIniFile.GetString("Meta", "Date", "").ToUTF16().c_str(), sizeof(String) / sizeof(String[0])); set_about_field(hDlg, IDC_RDX_DATE, wGS(INI_DATE).c_str(), String); wcsncpy(RDXHomePage, RdxIniFile.GetString("Meta", "Homepage", "").ToUTF16().c_str(), sizeof(RDXHomePage) / sizeof(RDXHomePage[0])); SetDlgItemTextW(hDlg, IDC_RDX_HOME, wGS(INI_HOMEPAGE).c_str()); if (wcslen(RDXHomePage) == 0) { EnableWindow(GetDlgItem(hDlg, IDC_RDX_HOME), FALSE); } SetDlgItemTextW(hDlg, IDOK, wGS(CHEAT_OK).c_str()); } break; case WM_COMMAND: switch (LOWORD(wParam)) { case IDC_RDB_HOME: ShellExecuteW(NULL, L"open", RDBHomePage, NULL, NULL, SW_SHOWNORMAL); break; case IDC_CHT_HOME: ShellExecuteW(NULL, L"open", CHTHomePage, NULL, NULL, SW_SHOWNORMAL); break; case IDC_RDX_HOME: ShellExecuteW(NULL, L"open", RDXHomePage, NULL, NULL, SW_SHOWNORMAL); break; case IDOK: case IDCANCEL: EndDialog(hDlg, 0); break; } default: return FALSE; } return TRUE; }
JNIEXPORT jint JNICALL Java_org_eclipse_cdt_utils_spawner_Spawner_exec0 (JNIEnv * env, jobject process, jobjectArray cmdarray, jobjectArray envp, jstring dir, jintArray channels) { HANDLE stdHandles[3]; PROCESS_INFORMATION pi = {0}, *piCopy; STARTUPINFOW si; DWORD flags = 0; const wchar_t * cwd = NULL; LPVOID envBlk = NULL; int ret = 0; int nCmdLineLength= 0; wchar_t * szCmdLine= 0; int nBlkSize = MAX_ENV_SIZE; wchar_t * szEnvBlock = NULL; jsize nCmdTokens = 0; jsize nEnvVars = 0; int i; DWORD pid = GetCurrentProcessId(); int nPos; pProcInfo_t pCurProcInfo; // This needs to be big enough to contain the name of the event used when calling CreateEventW bellow. // It is made of a prefix (7 characters max) plus the value of a pointer that gets output in characters. // This will be bigger in the case of 64 bit. static const int MAX_EVENT_NAME_LENGTH = 50; wchar_t eventBreakName[MAX_EVENT_NAME_LENGTH]; wchar_t eventWaitName[MAX_EVENT_NAME_LENGTH]; wchar_t eventTerminateName[MAX_EVENT_NAME_LENGTH]; wchar_t eventKillName[MAX_EVENT_NAME_LENGTH]; wchar_t eventCtrlcName[MAX_EVENT_NAME_LENGTH]; #ifdef DEBUG_MONITOR wchar_t buffer[4000]; #endif int nLocalCounter; wchar_t inPipeName[PIPE_NAME_LENGTH]; wchar_t outPipeName[PIPE_NAME_LENGTH]; wchar_t errPipeName[PIPE_NAME_LENGTH]; nCmdLineLength= MAX_CMD_SIZE; szCmdLine= (wchar_t *)malloc(nCmdLineLength * sizeof(wchar_t)); szCmdLine[0]= _T('\0'); if((HIBYTE(LOWORD(GetVersion()))) & 0x80) { ThrowByName(env, "java/io/IOException", "Does not support Windows 3.1/95/98/Me"); return 0; } if (cmdarray == 0) { ThrowByName(env, "java/lang/NullPointerException", "No command line specified"); return 0; } ZeroMemory(stdHandles, sizeof(stdHandles)); // Create pipe names EnterCriticalSection(&cs); swprintf(inPipeName, L"\\\\.\\pipe\\stdin%08i%010i", pid, nCounter); swprintf(outPipeName, L"\\\\.\\pipe\\stdout%08i%010i", pid, nCounter); swprintf(errPipeName, L"\\\\.\\pipe\\stderr%08i%010i", pid, nCounter); nLocalCounter = nCounter; ++nCounter; LeaveCriticalSection(&cs); if ((INVALID_HANDLE_VALUE == (stdHandles[0] = CreateNamedPipeW(inPipeName, PIPE_ACCESS_OUTBOUND, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, PIPE_UNLIMITED_INSTANCES, PIPE_SIZE, PIPE_SIZE, PIPE_TIMEOUT, NULL))) || (INVALID_HANDLE_VALUE == (stdHandles[1] = CreateNamedPipeW(outPipeName, PIPE_ACCESS_INBOUND | FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, PIPE_UNLIMITED_INSTANCES, PIPE_SIZE, PIPE_SIZE, PIPE_TIMEOUT, NULL))) || (INVALID_HANDLE_VALUE == (stdHandles[2] = CreateNamedPipeW(errPipeName, PIPE_ACCESS_INBOUND | FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, PIPE_UNLIMITED_INSTANCES, PIPE_SIZE, PIPE_SIZE, PIPE_TIMEOUT, NULL)))) { CloseHandle(stdHandles[0]); CloseHandle(stdHandles[1]); CloseHandle(stdHandles[2]); ThrowByName(env, "java/io/IOException", "CreatePipe"); return 0; } #ifdef DEBUG_MONITOR swprintf(buffer, _T("Opened pipes: %s, %s, %s\n"), inPipeName, outPipeName, errPipeName); OutputDebugStringW(buffer); #endif nCmdTokens = env->GetArrayLength(cmdarray); nEnvVars = env->GetArrayLength(envp); pCurProcInfo = createProcInfo(); if(NULL == pCurProcInfo) { ThrowByName(env, "java/io/IOException", "Too many processes"); return 0; } // Construct starter's command line swprintf(eventBreakName, L"SABreak%04x%08x", pid, nLocalCounter); swprintf(eventWaitName, L"SAWait%004x%08x", pid, nLocalCounter); swprintf(eventTerminateName, L"SATerm%004x%08x", pid, nLocalCounter); swprintf(eventKillName, L"SAKill%04x%08x", pid, nLocalCounter); swprintf(eventCtrlcName, L"SACtrlc%04x%08x", pid, nLocalCounter); pCurProcInfo->eventBreak = CreateEventW(NULL, FALSE, FALSE, eventBreakName); if(NULL == pCurProcInfo->eventBreak || GetLastError() == ERROR_ALREADY_EXISTS) { ThrowByName(env, "java/io/IOException", "Cannot create event"); return 0; } pCurProcInfo->eventWait = CreateEventW(NULL, TRUE, FALSE, eventWaitName); pCurProcInfo->eventTerminate = CreateEventW(NULL, FALSE, FALSE, eventTerminateName); pCurProcInfo->eventKill = CreateEventW(NULL, FALSE, FALSE, eventKillName); pCurProcInfo->eventCtrlc = CreateEventW(NULL, FALSE, FALSE, eventCtrlcName); swprintf(szCmdLine, L"\"%sstarter.exe\" %i %i %s %s %s %s %s ", path, pid, nLocalCounter, eventBreakName, eventWaitName, eventTerminateName, eventKillName, eventCtrlcName); nPos = wcslen(szCmdLine); // Prepare command line for(i = 0; i < nCmdTokens; ++i) { jstring item = (jstring)env->GetObjectArrayElement(cmdarray, i); jsize len = env->GetStringLength(item); int nCpyLen; const wchar_t * str = (const wchar_t *)env->GetStringChars(item, 0); if(NULL != str) { int requiredSize= nPos+len+2; if (requiredSize > 32*1024) { ThrowByName(env, "java/io/IOException", "Command line too long"); return 0; } ensureSize(&szCmdLine, &nCmdLineLength, requiredSize); if (NULL == szCmdLine) { ThrowByName(env, "java/io/IOException", "Not enough memory"); return 0; } if(0 > (nCpyLen = copyTo(szCmdLine + nPos, str, len, nCmdLineLength - nPos))) { ThrowByName(env, "java/io/IOException", "Command line too long"); return 0; } nPos += nCpyLen; szCmdLine[nPos] = _T(' '); ++nPos; env->ReleaseStringChars(item, (const jchar *)str); } } szCmdLine[nPos] = _T('\0'); #ifdef DEBUG_MONITOR swprintf(buffer, _T("There are %i environment variables \n"), nEnvVars); OutputDebugStringW(buffer); #endif // Prepare environment block if (nEnvVars > 0) { nPos = 0; szEnvBlock = (wchar_t *)malloc(nBlkSize * sizeof(wchar_t)); for(i = 0; i < nEnvVars; ++i) { jstring item = (jstring)env->GetObjectArrayElement(envp, i); jsize len = env->GetStringLength(item); const wchar_t * str = (const wchar_t *)env->GetStringChars(item, 0); if(NULL != str) { while((nBlkSize - nPos) <= (len + 2)) // +2 for two '\0' { nBlkSize += MAX_ENV_SIZE; szEnvBlock = (wchar_t *)realloc(szEnvBlock, nBlkSize * sizeof(wchar_t)); if(NULL == szEnvBlock) { ThrowByName(env, "java/io/IOException", "Not enough memory"); return 0; } #ifdef DEBUG_MONITOR swprintf(buffer, _T("Realloc environment block; new length is %i \n"), nBlkSize); OutputDebugStringW(buffer); #endif } #ifdef DEBUG_MONITOR swprintf(buffer, _T("%s\n"), str); OutputDebugStringW(buffer); #endif wcsncpy(szEnvBlock + nPos, str, len); nPos += len; szEnvBlock[nPos] = _T('\0'); ++nPos; env->ReleaseStringChars(item, (const jchar *)str); } } szEnvBlock[nPos] = _T('\0'); } if (dir != 0) { const wchar_t * str = (const wchar_t *)env->GetStringChars(dir, 0); if(NULL != str) { cwd = wcsdup(str); env->ReleaseStringChars(dir, (const jchar *)str); } } ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); si.dwFlags |= STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE; // Processes in the Process Group are hidden SetHandleInformation(stdHandles[0], HANDLE_FLAG_INHERIT, FALSE); SetHandleInformation(stdHandles[1], HANDLE_FLAG_INHERIT, FALSE); SetHandleInformation(stdHandles[2], HANDLE_FLAG_INHERIT, FALSE); flags = CREATE_NEW_CONSOLE; flags |= CREATE_NO_WINDOW; flags |= CREATE_UNICODE_ENVIRONMENT; #ifdef DEBUG_MONITOR OutputDebugStringW(szCmdLine); #endif // launches starter; we need it to create another console group to correctly process // emulation of SYSint signal (Ctrl-C) ret = CreateProcessW(0, /* executable name */ szCmdLine, /* command line */ 0, /* process security attribute */ 0, /* thread security attribute */ FALSE, /* inherits system handles */ flags, /* normal attached process */ szEnvBlock, /* environment block */ cwd, /* change to the new current directory */ &si, /* (in) startup information */ &pi); /* (out) process information */ if(NULL != cwd) free((void *)cwd); if(NULL != szEnvBlock) free(szEnvBlock); if(NULL != szCmdLine) free(szCmdLine); if (!ret) // Launching error { char * lpMsgBuf; CloseHandle(stdHandles[0]); CloseHandle(stdHandles[1]); CloseHandle(stdHandles[2]); FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (char *)&lpMsgBuf, 0, NULL ); ThrowByName(env, "java/io/IOException", lpMsgBuf); // Free the buffer. LocalFree( lpMsgBuf ); cleanUpProcBlock(pCurProcInfo); ret = -1; } else { int file_handles[3]; HANDLE h[2]; int what; EnterCriticalSection(&cs); pCurProcInfo -> pid = pi.dwProcessId; h[0] = pCurProcInfo -> eventWait; h[1] = pi.hProcess; what = WaitForMultipleObjects(2, h, FALSE, INFINITE); if(what != WAIT_OBJECT_0) // CreateProcess failed { #ifdef DEBUG_MONITOR swprintf(buffer, _T("Process %i failed\n"), pi.dwProcessId); OutputDebugStringW(buffer); #endif cleanUpProcBlock(pCurProcInfo); ThrowByName(env, "java/io/IOException", "Launching failed"); #ifdef DEBUG_MONITOR OutputDebugStringW(_T("Process failed\n")); #endif } else { ret = (long)(pCurProcInfo -> uid); // Prepare stream handlers to return to java program file_handles[0] = (int)stdHandles[0]; file_handles[1] = (int)stdHandles[1]; file_handles[2] = (int)stdHandles[2]; env->SetIntArrayRegion(channels, 0, 3, (jint *)file_handles); // do the cleanup so launch the according thread // create a copy of the PROCESS_INFORMATION as this might get destroyed piCopy = (PROCESS_INFORMATION *)malloc(sizeof(PROCESS_INFORMATION)); memcpy(piCopy, &pi, sizeof(PROCESS_INFORMATION)); _beginthread(waitProcTermination, 0, (void *)piCopy); #ifdef DEBUG_MONITOR OutputDebugStringW(_T("Process started\n")); #endif } LeaveCriticalSection(&cs); } CloseHandle(pi.hThread); return ret; }
void EditBox_OnKeyDown(struct Box_s *pbox, int vk, int scan) { struct editboxdata_s *data = pbox->boxdata; int len = (int)wcslen(data->text); WCHAR beforecur[1024], aftercur[1024]; char keystate[256]; WCHAR unicode; if (data->disabled) { return; } /* reject alt, ctrl, and shift keys, since they won't add a character */ if (vk == VK_CONTROL || vk == VK_SHIFT || vk == VK_MENU) { return; } GetKeyboardState(keystate); if (Util_OldWinVer()) { char ascii[2]; len = ToAscii(vk, scan, keystate, (LPWORD)ascii, 0); if (!len) { return; } MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, ascii, len, &unicode, 1); } else { ToUnicode(vk, scan, keystate, &unicode, 1, 0); } wcsncpy(beforecur, data->text, data->curpos); beforecur[data->curpos] = 0; aftercur[0] = 0; wcscpy(aftercur, data->text + data->curpos); if (vk == 8) /* backspace */ { if (data->curpos != 0) { data->curpos--; beforecur[data->curpos] = 0; data->text[0] = 0; wcscat(data->text, beforecur); wcscat(data->text, aftercur); if (data->OnKey) { data->OnKey(pbox, EditBox_GetText(pbox)); } } } else if (vk == 46) /* delete */ { if (wcslen(aftercur) > 0) { data->text[0] = 0; wcscat(data->text, beforecur); wcscat(data->text, aftercur + 1); if (data->OnKey) { data->OnKey(pbox, EditBox_GetText(pbox)); } } } else if (vk == 9) /* tab */ { Box_SetNextFocus(pbox, keystate[VK_SHIFT] & 0x8000); } else if (vk == 13) /* enter */ { if (data->OnKey) { data->OnKey(pbox, EditBox_GetText(pbox)); } if (data->OnEnter) { data->OnEnter(pbox, EditBox_GetText(pbox)); } } else if (vk == 35) /* end */ { data->curpos = len; } else if (vk == 36) /* home */ { data->curpos = 0; } else if (vk == 37) /* left */ { if (data->curpos != 0) { data->curpos--; } } else if (vk == 39) /* right */ { if (data->curpos != len) { data->curpos++; } } else if ((vk == 86 && (keystate[VK_CONTROL] & 0x8000)) || (vk == 45 && (keystate[VK_SHIFT] & 0x8000))) /* ctrl+v, shift+ins */ { EditBox_OnPaste(pbox); } else if (len < 1023 && unicode > 31) /* Displayable character */ { beforecur[data->curpos] = unicode; data->curpos++; beforecur[data->curpos] = 0; data->text[0] = 0; wcscat(data->text, beforecur); wcscat(data->text, aftercur); if (data->OnKey) { data->OnKey(pbox, EditBox_GetText(pbox)); } } else { Log_Write(0, "unhandled vk %d\n", vk); } Box_Repaint(pbox); }
void EditBox_OnPaste(struct Box_s *pbox) { WCHAR beforecur[1024], aftercur[1024]; struct editboxdata_s *data = pbox->boxdata; wcsncpy(beforecur, data->text, data->curpos); beforecur[data->curpos] = 0; aftercur[0] = 0; wcscpy(aftercur, data->text + data->curpos); if (IsClipboardFormatAvailable(CF_UNICODETEXT)) { if (OpenClipboard(pbox->hwnd)) { HGLOBAL hg; hg = GetClipboardData(CF_UNICODETEXT); if (hg) { WCHAR *pastetext = NULL; WCHAR *temp = GlobalLock(hg); if (temp) { pastetext = wcsdup(temp); GlobalUnlock(hg); data->text[0] = 0; wcscat(data->text, beforecur); wcscat(data->text, pastetext); data->curpos = (int)wcslen(data->text); wcscat(data->text, aftercur); if (data->OnKey) { data->OnKey(pbox, EditBox_GetText(pbox)); } } } CloseClipboard(); } } else if (IsClipboardFormatAvailable(CF_TEXT)) { if (OpenClipboard(pbox->hwnd)) { HGLOBAL hg; hg = GetClipboardData(CF_TEXT); if (hg) { char *temptext = NULL; WCHAR *pastetext = NULL; char *temp = GlobalLock(hg); int len; if (temp) { temptext = strdup(temp); GlobalUnlock(hg); len = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, temptext, -1, NULL, 0); pastetext = malloc((len + 1) * sizeof(WCHAR)); MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, temptext, -1, pastetext, len); pastetext[len] = L'\0'; data->text[0] = 0; wcscat(data->text, beforecur); wcscat(data->text, pastetext); data->curpos = (int)wcslen(data->text); wcscat(data->text, aftercur); if (data->OnKey) { data->OnKey(pbox, EditBox_GetText(pbox)); } } } CloseClipboard(); } } Box_Repaint(pbox); }
/* * Quotes command line arguments * Returns a pointer to the end (next char to be written) of the buffer */ WCHAR* quote_cmd_arg(const WCHAR *source, WCHAR *target) { size_t len = wcslen(source); size_t i; int quote_hit; WCHAR* start; /* * Check if the string must be quoted; * if unnecessary, don't do it, it may only confuse older programs. */ if (len == 0) { return target; } if (NULL == wcspbrk(source, L" \t\"")) { /* No quotation needed */ wcsncpy(target, source, len); target += len; return target; } if (NULL == wcspbrk(source, L"\"\\")) { /* * No embedded double quotes or backlashes, so I can just wrap * quote marks around the whole thing. */ *(target++) = L'"'; wcsncpy(target, source, len); target += len; *(target++) = L'"'; return target; } /* * Expected input/output: * input : hello"world * output: "hello\"world" * input : hello""world * output: "hello\"\"world" * input : hello\world * output: hello\world * input : hello\\world * output: hello\\world * input : hello\"world * output: "hello\\\"world" * input : hello\\"world * output: "hello\\\\\"world" * input : hello world\ * output: "hello world\" */ *(target++) = L'"'; start = target; quote_hit = 1; for (i = len; i > 0; --i) { *(target++) = source[i - 1]; if (quote_hit && source[i - 1] == L'\\') { *(target++) = L'\\'; } else if(source[i - 1] == L'"') { quote_hit = 1; *(target++) = L'\\'; } else { quote_hit = 0; } } target[0] = L'\0'; wcsrev(start); *(target++) = L'"'; return target; }
/** * Processes a software update command * * @param argc The number of arguments in argv * @param argv The arguments normally passed to updater.exe * argv[0] must be the path to updater.exe * @return TRUE if the update was successful. */ BOOL ProcessSoftwareUpdateCommand(DWORD argc, LPWSTR *argv) { BOOL result = TRUE; if (argc < 3) { LOG_WARN(("Not enough command line parameters specified. " "Updating update.status.")); // We can only update update.status if argv[1] exists. argv[1] is // the directory where the update.status file exists. if (argc < 2 || !WriteStatusFailure(argv[1], SERVICE_NOT_ENOUGH_COMMAND_LINE_ARGS)) { LOG_WARN(("Could not write update.status service update failure. (%d)", GetLastError())); } return FALSE; } WCHAR installDir[MAX_PATH + 1] = {L'\0'}; if (!GetInstallationDir(argc, argv, installDir)) { LOG_WARN(("Could not get the installation directory")); if (!WriteStatusFailure(argv[1], SERVICE_INSTALLDIR_ERROR)) { LOG_WARN(("Could not write update.status for GetInstallationDir failure.")); } return FALSE; } // Make sure the path to the updater to use for the update is local. // We do this check to make sure that file locking is available for // race condition security checks. BOOL isLocal = FALSE; if (!IsLocalFile(argv[0], isLocal) || !isLocal) { LOG_WARN(("Filesystem in path %ls is not supported (%d)", argv[0], GetLastError())); if (!WriteStatusFailure(argv[1], SERVICE_UPDATER_NOT_FIXED_DRIVE)) { LOG_WARN(("Could not write update.status service update failure. (%d)", GetLastError())); } return FALSE; } nsAutoHandle noWriteLock(CreateFileW(argv[0], GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL)); if (INVALID_HANDLE_VALUE == noWriteLock) { LOG_WARN(("Could not set no write sharing access on file. (%d)", GetLastError())); if (!WriteStatusFailure(argv[1], SERVICE_COULD_NOT_LOCK_UPDATER)) { LOG_WARN(("Could not write update.status service update failure. (%d)", GetLastError())); } return FALSE; } // Verify that the updater.exe that we are executing is the same // as the one in the installation directory which we are updating. // The installation dir that we are installing to is installDir. WCHAR installDirUpdater[MAX_PATH + 1] = {L'\0'}; wcsncpy(installDirUpdater, installDir, MAX_PATH); if (!PathAppendSafe(installDirUpdater, L"updater.exe")) { LOG_WARN(("Install directory updater could not be determined.")); result = FALSE; } BOOL updaterIsCorrect; if (result && !VerifySameFiles(argv[0], installDirUpdater, updaterIsCorrect)) { LOG_WARN(("Error checking if the updaters are the same.\n" "Path 1: %ls\nPath 2: %ls", argv[0], installDirUpdater)); result = FALSE; } if (result && !updaterIsCorrect) { LOG_WARN(("The updaters do not match, updater will not run.")); result = FALSE; } if (result) { LOG(("updater.exe was compared successfully to the installation directory" " updater.exe.")); } else { if (!WriteStatusFailure(argv[1], SERVICE_UPDATER_COMPARE_ERROR)) { LOG_WARN(("Could not write update.status updater compare failure.")); } return FALSE; } // Check to make sure the updater.exe module has the unique updater identity. // This is a security measure to make sure that the signed executable that // we will run is actually an updater. HMODULE updaterModule = LoadLibraryEx(argv[0], NULL, LOAD_LIBRARY_AS_DATAFILE); if (!updaterModule) { LOG_WARN(("updater.exe module could not be loaded. (%d)", GetLastError())); result = FALSE; } else { char updaterIdentity[64]; if (!LoadStringA(updaterModule, IDS_UPDATER_IDENTITY, updaterIdentity, sizeof(updaterIdentity))) { LOG_WARN(("The updater.exe application does not contain the Mozilla" " updater identity.")); result = FALSE; } if (strcmp(updaterIdentity, UPDATER_IDENTITY_STRING)) { LOG_WARN(("The updater.exe identity string is not valid.")); result = FALSE; } FreeLibrary(updaterModule); } if (result) { LOG(("The updater.exe application contains the Mozilla" " updater identity.")); } else { if (!WriteStatusFailure(argv[1], SERVICE_UPDATER_IDENTITY_ERROR)) { LOG_WARN(("Could not write update.status no updater identity.")); } return TRUE; } // Check for updater.exe sign problems BOOL updaterSignProblem = FALSE; #ifndef DISABLE_UPDATER_AUTHENTICODE_CHECK updaterSignProblem = !DoesBinaryMatchAllowedCertificates(installDir, argv[0]); #endif // Only proceed with the update if we have no signing problems if (!updaterSignProblem) { BOOL updateProcessWasStarted = FALSE; if (StartUpdateProcess(argc, argv, installDir, updateProcessWasStarted)) { LOG(("updater.exe was launched and run successfully!")); LogFlush(); // Don't attempt to update the service when the update is being staged. if (!IsUpdateBeingStaged(argc, argv)) { // We might not execute code after StartServiceUpdate because // the service installer will stop the service if it is running. StartServiceUpdate(installDir); } } else { result = FALSE; LOG_WARN(("Error running update process. Updating update.status (%d)", GetLastError())); LogFlush(); // If the update process was started, then updater.exe is responsible for // setting the failure code. If it could not be started then we do the // work. We set an error instead of directly setting status pending // so that the app.update.service.errors pref can be updated when // the callback app restarts. if (!updateProcessWasStarted) { if (!WriteStatusFailure(argv[1], SERVICE_UPDATER_COULD_NOT_BE_STARTED)) { LOG_WARN(("Could not write update.status service update failure. (%d)", GetLastError())); } } } } else { result = FALSE; LOG_WARN(("Could not start process due to certificate check error on " "updater.exe. Updating update.status. (%d)", GetLastError())); // When there is a certificate check error on the updater.exe application, // we want to write out the error. if (!WriteStatusFailure(argv[1], SERVICE_UPDATER_SIGN_ERROR)) { LOG_WARN(("Could not write pending state to update.status. (%d)", GetLastError())); } } return result; }
bool w2t(const wchar_t *ws, TCHAR *buff, int bufflen) { wcsncpy(buff, ws, bufflen); return true; }
FILE * pt_popen(const char *cmd, const char *mode) { FILE *fptr = NULL; PROCESS_INFORMATION piProcInfo; STARTUPINFOW siStartInfo; int success, redirect_error = 0; wchar_t *wcmd = NULL; wchar_t *err2out; pipe_context *pc; size_t utf8len = utf8_strlen(cmd, strlen(cmd)); if ( !(wcmd = malloc((utf8len+1)*sizeof(wchar_t))) ) { return NULL; } utf8towcs(wcmd, cmd); if ( !(pc=allocPipeContext()) ) goto finito; if ( !mode || !*mode ) goto finito; pc->mode = *mode; if ( pc->mode != 'r' && pc->mode != 'w' ) goto finito; /* * Shall we redirect stderr to stdout ? */ if ( (err2out=wcsstr(wcmd, L"2>&1")) != NULL) { /* this option doesn't apply to win32 shells, so we clear it out! */ wcsncpy(err2out, L" ", 4); redirect_error = 1; } /* * Create the Pipes... */ if (my_pipe(pc->in) == -1 || my_pipe(pc->out) == -1) goto finito; if ( !redirect_error ) { if ( my_pipe(pc->err) == -1) goto finito; } /* * Now create the child process */ ZeroMemory(&siStartInfo, sizeof(STARTUPINFO)); siStartInfo.cb = sizeof(STARTUPINFO); siStartInfo.hStdInput = pc->in[0]; siStartInfo.hStdOutput = pc->out[1]; if ( redirect_error ) siStartInfo.hStdError = pc->out[1]; else siStartInfo.hStdError = pc->err[1]; siStartInfo.dwFlags = STARTF_USESTDHANDLES; success = CreateProcessW(NULL, wcmd, // command line NULL, // process security attributes NULL, // primary thread security attributes TRUE, // handles are inherited CREATE_NO_WINDOW, // creation flags: without window (?) NULL, // use parent's environment NULL, // use parent's current directory &siStartInfo, // STARTUPINFO pointer &piProcInfo); // receives PROCESS_INFORMATION if ( !success ) goto finito; CloseHandle(piProcInfo.hThread); CloseHandle(piProcInfo.hProcess); /* * These handles listen to the Child process */ CloseHandle(pc->in[0]); pc->in[0] = INVALID_HANDLE_VALUE; CloseHandle(pc->out[1]); pc->out[1] = INVALID_HANDLE_VALUE; if ( pc->err[1] != INVALID_HANDLE_VALUE ) { CloseHandle(pc->err[1]); pc->err[1] = INVALID_HANDLE_VALUE; } if ( pc->mode == 'r' ) fptr = _fdopen(_open_osfhandle((intptr_t)pc->out[0],_O_BINARY),"r"); else fptr = _fdopen(_open_osfhandle((intptr_t)pc->in[1],_O_BINARY),"w"); finito: if ( fptr ) { pc->fd = fptr; linkPipeContext(pc); } else { if ( pc ) discardPipeContext(pc); } if ( wcmd ) free(wcmd); return fptr; }
void AudioRendererSettings::LoadSettingsFromRegistry() { USES_CONVERSION; // this is required for T2W macro Log("Loading settings from registry"); HKEY hKey; char* lpData = new char[MAX_REG_LENGTH]; // settings from Reclock - watch CPU usage when enabling these! /*bool usequickseek = false; bool useaafilter = false; //seems clearer without it int aafiltertaps = 56; //Def=32 doesnt matter coz its not used int seqms = 120; //reclock original is 82 int seekwinms = 28; //reclock original is 28 int overlapms = seekwinms; //reduces cutting sound if this is large int seqmslfe = 180; //larger value seems to preserve low frequencies better int seekwinmslfe = 42; //as percentage of seqms int overlapmslfe = seekwinmslfe; //reduces cutting sound if this is large */ LPCTSTR WASAPIPreferredDeviceData = new TCHAR[MAX_REG_LENGTH]; ZeroMemory((void*)WASAPIPreferredDeviceData, MAX_REG_LENGTH); // Try to access the setting root "Software\Team MediaPortal\Audio Renderer" RegOpenKeyEx(HKEY_CURRENT_USER, folder, NULL, KEY_ALL_ACCESS, &hKey); if (hKey) { ReadRegistryKeyDword(hKey, enableTimestretching, enableTimestretchingData); ReadRegistryKeyDword(hKey, WASAPIExclusive, WASAPIExclusiveData); ReadRegistryKeyDword(hKey, WASAPIUseEventMode, WASAPIUseEventModeData); ReadRegistryKeyDword(hKey, devicePeriod, devicePeriodData); ReadRegistryKeyDword(hKey, AC3Encoding, AC3EncodingData); ReadRegistryKeyDword(hKey, AC3bitrate, AC3bitrateData); ReadRegistryKeyDword(hKey, maxBias, maxBiasData); ReadRegistryKeyDword(hKey, minBias, minBiasData); ReadRegistryKeyDword(hKey, audioDelay, audioDelayData); ReadRegistryKeyDword(hKey, logSampleTimes, logSampleTimesData); ReadRegistryKeyDword(hKey, logDebug, logDebugData); ReadRegistryKeyDword(hKey, HWBasedRefClock, HWBasedRefClockData); ReadRegistryKeyDword(hKey, enableSyncAdjustment, enableSyncAdjustmentData); ReadRegistryKeyDword(hKey, forceSamplingRate, forceSamplingRateData); ReadRegistryKeyDword(hKey, forceBitDepth, forceBitDepthData); ReadRegistryKeyDword(hKey, resamplingQuality, resamplingQualityData); ReadRegistryKeyDword(hKey, speakerConfig, speakerConfigData); ReadRegistryKeyDword(hKey, forceChannelMixing, forceChannelMixingData); ReadRegistryKeyDword(hKey, releaseDeviceOnStop, releaseDeviceOnStopData); ReadRegistryKeyDword(hKey, expandMonoToStereo, expandMonoToStereoData); // SoundTouch quality settings ReadRegistryKeyDword(hKey, quality_USE_QUICKSEEK, quality_USE_QUICKSEEKData); ReadRegistryKeyDword(hKey, quality_USE_AA_FILTER, quality_USE_AA_FILTERData); ReadRegistryKeyDword(hKey, quality_AA_FILTER_LENGTH, quality_AA_FILTER_LENGTHData); ReadRegistryKeyDword(hKey, quality_SEQUENCE_MS, quality_SEQUENCE_MSData); ReadRegistryKeyDword(hKey, quality_SEEKWINDOW_MS, quality_SEEKWINDOW_MSData); ReadRegistryKeyDword(hKey, quality_OVERLAP_MS, quality_OVERLAP_MSData); ReadRegistryKeyString(hKey, WASAPIPreferredDevice, WASAPIPreferredDeviceData); Log(" EnableTimestrecthing: %d", enableTimestretchingData); Log(" WASAPIExclusive: %d", WASAPIExclusiveData); Log(" WASAPIUseEventMode: %d", WASAPIUseEventModeData); Log(" AC3Encoding: %d (0 = disabled, 1 = auto, 2 = forced)", AC3EncodingData); Log(" AC3bitrate: %d", AC3bitrateData); Log(" MaxBias: %d", maxBiasData); Log(" MinBias: %d", minBiasData); Log(" AudioDelay: %d", audioDelayData); Log(" LogSampleTimes: %d", logSampleTimesData); Log(" LogDebug: %d", logDebugData); Log(" HWBasedRefClock: %d", HWBasedRefClockData); Log(" EnableSyncAdjustment: %d", enableSyncAdjustmentData); Log(" ForceSamplingRate: %d", forceSamplingRateData); Log(" ForceBitDepth: %d", forceBitDepthData); Log(" ResamplingQuality: %s", ResamplingQualityAsString(resamplingQualityData)); Log(" SpeakerConfig: %d", speakerConfigData); Log(" ForceChannelMixing: %d", forceChannelMixingData); Log(" ReleaseDeviceOnStop: %d", releaseDeviceOnStopData); Log(" ExpandMonoToStereo: %d", expandMonoToStereoData); Log(" quality_USE_QUICKSEEK: %d", quality_USE_QUICKSEEKData); Log(" quality_USE_AA_FILTER: %d", quality_USE_AA_FILTERData); Log(" quality_AA_FILTER_LENGTH: %d", quality_AA_FILTER_LENGTHData); Log(" quality_SEQUENCE_MS: %d", quality_SEQUENCE_MSData); Log(" quality_SEEKWINDOW_MS: %d", quality_SEEKWINDOW_MSData); Log(" quality_OVERLAP_MS: %d", quality_OVERLAP_MSData); Log(" DevicePeriod: %d (1 = minimal, 0 = driver default, other user defined)", devicePeriodData); Log(" WASAPIPreferredDevice: %s", WASAPIPreferredDeviceData); m_bUseWASAPI = true; if (enableTimestretchingData > 0) m_bUseTimeStretching = true; else m_bUseTimeStretching = false; if (WASAPIExclusiveData > 0) m_WASAPIShareMode = AUDCLNT_SHAREMODE_EXCLUSIVE; else m_WASAPIShareMode = AUDCLNT_SHAREMODE_SHARED; if (WASAPIUseEventModeData > 0) m_bWASAPIUseEventMode = true; else m_bWASAPIUseEventMode = false; if (expandMonoToStereoData > 0) m_bExpandMonoToStereo = true; else m_bExpandMonoToStereo = false; if (AC3EncodingData == DISABLED || AC3EncodingData == AUTO || AC3EncodingData == FORCED) m_lAC3Encoding = AC3EncodingData; else m_lAC3Encoding = 0; m_dMaxBias = (double)maxBiasData / 10000.0; m_dMinBias = (double)minBiasData / 10000.0; m_lAudioDelay = audioDelayData; if (logSampleTimesData > 0) m_bLogSampleTimes = true; else m_bLogSampleTimes = false; if (logDebugData > 0) m_bLogDebug = true; else m_bLogDebug = false; if (HWBasedRefClockData > 0) m_bHWBasedRefClock = true; else m_bHWBasedRefClock = false; if (enableSyncAdjustmentData > 0) m_bEnableSyncAdjustment = true; else m_bEnableSyncAdjustment = false; bool AC3EncodingForced = AC3EncodingData == FORCED; bool sampleRateAllowed = AllowedValue(gAllowedSampleRates, sizeof(gAllowedSampleRates) / sizeof(int), forceSamplingRateData); bool bitDepthAllowed = AllowedValue(gAllowedBitDepths, sizeof(gAllowedBitDepths) / sizeof(int), forceBitDepthData); if (AC3EncodingForced) { if (sampleRateAllowed && (forceSamplingRateData != 48000 && forceSamplingRateData != 44100)) { Log(" Warning: AC3 encoding forced and sampling rate set to non-matching!"); sampleRateAllowed = false; } } else if (AC3EncodingData == AUTO && (forceSamplingRateData != 48000 && forceSamplingRateData != 44100 && forceSamplingRateData != 0)) Log(" Warning: Using other than 48000 hz or 44100 hz sampling rates will disable AC3 encoding!"); if (sampleRateAllowed || forceSamplingRateData == 0) m_nForceSamplingRate = forceSamplingRateData; else { m_nForceSamplingRate = 0; if (forceSamplingRateData != 0) Log(" invalid forced sample rate!"); } if (bitDepthAllowed && !AC3EncodingForced || forceBitDepthData == 0) m_nForceBitDepth = forceBitDepthData; else { m_nForceBitDepth = 0; if (forceBitDepthData != 0) Log(" invalid forced bit depth!"); } if (AllowedValue(gAllowedResamplingQualities, sizeof(gAllowedResamplingQualities) / sizeof(int), resamplingQualityData)) m_nResamplingQuality = resamplingQualityData; else { m_nResamplingQuality = 4; Log(" invalid resampling quality setting, using 4 (SRC_LINEAR)"); } if (AllowedValue(gAllowedAC3bitrates, sizeof(gAllowedAC3bitrates) / sizeof(int), AC3bitrateData)) m_AC3bitrate = AC3bitrateData * 1000; else { m_AC3bitrate = DEFAULT_AC3_BITRATE; Log(" invalid AC3 bitrate, using 448"); } m_hnsPeriod = devicePeriodData; if (forceChannelMixingData > 0) m_bForceChannelMixing = true; else m_bForceChannelMixing = false; // TODO validate channel mask if (speakerConfigData > 0) { m_lSpeakerConfig = speakerConfigData; m_lSpeakerCount = ChannelCount(m_lSpeakerConfig); if (AC3EncodingForced && m_lSpeakerCount > 6 && m_bForceChannelMixing) { m_lSpeakerConfig = KSAUDIO_SPEAKER_5POINT1_SURROUND; m_lSpeakerCount = 6; Log(" Warning: incompatible settings. ForceChannelMixing + AC3 encoding forced + more than 6 channels"); } } else m_lSpeakerConfig = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; if (releaseDeviceOnStopData > 0) m_bReleaseDeviceOnStop = true; else m_bReleaseDeviceOnStop = false; if (quality_USE_QUICKSEEKData > 0) m_bQuality_USE_QUICKSEEK = true; else m_bQuality_USE_QUICKSEEK = false; if (quality_USE_AA_FILTERData > 0) m_bQuality_USE_AA_FILTER = true; else m_bQuality_USE_AA_FILTER = false; delete[] m_wWASAPIPreferredDeviceId; m_wWASAPIPreferredDeviceId = new WCHAR[MAX_REG_LENGTH]; wcsncpy(m_wWASAPIPreferredDeviceId, T2W(WASAPIPreferredDeviceData), MAX_REG_LENGTH); delete[] WASAPIPreferredDeviceData; } else // no settings in registry, create default values { Log("Failed to open %s", folder); Log("Initializing registry with default settings"); LONG result = RegCreateKeyEx(HKEY_CURRENT_USER, folder, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, NULL); if (result == ERROR_SUCCESS) { Log("Success creating master key"); WriteRegistryKeyDword(hKey, enableTimestretching, enableTimestretchingData); WriteRegistryKeyDword(hKey, WASAPIExclusive, WASAPIExclusiveData); WriteRegistryKeyDword(hKey, WASAPIUseEventMode, WASAPIUseEventModeData); WriteRegistryKeyDword(hKey, devicePeriod, devicePeriodData); WriteRegistryKeyDword(hKey, AC3Encoding, AC3EncodingData); WriteRegistryKeyDword(hKey, AC3bitrate, AC3bitrateData); WriteRegistryKeyDword(hKey, maxBias, maxBiasData); WriteRegistryKeyDword(hKey, minBias, minBiasData); WriteRegistryKeyDword(hKey, audioDelay, audioDelayData); WriteRegistryKeyDword(hKey, logSampleTimes, logSampleTimesData); WriteRegistryKeyDword(hKey, logDebug, logDebugData); WriteRegistryKeyDword(hKey, HWBasedRefClock, HWBasedRefClockData); WriteRegistryKeyDword(hKey, enableSyncAdjustment, enableSyncAdjustmentData); WriteRegistryKeyDword(hKey, forceSamplingRate, forceSamplingRateData); WriteRegistryKeyDword(hKey, forceBitDepth, forceBitDepthData); WriteRegistryKeyDword(hKey, resamplingQuality, resamplingQualityData); WriteRegistryKeyDword(hKey, speakerConfig, speakerConfigData); WriteRegistryKeyDword(hKey, forceChannelMixing, forceChannelMixingData); WriteRegistryKeyDword(hKey, releaseDeviceOnStop, releaseDeviceOnStopData); WriteRegistryKeyDword(hKey, expandMonoToStereo, expandMonoToStereoData); WriteRegistryKeyDword(hKey, quality_USE_QUICKSEEK, quality_USE_QUICKSEEKData); WriteRegistryKeyDword(hKey, quality_USE_AA_FILTER, quality_USE_AA_FILTERData); WriteRegistryKeyDword(hKey, quality_AA_FILTER_LENGTH, quality_AA_FILTER_LENGTHData); WriteRegistryKeyDword(hKey, quality_SEQUENCE_MS, quality_SEQUENCE_MSData); WriteRegistryKeyDword(hKey, quality_SEEKWINDOW_MS, quality_SEEKWINDOW_MSData); WriteRegistryKeyDword(hKey, quality_OVERLAP_MS, quality_OVERLAP_MSData); delete[] m_wWASAPIPreferredDeviceId; m_wWASAPIPreferredDeviceId = new WCHAR[MAX_REG_LENGTH]; wcsncpy(m_wWASAPIPreferredDeviceId, T2W(WASAPIPreferredDeviceData), MAX_REG_LENGTH); WriteRegistryKeyString(hKey, WASAPIPreferredDevice, WASAPIPreferredDeviceData); } else Log("Error creating master key %d", result); } delete[] lpData; RegCloseKey (hKey); }
bool t2w(const TCHAR *ts, wchar_t *buff, int bufflen) { wcsncpy(buff, ts, bufflen); return true; }
int PASCAL ProcessFile(HANDLE hArcData,int Operation,char *DestPath,char *DestName,wchar *DestPathW,wchar *DestNameW) { DataSet *Data=(DataSet *)hArcData; try { Data->Cmd.DllError=0; if (Data->OpenMode==RAR_OM_LIST || Data->OpenMode==RAR_OM_LIST_INCSPLIT || Operation==RAR_SKIP && !Data->Arc.Solid) { if (Data->Arc.Volume && Data->Arc.GetHeaderType()==FILE_HEAD && (Data->Arc.NewLhd.Flags & LHD_SPLIT_AFTER)!=0) if (MergeArchive(Data->Arc,NULL,false,'L')) { Data->Extract.SignatureFound=false; Data->Arc.Seek(Data->Arc.CurBlockPos,SEEK_SET); return(0); } else return(ERAR_EOPEN); Data->Arc.SeekToNext(); } else { Data->Cmd.DllOpMode=Operation; if (DestPath!=NULL || DestName!=NULL) { #ifdef _WIN_ALL OemToCharA(NullToEmpty(DestPath),Data->Cmd.ExtrPath); #else strcpy(Data->Cmd.ExtrPath,NullToEmpty(DestPath)); #endif AddEndSlash(Data->Cmd.ExtrPath); #ifdef _WIN_ALL OemToCharA(NullToEmpty(DestName),Data->Cmd.DllDestName); #else strcpy(Data->Cmd.DllDestName,NullToEmpty(DestName)); #endif } else { *Data->Cmd.ExtrPath=0; *Data->Cmd.DllDestName=0; } if (DestPathW!=NULL || DestNameW!=NULL) { wcsncpy(Data->Cmd.ExtrPathW,NullToEmpty(DestPathW),NM-2); AddEndSlash(Data->Cmd.ExtrPathW); wcsncpy(Data->Cmd.DllDestNameW,NullToEmpty(DestNameW),NM-1); if (*Data->Cmd.DllDestNameW!=0 && *Data->Cmd.DllDestName==0) WideToChar(Data->Cmd.DllDestNameW,Data->Cmd.DllDestName); } else { *Data->Cmd.ExtrPathW=0; *Data->Cmd.DllDestNameW=0; } strcpy(Data->Cmd.Command,Operation==RAR_EXTRACT ? "X":"T"); Data->Cmd.Test=Operation!=RAR_EXTRACT; bool Repeat=false; Data->Extract.ExtractCurrentFile(&Data->Cmd,Data->Arc,Data->HeaderSize,Repeat); // Archive can be closed if we process volumes, next volume is missing // and current one is already removed or deleted. So we need to check // if archive is still open to avoid calling file operations on // the invalid file handle. Some of our file operations like Seek() // process such invalid handle correctly, some not. while (Data->Arc.IsOpened() && Data->Arc.ReadHeader()!=0 && Data->Arc.GetHeaderType()==NEWSUB_HEAD) { Data->Extract.ExtractCurrentFile(&Data->Cmd,Data->Arc,Data->HeaderSize,Repeat); Data->Arc.SeekToNext(); } Data->Arc.Seek(Data->Arc.CurBlockPos,SEEK_SET); } } catch (int ErrCode) { return(RarErrorToDll(ErrCode)); } return(Data->Cmd.DllError); }
int PASCAL RARReadHeaderEx(HANDLE hArcData,struct RARHeaderDataEx *D) { DataSet *Data=(DataSet *)hArcData; try { if ((Data->HeaderSize=(int)Data->Arc.SearchBlock(FILE_HEAD))<=0) { if (Data->Arc.Volume && Data->Arc.GetHeaderType()==ENDARC_HEAD && (Data->Arc.EndArcHead.Flags & EARC_NEXT_VOLUME)) if (MergeArchive(Data->Arc,NULL,false,'L')) { Data->Extract.SignatureFound=false; Data->Arc.Seek(Data->Arc.CurBlockPos,SEEK_SET); return(RARReadHeaderEx(hArcData,D)); } else return(ERAR_EOPEN); return(Data->Arc.BrokenFileHeader ? ERAR_BAD_DATA:ERAR_END_ARCHIVE); } if (Data->OpenMode==RAR_OM_LIST && (Data->Arc.NewLhd.Flags & LHD_SPLIT_BEFORE)) { int Code=RARProcessFile(hArcData,RAR_SKIP,NULL,NULL); if (Code==0) return(RARReadHeaderEx(hArcData,D)); else return(Code); } strncpyz(D->ArcName,Data->Arc.FileName,ASIZE(D->ArcName)); if (*Data->Arc.FileNameW) wcsncpy(D->ArcNameW,Data->Arc.FileNameW,ASIZE(D->ArcNameW)); else CharToWide(Data->Arc.FileName,D->ArcNameW); strncpyz(D->FileName,Data->Arc.NewLhd.FileName,ASIZE(D->FileName)); if (*Data->Arc.NewLhd.FileNameW) wcsncpy(D->FileNameW,Data->Arc.NewLhd.FileNameW,ASIZE(D->FileNameW)); else { #ifdef _WIN_ALL char AnsiName[NM]; OemToCharA(Data->Arc.NewLhd.FileName,AnsiName); if (!CharToWide(AnsiName,D->FileNameW,ASIZE(D->FileNameW))) *D->FileNameW=0; #else if (!CharToWide(Data->Arc.NewLhd.FileName,D->FileNameW,ASIZE(D->FileNameW))) *D->FileNameW=0; #endif } D->Flags=Data->Arc.NewLhd.Flags; D->PackSize=Data->Arc.NewLhd.PackSize; D->PackSizeHigh=Data->Arc.NewLhd.HighPackSize; D->UnpSize=Data->Arc.NewLhd.UnpSize; D->UnpSizeHigh=Data->Arc.NewLhd.HighUnpSize; D->HostOS=Data->Arc.NewLhd.HostOS; D->FileCRC=Data->Arc.NewLhd.FileCRC; D->FileTime=Data->Arc.NewLhd.FileTime; D->UnpVer=Data->Arc.NewLhd.UnpVer; D->Method=Data->Arc.NewLhd.Method; D->FileAttr=Data->Arc.NewLhd.FileAttr; D->CmtSize=0; D->CmtState=0; } catch (int ErrCode) { return(RarErrorToDll(ErrCode)); } return(0); }
void MumbleManager::init() { #if defined BSD4_4 return; #endif if (mLinkedMem || !config.getBoolValue("enableMumble")) return; logger->log1("MumbleManager::init"); #ifdef WIN32 HANDLE hMapObject = OpenFileMappingW(FILE_MAP_ALL_ACCESS, FALSE, L"MumbleLink"); if (!hMapObject) { logger->log1("MumbleManager::init can't open MumbleLink"); return; } mLinkedMem = reinterpret_cast<LinkedMem *>(MapViewOfFile(hMapObject, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(LinkedMem))); if (!mLinkedMem) { CloseHandle(hMapObject); hMapObject = nullptr; logger->log1("MumbleManager::init can't map MumbleLink"); return; } #elif defined BSD4_4 #else char memName[256]; snprintf(memName, sizeof(memName), "/MumbleLink.%u", getuid()); const int shmfd = shm_open(memName, O_RDWR, S_IRUSR | S_IWUSR); if (shmfd < 0) { logger->log1("MumbleManager::init can't" " open shared memory MumbleLink"); return; } mLinkedMem = static_cast<LinkedMem *>(mmap(nullptr, sizeof(struct LinkedMem), PROT_READ | PROT_WRITE, MAP_SHARED, shmfd, 0)); if (mLinkedMem == reinterpret_cast<void *>(-1)) { mLinkedMem = nullptr; logger->log1("MumbleManager::init can't map MumbleLink"); return; } #endif wcsncpy(mLinkedMemCache.name, L"ManaPlus", 256); wcsncpy(mLinkedMemCache.description, L"ManaPlus Plugin", 2048); mLinkedMemCache.uiVersion = 2; // Left handed coordinate system. // X positive towards "left". // Y positive towards "up". // Z positive towards "into screen". // // 1 unit = 1 meter // Unit vector pointing out of the avatars eyes // (here Front looks into scene). /* no way to look "up", 2d */ mLinkedMemCache.fAvatarFront[1] = 0.0F; // Unit vector pointing out of the top of the avatars head // (here Top looks straight up). /* no way to change this in tmw */ mLinkedMemCache.fAvatarTop[0] = 0.0F; mLinkedMemCache.fAvatarTop[1] = 1.0F; mLinkedMemCache.fAvatarTop[2] = 0.0F; mLinkedMemCache.fCameraFront[0] = 0.0F; mLinkedMemCache.fCameraFront[1] = 0.0F; mLinkedMemCache.fCameraFront[2] = 1.0F; mLinkedMemCache.fCameraTop[0] = 0.0F; mLinkedMemCache.fCameraTop[1] = 1.0F; mLinkedMemCache.fCameraTop[2] = 0.0F; mLinkedMemCache.uiTick++; }
JNIEXPORT jint JNICALL Java_org_eclipse_cdt_utils_spawner_Spawner_exec1 (JNIEnv * env, jobject process, jobjectArray cmdarray, jobjectArray envp, jstring dir) { SECURITY_ATTRIBUTES sa; PROCESS_INFORMATION pi = {0}; STARTUPINFOW si; DWORD flags = 0; wchar_t * cwd = NULL; wchar_t * envBlk = NULL; int ret = 0; jsize nCmdTokens = 0; jsize nEnvVars = 0; int i; int nPos; int nCmdLineLength= 0; wchar_t * szCmdLine= 0; int nBlkSize = MAX_ENV_SIZE; wchar_t * szEnvBlock = NULL; nCmdLineLength= MAX_CMD_SIZE; szCmdLine= (wchar_t *)malloc(nCmdLineLength * sizeof(wchar_t)); szCmdLine[0]= 0; sa.nLength = sizeof(sa); sa.lpSecurityDescriptor = 0; sa.bInheritHandle = TRUE; nCmdTokens = env->GetArrayLength(cmdarray); nEnvVars = env->GetArrayLength(envp); nPos = 0; // Prepare command line for(i = 0; i < nCmdTokens; ++i) { jstring item = (jstring)env->GetObjectArrayElement(cmdarray, i); jsize len = env->GetStringLength(item); int nCpyLen; const wchar_t * str = (const wchar_t *)env->GetStringChars(item, 0); if(NULL != str) { int requiredSize= nPos+len+2; if (requiredSize > 32*1024) { ThrowByName(env, "java/io/IOException", "Command line too long"); return 0; } ensureSize(&szCmdLine, &nCmdLineLength, requiredSize); if (NULL == szCmdLine) { ThrowByName(env, "java/io/IOException", "Not enough memory"); return 0; } if(0 > (nCpyLen = copyTo(szCmdLine + nPos, str, len, nCmdLineLength - nPos))) { ThrowByName(env, "java/io/Exception", "Command line too long"); return 0; } nPos += nCpyLen; szCmdLine[nPos] = _T(' '); ++nPos; env->ReleaseStringChars(item, (const jchar *)str); } } szCmdLine[nPos] = _T('\0'); // Prepare environment block if (nEnvVars > 0) { szEnvBlock = (wchar_t *)malloc(nBlkSize * sizeof(wchar_t)); nPos = 0; for(i = 0; i < nEnvVars; ++i) { jstring item = (jstring)env->GetObjectArrayElement(envp, i); jsize len = env->GetStringLength(item); const wchar_t * str = (const wchar_t *)env->GetStringChars(item, 0); if(NULL != str) { while((nBlkSize - nPos) <= (len + 2)) // +2 for two '\0' { nBlkSize += MAX_ENV_SIZE; szEnvBlock = (wchar_t *)realloc(szEnvBlock, nBlkSize * sizeof(wchar_t)); if(NULL == szEnvBlock) { ThrowByName(env, "java/io/Exception", "Not enough memory"); return 0; } } wcsncpy(szEnvBlock + nPos, str, len); nPos += len; szEnvBlock[nPos] = _T('\0'); ++nPos; env->ReleaseStringChars(item, (const jchar *)str); } } szEnvBlock[nPos] = _T('\0'); envBlk = szEnvBlock; } if (dir != 0) { const wchar_t * str = (const wchar_t *)env->GetStringChars(dir, 0); if(NULL != str) { cwd = wcsdup(str); env->ReleaseStringChars(dir, (const jchar *)str); } } ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); flags = CREATE_NEW_CONSOLE; flags |= CREATE_UNICODE_ENVIRONMENT; ret = CreateProcessW(0, /* executable name */ szCmdLine, /* command line */ 0, /* process security attribute */ 0, /* thread security attribute */ TRUE, /* inherits system handles */ flags, /* normal attached process */ envBlk, /* environment block */ cwd, /* change to the new current directory */ &si, /* (in) startup information */ &pi); /* (out) process information */ if(NULL != cwd) free(cwd); if(NULL != szEnvBlock) free(szEnvBlock); if(NULL != szCmdLine) free(szCmdLine); if (!ret) // error { char * lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (wchar_t *)&lpMsgBuf, 0, NULL ); ThrowByName(env, "java/io/IOException", lpMsgBuf); // Free the buffer. LocalFree( lpMsgBuf ); ret = -1; } else { // Clean-up CloseHandle(pi.hThread); CloseHandle(pi.hProcess); ret = (long)pi.dwProcessId; //hProcess; } return ret; }
CASW_VGUI_Info_Message::CASW_VGUI_Info_Message( vgui::Panel *pParent, const char *pElementName, C_ASW_Info_Message* pMessage ) : vgui::Panel( pParent, pElementName ), CASW_VGUI_Ingame_Panel() { //input->MouseEvent(0, false); // unclick all our mouse buttons when this panel pops up (so firing doesn't get stuck on) if (g_hCurrentInfoPanel.Get()) { g_hCurrentInfoPanel->MarkForDeletion(); g_hCurrentInfoPanel->SetVisible(false); } g_hCurrentInfoPanel = this; m_hMessage = pMessage; for (int i=0;i<4;i++) { m_pLine[i] = new vgui::WrappedLabel(this, "InfoMessageLabel", ""); m_pLine[i]->SetContentAlignment(vgui::Label::a_northwest); m_pLine[i]->SetMouseInputEnabled(false); } m_pOkayButton = new ImageButton(this, "OkayButton", "#asw_close"); m_pOkayButton->AddActionSignalTarget(this); KeyValues *msg = new KeyValues("Command"); msg->SetString("command", "OkayButton"); m_pOkayButton->SetCommand(msg); m_pMessageImage = new vgui::ImagePanel(this, "MessageImage"); m_pMessageImage->SetVisible(false); m_pMessageImage->SetShouldScaleImage(true); m_szImageName[0] = '\0'; if (ShouldAddLogButton()) { m_pLogButton = new ImageButton(this, "LogButton", "#asw_message_log"); m_pLogButton->AddActionSignalTarget(this); KeyValues *msg = new KeyValues("Command"); msg->SetString("command", "MessageLog"); m_pLogButton->SetCommand(msg); } else { Msg(" so not adding it\n"); m_pLogButton = NULL; } // find use key bind char lkeybuffer[12]; Q_snprintf(lkeybuffer, sizeof(lkeybuffer), "%s", ASW_FindKeyBoundTo("+use")); Q_strupr(lkeybuffer); // copy the found key into wchar_t format (localize it if it's a token rather than a normal keyname) wchar_t keybuffer[24]; if (lkeybuffer[0] == '#') { const wchar_t *pLocal = g_pVGuiLocalize->Find(lkeybuffer); if (pLocal) wcsncpy(keybuffer, pLocal, 24); else g_pVGuiLocalize->ConvertANSIToUnicode(lkeybuffer, keybuffer, sizeof(keybuffer)); } else g_pVGuiLocalize->ConvertANSIToUnicode(lkeybuffer, keybuffer, sizeof(keybuffer)); // look up close text localised const wchar_t *pLocal = g_pVGuiLocalize->Find("#asw_close"); if (pLocal) { // join use key and close text together wchar_t buffer[ 256 ]; g_pVGuiLocalize->ConstructString( buffer, sizeof(buffer), g_pVGuiLocalize->Find("#asw_use_icon_format"), 2, keybuffer, pLocal ); // set label m_pOkayButton->SetText(buffer); } if (GetControllerFocus()) { GetControllerFocus()->AddToFocusList(m_pOkayButton); GetControllerFocus()->SetFocusPanel(m_pOkayButton); if (m_pLogButton) { GetControllerFocus()->AddToFocusList(m_pLogButton); } } m_bClosingMessage = false; CLocalPlayerFilter filter; // check for a special sound in the info message const char *pszSound = pMessage ? pMessage->GetSound() : NULL; if (pszSound && Q_strlen(pszSound) > 0) { StopInfoMessageSound(); EmitSound_t ep; ep.m_pSoundName = pszSound; ep.m_flVolume = 1.0f; ep.m_nPitch = PITCH_NORM; ep.m_SoundLevel = SNDLVL_NONE; ep.m_nChannel = CHAN_STATIC; C_BaseEntity::EmitSound( filter, SOUND_FROM_LOCAL_PLAYER, ep ); g_LastInfoSoundGUID = enginesound->GetGuidForLastSoundEmitted(); } UpdateMessage(); SetAlpha(0); vgui::GetAnimationController()->RunAnimationCommand(this, "Alpha", 255, 0.0f, 0.3f, vgui::AnimationController::INTERPOLATOR_LINEAR); SetKeyBoardInputEnabled(true); SetMouseInputEnabled(true); RequestFocus(); ASWInput()->SetCameraFixed( true ); g_asw_iGUIWindowsOpen++; }
//----------------------------------------------------------------------------- // Purpose: Looks up key bindings for commands and replaces them in string. // %<commandname>% will get replaced with its bound control, e.g. %attack2% // Input buffer sizes are in bytes rather than unicode character count // for consistency with other APIs. If inbufsizebytes is 0 a NULL-terminated // input buffer is assumed, or you can pass the size of the input buffer if // not NULL-terminated. //----------------------------------------------------------------------------- void UTIL_ReplaceKeyBindings( const wchar_t *inbuf, int inbufsizebytes, wchar_t *outbuf, int outbufsizebytes ) { if ( !inbuf || !inbuf[0] ) return; // copy to a new buf if there are vars outbuf[0]=0; int pos = 0; const wchar_t *inbufend = NULL; if ( inbufsizebytes > 0 ) { inbufend = inbuf + ( inbufsizebytes / 2 ); } while( inbuf != inbufend && *inbuf != 0 ) { // check for variables if ( *inbuf == '%' ) { ++inbuf; const wchar_t *end = wcschr( inbuf, '%' ); if ( end && ( end != inbuf ) ) // make sure we handle %% in the string, which should be treated in the output as % { wchar_t token[64]; wcsncpy( token, inbuf, end - inbuf ); token[end - inbuf] = 0; inbuf += end - inbuf; // lookup key names char binding[64]; g_pVGuiLocalize->ConvertUnicodeToANSI( token, binding, sizeof(binding) ); const char *key = engine->Key_LookupBinding( *binding == '+' ? binding + 1 : binding ); if ( !key ) { key = IsX360() ? "" : "< not bound >"; } //!! change some key names into better names char friendlyName[64]; bool bAddBrackets = false; if ( IsX360() ) { if ( !key || !key[0] ) { Q_snprintf( friendlyName, sizeof(friendlyName), "#GameUI_None" ); bAddBrackets = true; } else { Q_snprintf( friendlyName, sizeof(friendlyName), "#GameUI_KeyNames_%s", key ); } } else { Q_snprintf( friendlyName, sizeof(friendlyName), "%s", key ); } Q_strupr( friendlyName ); wchar_t *locName = g_pVGuiLocalize->Find( friendlyName ); if ( !locName || wcslen(locName) <= 0) { g_pVGuiLocalize->ConvertANSIToUnicode( friendlyName, token, sizeof(token) ); outbuf[pos] = '\0'; wcscat( outbuf, token ); pos += wcslen(token); } else { outbuf[pos] = '\0'; if ( bAddBrackets ) { wcscat( outbuf, L"[" ); pos += 1; } wcscat( outbuf, locName ); pos += wcslen(locName); if ( bAddBrackets ) { wcscat( outbuf, L"]" ); pos += 1; } } } else { outbuf[pos] = *inbuf; ++pos; } } else { outbuf[pos] = *inbuf; ++pos; } ++inbuf; } outbuf[pos] = '\0'; }
/*--------------------------------------------------------------------------*/ wchar_t *expandPathVariableW(wchar_t *wcstr) { wchar_t *wcexpanded = NULL; if (wcstr) { int i = 0; int lenStr = (int)wcslen(wcstr); for (i = 0; i < NB_ALIAS; i++) { int lenAlias = 0; /* input is ALIAS without subdirectory */ if (wcscmp(VARIABLES_words[i].Alias, wcstr) == 0) { wchar_t *wcexpanded = getVariableValueDefinedInScilab(VARIABLES_words[i].VariableName); if (wcexpanded) { return convertFileSeparators(wcexpanded); } } lenAlias = (int)wcslen(VARIABLES_words[i].Alias); if (lenStr > lenAlias) { wchar_t *wcBegin = (wchar_t *)MALLOC(sizeof(wchar_t) * (lenAlias + 1)); if (wcBegin) { wcsncpy(wcBegin, wcstr, lenAlias); wcBegin[lenAlias] = 0; if (wcscmp(wcBegin, VARIABLES_words[i].Alias) == 0 ) { if ( (wcstr[lenAlias] == L'/') || (wcstr[lenAlias] == L'\\') ) { wchar_t * newBegin = getVariableValueDefinedInScilab(VARIABLES_words[i].VariableName); if (newBegin) { int lengthnewBegin = (int)wcslen(newBegin); wcexpanded = (wchar_t *)MALLOC(sizeof(wchar_t) * (lengthnewBegin + (int)wcslen(&wcstr[lenAlias]) + 1)); if (wcexpanded) { wcscpy(wcexpanded, newBegin); wcscat(wcexpanded, &wcstr[lenAlias]); FREE(wcBegin); wcBegin = NULL; FREE(newBegin); newBegin = NULL; return convertFileSeparators(wcexpanded); } FREE(newBegin); newBegin = NULL; } } } FREE(wcBegin); wcBegin = NULL; } } } /* Variables not founded returns a copy of input */ wcexpanded = (wchar_t*)MALLOC(sizeof(wchar_t) * ((int)wcslen(wcstr) + 1)); if (wcexpanded) { wcscpy(wcexpanded, wcstr); return convertFileSeparators(wcexpanded); } } return wcexpanded; }
////////////////////////////////////////////////////////////////////////////// // main // // Note: XPCOM cannot be used until AttemptGRELoad has returned successfully. int main(int argc, char* argv[]) { pargc = &argc; pargv = &argv; nsresult rv; char buffer[MAXPATHLEN]; wchar_t wbuffer[MAXPATHLEN]; // Set up curEXEPath if (!GetModuleFileNameW(0, wbuffer, MAXPATHLEN)) { Output("Couldn't calculate the application directory."); return 255; } wcsncpy(curExePath, wbuffer, MAXPATHLEN); // Get the current directory into wbuffer wchar_t* lastSlash = wcsrchr(wbuffer, L'\\'); if (!lastSlash) { Output("Application directory format not understood."); return 255; } *(++lastSlash) = L'\0'; // Set up backup file path if (wcslen(wbuffer) + _countof(kAPP_RT_BACKUP) >= MAXPATHLEN) { Output("Application directory path is too long (couldn't set up backup file path)."); } wcsncpy(lastSlash, kAPP_RT_BACKUP, _countof(kAPP_RT_BACKUP)); wcsncpy(backupFilePath, wbuffer, MAXPATHLEN); *lastSlash = L'\0'; // Convert current directory to utf8 and stuff it in buffer if (0 == WideCharToMultiByte(CP_UTF8, 0, wbuffer, -1, buffer, MAXPATHLEN, NULL, NULL)) { Output("Application directory could not be processed."); return 255; } // Set up appIniPath with path to webapp.ini. // This should be in the same directory as the running executable. char appIniPath[MAXPATHLEN]; if (NS_FAILED(joinPath(appIniPath, buffer, kWEBAPP_INI, MAXPATHLEN))) { Output("Path to webapp.ini could not be processed."); return 255; } // Open webapp.ini as an INI file (as opposed to using the // XRE webapp.ini-specific processing we do later) nsINIParser parser; if (NS_FAILED(parser.Init(appIniPath))) { Output("Could not open webapp.ini"); return 255; } // Set up our environment to know where webapp.ini was loaded from. char appEnv[MAXPATHLEN + _countof(kAPP_ENV_PREFIX)]; strcpy(appEnv, kAPP_ENV_PREFIX); strcpy(appEnv + _countof(kAPP_ENV_PREFIX) - 1, appIniPath); if (putenv(appEnv)) { Output("Couldn't set up app environment"); return 255; } // Get profile dir from webapp.ini if (NS_FAILED(parser.GetString("Webapp", "Profile", profile, MAXPATHLEN))) { Output("Unable to retrieve profile from web app INI file"); return 255; } char firefoxDir[MAXPATHLEN]; // First attempt at loading Firefox binaries: // Get the location of Firefox from our webapp.ini // XXX: This string better be UTF-8... rv = parser.GetString("WebappRT", "InstallDir", firefoxDir, MAXPATHLEN); if (NS_SUCCEEDED(rv)) { if (AttemptLoadFromDir(firefoxDir)) { return 0; } } // Second attempt at loading Firefox binaries: // Get the location of Firefox from the registry if (GetFirefoxDirFromRegistry(firefoxDir)) { if (AttemptLoadFromDir(firefoxDir)) { // XXX: Write gre dir location to webapp.ini return 0; } } // We've done all we know how to do to try to find and launch FF Output("This app requires that Firefox version 15 or above is installed." " Firefox 15+ has not been detected."); return 255; }
//--------------------------------------------------------------------------- bool TFileZillaIntf::HandleMessage(WPARAM wParam, LPARAM lParam) { bool Result; unsigned int MessageID = FZ_MSG_ID(wParam); switch (MessageID) { case FZ_MSG_STATUS: { ASSERT(FZ_MSG_PARAM(wParam) == 0); t_ffam_statusmessage * Status = (t_ffam_statusmessage *)lParam; ASSERT(Status->post); Result = HandleStatus(Status->status, Status->type); delete Status; } break; case FZ_MSG_ASYNCREQUEST: if (FZ_MSG_PARAM(wParam) == FZ_ASYNCREQUEST_OVERWRITE) { int RequestResult = 0; wchar_t FileName1[MAX_PATH]; COverwriteRequestData * Data = (COverwriteRequestData *)lParam; try { ASSERT(Data != NULL); wcsncpy(FileName1, Data->FileName1, _countof(FileName1)); FileName1[_countof(FileName1) - 1] = L'\0'; TRemoteFileTime RemoteTime; CopyFileTime(RemoteTime, Data->remotetime); Result = HandleAsynchRequestOverwrite( FileName1, _countof(FileName1), Data->FileName2, Data->path1, Data->path2, Data->size1, Data->size2, (Data->localtime != NULL) ? Data->localtime->GetTime() : 0, (Data->localtime != NULL) && ((Data->localtime->GetHour() != 0) || (Data->localtime->GetMinute() != 0)), RemoteTime, ToPtr(Data->pTransferFile->nUserData), Data->localFileHandle, RequestResult); } catch (...) { FFileZillaApi->SetAsyncRequestResult(FILEEXISTS_SKIP, Data); throw; } if (Result) { Data->FileName1 = FileName1; Result = Check(FFileZillaApi->SetAsyncRequestResult(RequestResult, Data), L"setasyncrequestresult"); } } else if (FZ_MSG_PARAM(wParam) == FZ_ASYNCREQUEST_VERIFYCERT) { int RequestResult; CVerifyCertRequestData * AData = (CVerifyCertRequestData *)lParam; try { ASSERT(AData != NULL); TFtpsCertificateData Data; CopyContact(Data.Subject, AData->pCertData->subject); CopyContact(Data.Issuer, AData->pCertData->issuer); CopyValidityTime(Data.ValidFrom, AData->pCertData->validFrom); CopyValidityTime(Data.ValidUntil, AData->pCertData->validUntil); Data.SubjectAltName = AData->pCertData->subjectAltName; Data.Hash = AData->pCertData->hash; Data.Certificate = AData->pCertData->certificate; Data.CertificateLen = AData->pCertData->certificateLen; Data.VerificationResult = AData->pCertData->verificationResult; Data.VerificationDepth = AData->pCertData->verificationDepth; Result = HandleAsynchRequestVerifyCertificate(Data, RequestResult); } catch (...) { FFileZillaApi->SetAsyncRequestResult(0, AData); throw; } if (Result) { Result = Check(FFileZillaApi->SetAsyncRequestResult(RequestResult, AData), L"setasyncrequestresult"); } } else if (FZ_MSG_PARAM(wParam) == FZ_ASYNCREQUEST_NEEDPASS) { int RequestResult = 0; CNeedPassRequestData * AData = (CNeedPassRequestData *)lParam; try { TNeedPassRequestData Data; Data.Password = NULL; Data.Password = AData->Password.GetBuffer(AData->Password.GetLength()); Result = HandleAsynchRequestNeedPass(Data, RequestResult); AData->Password.ReleaseBuffer(AData->Password.GetLength()); if (Result && (RequestResult == TFileZillaIntf::REPLY_OK)) { AData->Password = Data.Password; free(Data.Password); Data.Password = NULL; } } catch (...) { FFileZillaApi->SetAsyncRequestResult(0, AData); throw; } if (Result) { Result = Check(FFileZillaApi->SetAsyncRequestResult(RequestResult, AData), L"setasyncrequestresult"); } } else { // FZ_ASYNCREQUEST_GSS_AUTHFAILED // FZ_ASYNCREQUEST_GSS_NEEDUSER // FZ_ASYNCREQUEST_GSS_NEEDPASS ASSERT(FALSE); Result = false; } break; case FZ_MSG_LISTDATA: { ASSERT(FZ_MSG_PARAM(wParam) == 0); t_directory * Directory = (t_directory *)lParam; CString Path = Directory->path.GetPath(); rde::vector<TListDataEntry> Entries(Directory->num); for (intptr_t Index = 0; Index < Directory->num; ++Index) { t_directory::t_direntry & Source = Directory->direntry[Index]; TListDataEntry & Dest = Entries[Index]; Dest.Name = Source.name; Dest.Permissions = Source.permissionstr; Dest.HumanPerm = Source.humanpermstr; Dest.OwnerGroup = Source.ownergroup; Dest.Size = Source.size; Dest.Dir = Source.dir; Dest.Link = Source.bLink; CopyFileTime(Dest.Time, Source.date); Dest.LinkTarget = Source.linkTarget; } int Num = Directory->num; TListDataEntry * pEntries = Num > 0 ? &Entries[0] : NULL; Result = HandleListData(Path, pEntries, Num); delete Directory; } break; case FZ_MSG_TRANSFERSTATUS: { ASSERT(FZ_MSG_PARAM(wParam) == 0); t_ffam_transferstatus * Status = reinterpret_cast<t_ffam_transferstatus *>(lParam); if (Status != NULL) { Result = HandleTransferStatus(true, Status->transfersize, Status->bytes, Status->percent, Status->timeelapsed, Status->timeleft, Status->transferrate, Status->bFileTransfer != 0); delete Status; } else { Result = HandleTransferStatus(false, -1, -1, -1, -1, -1, -1, false); } } break; case FZ_MSG_REPLY: Result = HandleReply(FZ_MSG_PARAM(wParam), lParam); break; case FZ_MSG_CAPABILITIES: Result = HandleCapabilities((TFTPServerCapabilities *)lParam); break; case FZ_MSG_SOCKETSTATUS: case FZ_MSG_SECURESERVER: case FZ_MSG_QUITCOMPLETE: default: ASSERT(false); Result = false; break; } return Result; }
void Mixer::getPortsInfo() { MIXERCAPS mc; mixerGetDevCaps((UINT)hMixer, &mc, sizeof mc); MIXERLINE mlt; unsigned i; for (i = 0; i < mc.cDestinations; ++i) { memset(&mlt, 0, sizeof mlt); mlt.cbStruct = sizeof mlt; mlt.dwDestination = i; if (mixerGetLineInfo((HMIXEROBJ)hMixer, &mlt, MIXER_GETLINEINFOF_DESTINATION) != MMSYSERR_NOERROR) continue; if (mlt.dwLineID == dwRecLineID) break; // this is the destination we're interested in } ports = new AudioInputPort[mlt.cConnections]; numPorts = mlt.cConnections; for (i = 0; i < numPorts; ++i) { MIXERLINE mlc; memcpy(&mlc, &mlt, sizeof mlc); mlc.dwSource = i; mixerGetLineInfo((HMIXEROBJ)hMixer, &mlc, MIXER_GETLINEINFOF_SOURCE/*|MIXER_OBJECTF_HMIXER*/); ports[i].tag = mlc.dwLineID; ports[i].dwComponentType = mlc.dwComponentType; #ifdef UNICODE wcstombs(ports[i].name, mlc.szName, MIXER_LONG_NAME_CHARS); #else strncpy(ports[i].name, mlc.szName, MIXER_LONG_NAME_CHARS); #endif } // Make the microphone the first port in the list: for (i = 1; i < numPorts; ++i) { #ifdef OLD_MICROPHONE_TESTING_CODE if (_strnicmp("mic", ports[i].name, 3) == 0 || _strnicmp("mik", ports[i].name, 3) == 0) { #else if (ports[i].dwComponentType == MIXERLINE_COMPONENTTYPE_SRC_MICROPHONE) { #endif AudioInputPort tmp = ports[0]; ports[0] = ports[i]; ports[i] = tmp; } } } Boolean Mixer::enableInputPort(unsigned portIndex, char const*& errReason, MMRESULT& errCode) { errReason = NULL; // unless there's an error AudioInputPort& port = ports[portIndex]; MIXERCONTROL mc; mc.cMultipleItems = 1; // in case it doesn't get set below MIXERLINECONTROLS mlc; #if 0 // the following doesn't seem to be needed, and can fail: mlc.cbStruct = sizeof mlc; mlc.pamxctrl = &mc; mlc.cbmxctrl = sizeof (MIXERCONTROL); mlc.dwLineID = port.tag; mlc.dwControlType = MIXERCONTROL_CONTROLTYPE_VOLUME; if ((errCode = mixerGetLineControls((HMIXEROBJ)hMixer, &mlc, MIXER_GETLINECONTROLSF_ONEBYTYPE/*|MIXER_OBJECTF_HMIXER*/)) != MMSYSERR_NOERROR) { errReason = "mixerGetLineControls()"; return False; } #endif MIXERLINE ml; memset(&ml, 0, sizeof (MIXERLINE)); ml.cbStruct = sizeof (MIXERLINE); ml.dwLineID = port.tag; if ((errCode = mixerGetLineInfo((HMIXEROBJ)hMixer, &ml, MIXER_GETLINEINFOF_LINEID)) != MMSYSERR_NOERROR) { errReason = "mixerGetLineInfo()1"; return False; } #ifdef UNICODE wchar_t portname[MIXER_LONG_NAME_CHARS+1]; wcsncpy(portname, ml.szName, MIXER_LONG_NAME_CHARS); #else char portname[MIXER_LONG_NAME_CHARS+1]; strncpy(portname, ml.szName, MIXER_LONG_NAME_CHARS); #endif memset(&ml, 0, sizeof (MIXERLINE)); ml.cbStruct = sizeof (MIXERLINE); ml.dwLineID = dwRecLineID; if ((errCode = mixerGetLineInfo((HMIXEROBJ)hMixer, &ml, MIXER_GETLINEINFOF_LINEID/*|MIXER_OBJECTF_HMIXER*/)) != MMSYSERR_NOERROR) { errReason = "mixerGetLineInfo()2"; return False; } // Get Mixer/MUX control information (need control id to set and get control details) mlc.cbStruct = sizeof mlc; mlc.dwLineID = ml.dwLineID; mlc.cControls = 1; mc.cbStruct = sizeof mc; // Needed???##### mc.dwControlID = 0xDEADBEEF; // For testing ##### mlc.pamxctrl = &mc; mlc.cbmxctrl = sizeof mc; mlc.dwControlType = MIXERCONTROL_CONTROLTYPE_MUX; // Single Select if ((errCode = mixerGetLineControls((HMIXEROBJ)hMixer, &mlc, MIXER_GETLINECONTROLSF_ONEBYTYPE/*|MIXER_OBJECTF_HMIXER*/)) != MMSYSERR_NOERROR) { mlc.dwControlType = MIXERCONTROL_CONTROLTYPE_MIXER; // Multiple Select mixerGetLineControls((HMIXEROBJ)hMixer, &mlc, MIXER_GETLINECONTROLSF_ONEBYTYPE/*|MIXER_OBJECTF_HMIXER*/); } unsigned matchLine = 0; if (mc.cMultipleItems > 1) { // Before getting control, we need to know which line to grab. // We figure this out by listing the lines, and comparing names: MIXERCONTROLDETAILS mcd; mcd.cbStruct = sizeof mcd; mcd.cChannels = ml.cChannels; mcd.cMultipleItems = mc.cMultipleItems; MIXERCONTROLDETAILS_LISTTEXT* mcdlText = new MIXERCONTROLDETAILS_LISTTEXT[mc.cMultipleItems]; mcd.cbDetails = sizeof (MIXERCONTROLDETAILS_LISTTEXT); mcd.paDetails = mcdlText; if (mc.dwControlID != 0xDEADBEEF) { // we know the control id for real mcd.dwControlID = mc.dwControlID; if ((errCode = mixerGetControlDetails((HMIXEROBJ)hMixer, &mcd, MIXER_GETCONTROLDETAILSF_LISTTEXT/*|MIXER_OBJECTF_HMIXER*/)) != MMSYSERR_NOERROR) { delete[] mcdlText; errReason = "mixerGetControlDetails()1"; return False; } } else { // Hack: We couldn't find a MUX or MIXER control, so try to guess the control id: for (mc.dwControlID = 0; mc.dwControlID < 32; ++mc.dwControlID) { mcd.dwControlID = mc.dwControlID; if ((errCode = mixerGetControlDetails((HMIXEROBJ)hMixer, &mcd, MIXER_GETCONTROLDETAILSF_LISTTEXT/*|MIXER_OBJECTF_HMIXER*/)) == MMSYSERR_NOERROR) break; } if (mc.dwControlID == 32) { // unable to guess mux/mixer control id delete[] mcdlText; errReason = "mixerGetControlDetails()2"; return False; } } #ifdef UNICODE for (unsigned i = 0; i < mcd.cMultipleItems; ++i) { if (wcscmp(mcdlText[i].szName, portname) == 0) { matchLine = i; break; } } #else for (unsigned i = 0; i < mcd.cMultipleItems; ++i) { if (strcmp(mcdlText[i].szName, portname) == 0) { matchLine = i; break; } } #endif delete[] mcdlText; } // Now get control itself: MIXERCONTROLDETAILS mcd; mcd.cbStruct = sizeof mcd; mcd.dwControlID = mc.dwControlID; mcd.cChannels = ml.cChannels; mcd.cMultipleItems = mc.cMultipleItems; MIXERCONTROLDETAILS_BOOLEAN* mcdbState = new MIXERCONTROLDETAILS_BOOLEAN[mc.cMultipleItems]; mcd.paDetails = mcdbState; mcd.cbDetails = sizeof (MIXERCONTROLDETAILS_BOOLEAN); if ((errCode = mixerGetControlDetails((HMIXEROBJ)hMixer, &mcd, MIXER_GETCONTROLDETAILSF_VALUE/*|MIXER_OBJECTF_HMIXER*/)) != MMSYSERR_NOERROR) { delete[] mcdbState; errReason = "mixerGetControlDetails()3"; return False; } for (unsigned j = 0; j < mcd.cMultipleItems; ++j) { mcdbState[j].fValue = (j == matchLine); } if ((errCode = mixerSetControlDetails((HMIXEROBJ)hMixer, &mcd, MIXER_OBJECTF_HMIXER)) != MMSYSERR_NOERROR) { delete[] mcdbState; errReason = "mixerSetControlDetails()"; return False; } delete[] mcdbState; return True; }
/* * wcsxfrm: Transfom the wide-char str2 and place the result into the str1, * return the length of the wide-char, return -1 on error. */ size_t wcsxfrm (wchar_t * str1, const wchar_t * str2, size_t n) { wcsncpy (str1, str2, n); return wcslen (str1); }
void Assign(const WCHAR* u16_String, UINT u32_Len) { Allocate(u32_Len); // throws wcsncpy(mu16_Buf, u16_String, u32_Len); mu16_Buf[u32_Len] = 0; }
static int get_device_string(hid_device *dev, enum device_string_id key, wchar_t *string, size_t maxlen) { struct udev *udev; struct udev_device *udev_dev, *parent, *hid_dev; struct stat s; int ret = -1; char *serial_number_utf8 = NULL; char *product_name_utf8 = NULL; /* Create the udev object */ udev = udev_new(); if (!udev) { printf("Can't create udev\n"); return -1; } /* Get the dev_t (major/minor numbers) from the file handle. */ fstat(dev->device_handle, &s); /* Open a udev device from the dev_t. 'c' means character device. */ udev_dev = udev_device_new_from_devnum(udev, 'c', s.st_rdev); if (udev_dev) { hid_dev = udev_device_get_parent_with_subsystem_devtype( udev_dev, "hid", NULL); if (hid_dev) { unsigned short dev_vid; unsigned short dev_pid; int bus_type; size_t retm; ret = parse_uevent_info( udev_device_get_sysattr_value(hid_dev, "uevent"), &bus_type, &dev_vid, &dev_pid, &serial_number_utf8, &product_name_utf8); if (bus_type == BUS_BLUETOOTH) { switch (key) { case DEVICE_STRING_MANUFACTURER: wcsncpy(string, L"", maxlen); ret = 0; break; case DEVICE_STRING_PRODUCT: retm = mbstowcs(string, product_name_utf8, maxlen); ret = (retm == (size_t)-1)? -1: 0; break; case DEVICE_STRING_SERIAL: retm = mbstowcs(string, serial_number_utf8, maxlen); ret = (retm == (size_t)-1)? -1: 0; break; case DEVICE_STRING_COUNT: default: ret = -1; break; } } else { /* This is a USB device. Find its parent USB Device node. */ parent = udev_device_get_parent_with_subsystem_devtype( udev_dev, "usb", "usb_device"); if (parent) { const char *str; const char *key_str = NULL; if (key >= 0 && key < DEVICE_STRING_COUNT) { key_str = device_string_names[key]; } else { ret = -1; goto end; } str = udev_device_get_sysattr_value(parent, key_str); if (str) { /* Convert the string from UTF-8 to wchar_t */ retm = mbstowcs(string, str, maxlen); ret = (retm == (size_t)-1)? -1: 0; goto end; } } } } } end: free(serial_number_utf8); free(product_name_utf8); udev_device_unref(udev_dev); /* parent and hid_dev don't need to be (and can't be) unref'd. I'm not sure why, but they'll throw double-free() errors. */ udev_unref(udev); return ret; }
void EditBox_OnPaint(struct Box_s *pbox, HDC hdc, RECT rcClip, int x, int y, int paintmask) { struct editboxdata_s *data = pbox->boxdata; struct Box_s *child = pbox->child; RECT rcBox, rc; /* If box is not visible, punt */ if (!(pbox->flags & BOX_VISIBLE)) { return; } /* Set up the box rect */ rcBox.left = x; rcBox.top = y; rcBox.right = rcBox.left + pbox->w - 1; rcBox.bottom = rcBox.top + pbox->h - 1; /* Clip the box rect against the draw rect */ rc.left = MAX(rcBox.left, rcClip.left); rc.right = MIN(rcBox.right, rcClip.right); rc.top = MAX(rcBox.top, rcClip.top); rc.bottom = MIN(rcBox.bottom, rcClip.bottom); /* If nothing to draw, punt */ if ((rc.right <= rc.left) || (rc.bottom <= rc.top)) { return; } Box_OnPaint(pbox, hdc, rcClip, x, y, paintmask); if (data->text) { COLORREF oldfgcol; int oldbkmode; HFONT oldfont; RECT draw = rcBox; WCHAR firsthalf[1024], *secondhalf; RECT measure = rcBox; int pass = 0, xtext; oldbkmode = SetBkMode(hdc, TRANSPARENT); oldfgcol = SetTextColor(hdc, pbox->fgcol); if (pbox->font) { oldfont = SelectObject(hdc, pbox->font); } else { oldfont = SelectObject(hdc, tahoma11_f); } pass = data->curpos - data->curpos % 40; if (data->hidetext) { int i; for (i = 0; i < data->curpos - pass; i++) { firsthalf[i] = L'*'; } firsthalf[i] = 0; secondhalf = malloc((wcslen(data->text + data->curpos) + 1) * sizeof(WCHAR)); for (i = 0; i < (int)wcslen(data->text + data->curpos); i++) { secondhalf[i] = L'*'; } secondhalf[i] = 0; } else { wcsncpy(firsthalf, data->text + pass, data->curpos - pass); firsthalf[data->curpos - pass] = 0; secondhalf = data->text + data->curpos; } if (Util_OldWinVer()) { char *ansifirst = Util_ConvertWCHARToANSI(firsthalf); char *ansisecond = Util_ConvertWCHARToANSI(secondhalf); measure.right = measure.left; DrawTextA(hdc, ansifirst, (int)strlen(ansifirst), &measure, DT_CALCRECT | DT_NOPREFIX); ExtTextOutA(hdc, draw.left + 2, draw.top + 2, ETO_CLIPPED, &rc, ansifirst, (UINT)strlen(ansifirst), NULL); xtext = draw.left + 2 + measure.right - measure.left; if (Box_HasFocus(pbox)) { MoveToEx(hdc, xtext, draw.top + 2, NULL); LineTo(hdc, xtext, draw.top + 18); } ExtTextOutA(hdc, xtext, draw.top + 2, ETO_CLIPPED, &rc, ansisecond, (UINT)strlen(ansisecond), NULL); if (pbox->font) { SelectObject(hdc, oldfont); } SetBkMode(hdc, oldbkmode); SetTextColor(hdc, oldfgcol); } else { measure.right = measure.left; DrawTextW(hdc, firsthalf, (int)wcslen(firsthalf), &measure, DT_CALCRECT | DT_NOPREFIX); ExtTextOutW(hdc, draw.left + 2, draw.top + 2, ETO_CLIPPED, &rc, firsthalf, (UINT)wcslen(firsthalf), NULL); xtext = draw.left + 2 + measure.right - measure.left; if (Box_HasFocus(pbox)) { MoveToEx(hdc, xtext, draw.top + 2, NULL); LineTo(hdc, xtext, draw.top + 18); } ExtTextOutW(hdc, xtext, draw.top + 2, ETO_CLIPPED, &rc, secondhalf, (UINT)wcslen(secondhalf), NULL); } if (pbox->font) { SelectObject(hdc, oldfont); } SetBkMode(hdc, oldbkmode); SetTextColor(hdc, oldfgcol); } }
void setTooltip(const wchar_t* tooltip) { wcsncpy(nid.szTip, tooltip, sizeof(nid.szTip)/sizeof(wchar_t)); nid.uFlags = NIF_TIP; Shell_NotifyIcon(NIM_MODIFY, &nid); }
/* * Helper function for search_path */ static WCHAR* search_path_join_test(const WCHAR* dir, size_t dir_len, const WCHAR* name, size_t name_len, const WCHAR* ext, size_t ext_len, const WCHAR* cwd, size_t cwd_len) { WCHAR *result, *result_pos; DWORD attrs; if (dir_len >= 1 && (dir[0] == L'/' || dir[0] == L'\\')) { /* It's a full path without drive letter, use cwd's drive letter only */ cwd_len = 2; } else if (dir_len >= 2 && dir[1] == L':' && (dir_len < 3 || (dir[2] != L'/' && dir[2] != L'\\'))) { /* It's a relative path with drive letter (ext.g. D:../some/file) * Replace drive letter in dir by full cwd if it points to the same drive, * otherwise use the dir only. */ if (cwd_len < 2 || _wcsnicmp(cwd, dir, 2) != 0) { cwd_len = 0; } else { dir += 2; dir_len -= 2; } } else if (dir_len > 2 && dir[1] == L':') { /* It's an absolute path with drive letter * Don't use the cwd at all */ cwd_len = 0; } /* Allocate buffer for output */ result = result_pos = (WCHAR*)malloc(sizeof(WCHAR) * (cwd_len + 1 + dir_len + 1 + name_len + 1 + ext_len + 1)); /* Copy cwd */ wcsncpy(result_pos, cwd, cwd_len); result_pos += cwd_len; /* Add a path separator if cwd didn't end with one */ if (cwd_len && wcsrchr(L"\\/:", result_pos[-1]) == NULL) { result_pos[0] = L'\\'; result_pos++; } /* Copy dir */ wcsncpy(result_pos, dir, dir_len); result_pos += dir_len; /* Add a separator if the dir didn't end with one */ if (dir_len && wcsrchr(L"\\/:", result_pos[-1]) == NULL) { result_pos[0] = L'\\'; result_pos++; } /* Copy filename */ wcsncpy(result_pos, name, name_len); result_pos += name_len; if (ext_len) { /* Add a dot if the filename didn't end with one */ if (name_len && result_pos[-1] != '.') { result_pos[0] = L'.'; result_pos++; } /* Copy extension */ wcsncpy(result_pos, ext, ext_len); result_pos += ext_len; } /* Null terminator */ result_pos[0] = L'\0'; attrs = GetFileAttributesW(result); if (attrs != INVALID_FILE_ATTRIBUTES && !(attrs & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT))) { return result; } free(result); return NULL; }
DWORD WINAPI FileWatcherThread::run_thread( void *_watcher ) { FileWatcherThread *watcher = (FileWatcherThread*)_watcher; while(watcher->running) { ReadDirectoryChangesW( watcher->handle, watcher->buffer, watcher->buffer_size, TRUE, FILE_NOTIFY_CHANGE_CREATION | FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE, NULL, &watcher->overlap, NULL ); WaitForSingleObject(watcher->overlap.hEvent, INFINITE); int seek = 0; while(seek < watcher->buffer_size) { PFILE_NOTIFY_INFORMATION notifier = PFILE_NOTIFY_INFORMATION(watcher->buffer + seek); WCHAR szwFileName[MAX_PATH]; int ulCount = notifier->FileNameLength/2; wcsncpy(szwFileName, notifier->FileName, ulCount); szwFileName[ulCount] = L'\0'; std::wstring widepath(szwFileName); std::string path(widepath.begin(), widepath.end()); FilewatchEventType _event_type = fe_unknown; switch( notifier->Action ) { case FILE_ACTION_ADDED:{ _event_type = fe_create; break; } case FILE_ACTION_REMOVED:{ _event_type = fe_remove; break; } case FILE_ACTION_MODIFIED:{ _event_type = fe_modify; break; } case FILE_ACTION_RENAMED_OLD_NAME:{ _event_type = fe_remove; break; } case FILE_ACTION_RENAMED_NEW_NAME:{ _event_type = fe_create; break; } } //switch if(_event_type != fe_unknown) { // put into queue snow::io::event_node_t* node = new snow::io::event_node_t; node->path = std::string(watcher->path+"/"+path); node->event_type = (int)_event_type; snow::io::eventqueue_push(&filewatch_queue, node); } seek += notifier->NextEntryOffset; if(notifier->NextEntryOffset == 0) { break; } } //seek < buffer size } //while running return 0; } //run_thread