void stAttachDebugger( DWORD processId, std::string fnIncludes, std::string fnExcludes, bool activeProcess = true) /*++ Routine Description: Our mini-debugger implementation. It does following things: - Attach to a running process - On first breakpoint, inject the IAT patching DLL into target - Print information of any exception in target process - Print the debug spew from target process Arguments: processId - PID of the process to attach fnIncludes - List of include filters fnExclude - List of exclude filters activeProcess - If we are attaching to an already running process then we pass activeProcess = true, this causes us to call DebugActiveProcess and not wait for process creation event --*/ { int threadCount = 0; bool processInfected = false; if (activeProcess) { if (!DebugActiveProcess(processId)) { gView->PrintError(L"\nCould not attach to the process (PID = %d).", processId); stHandleError(GetLastError()); goto funcExit; } } HMODULE hMod = GetModuleHandle(L"Kernel32.dll"); if (hMod) { PFNDEBUGSETPROCESSKILLONEXIT pfnDebugSetProcessKillOnExit = (PFNDEBUGSETPROCESSKILLONEXIT)GetProcAddress(hMod, "DebugSetProcessKillOnExit"); if (pfnDebugSetProcessKillOnExit) { pfnDebugSetProcessKillOnExit(FALSE); } } gProcessId = processId; DEBUG_EVENT debugEvent; DWORD dwContinueStatus = DBG_CONTINUE; bool keepAlive = true; while(keepAlive) { WaitForDebugEvent(&debugEvent, INFINITE); dwContinueStatus = DBG_CONTINUE; if (debugEvent.dwProcessId == processId) { switch (debugEvent.dwDebugEventCode) { case EXCEPTION_DEBUG_EVENT: { switch (debugEvent.u.Exception.ExceptionRecord.ExceptionCode) { case EXCEPTION_BREAKPOINT: { //IHU_DBG_LOG(TRC_STRACE, HX_LEVEL_INFO, (L"EXCEPTION_BREAKPOINT\n")); if (!processInfected) { if (gRemovePatchOnExit) { HRSRC hRes; HGLOBAL hResG; LPVOID pRes; DWORD dwResSize; hRes = FindResource( NULL, MAKEINTRESOURCE(IDR_BIN_DLL), L"BIN"); hResG = LoadResource(NULL, hRes); pRes = LockResource(hResG); dwResSize = SizeofResource(NULL, hRes); wchar_t tempPath[MAX_PATH]; wchar_t tempFile[MAX_PATH]; GetTempPath(MAX_PATH, tempPath); GetTempFileName(tempPath, L"", 0, tempFile); gInjectorDllPath = tempFile; HANDLE oFile = CreateFile( gInjectorDllPath.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (oFile == INVALID_HANDLE_VALUE) { gView->PrintError( L"Failed to create the temporary DLL [%s]. Error code = %x\n", gInjectorDllPath.c_str(), GetLastError()); return; } DWORD bytesWritten; if (!WriteFile( oFile, pRes, dwResSize, &bytesWritten, NULL)) { gView->PrintError( L"Failed to write the temporary DLL. Error code = %x\n", GetLastError()); return; } CloseHandle(oFile); } else { wchar_t exePath[MAX_PATH]; if (GetModuleFileName( NULL, exePath, MAX_PATH)) { std::wstring dllPath = exePath; int slashPos = dllPath.find_last_of(L'\\'); if (slashPos != -1) { dllPath = dllPath.substr(0, slashPos + 1); } dllPath += L"stserum.dll"; gInjectorDllPath = dllPath; } } ihiInjectDll( ghProcess, (LPCWSTR)gInjectorDllPath.c_str(), (LPCSTR)fnIncludes.c_str(), (LPCSTR)fnExcludes.c_str()); processInfected = true; } break; } default: { if (debugEvent.u.Exception.dwFirstChance) { gView->PrintWarning(L"Exception = %x, Address = %x (first-chance!)\n", debugEvent.u.Exception.ExceptionRecord.ExceptionCode, debugEvent.u.Exception.ExceptionRecord.ExceptionAddress); } else { gView->PrintError(L"Exception = %x, Address = %x (second-chance!)\n", debugEvent.u.Exception.ExceptionRecord.ExceptionCode, debugEvent.u.Exception.ExceptionRecord.ExceptionAddress); } // // If this was a second chance exception, it will cause // the process to terminate // dwContinueStatus = DBG_EXCEPTION_NOT_HANDLED; break; } } break; } case CREATE_THREAD_DEBUG_EVENT: { ++threadCount; break; } case CREATE_PROCESS_DEBUG_EVENT: { if (ghProcess == INVALID_HANDLE_VALUE) { ghProcess = debugEvent.u.CreateProcessInfo.hProcess; } //IHU_DBG_LOG(TRC_STRACE, HX_LEVEL_INFO, (L"Create Process\n")); break; } case EXIT_THREAD_DEBUG_EVENT: { --threadCount; break; } case EXIT_PROCESS_DEBUG_EVENT: { gView->PrintMessage( L"Target process has been terminated. Exit Code = %d.\n", debugEvent.u.ExitProcess.dwExitCode); keepAlive = false; break; } case LOAD_DLL_DEBUG_EVENT: { break; } case UNLOAD_DLL_DEBUG_EVENT: { break; } case OUTPUT_DEBUG_STRING_EVENT: { DWORD cbRead = 0; ReadProcessMemory( ghProcess, debugEvent.u.DebugString.lpDebugStringData, gDbgString, debugEvent.u.DebugString.nDebugStringLength, &cbRead); if (debugEvent.u.DebugString.fUnicode) { if (gDbgString[0] == L'$') { gView->PrintTrace(L"%ws", &gDbgString[1]); } else if (gDbgString[0] == L'#') { gView->PrintError(L"%ws", &gDbgString[1]); } else { gView->PrintTraceOrig(L"%ws", gDbgString); } } else { if (gDbgString[0] == L'$') { gView->PrintTraceA("%s", &gDbgString[1]); } else if (gDbgString[0] == L'#') { gView->PrintErrorA("%s", &gDbgString[1]); } else { gView->PrintTraceOrigA("%s", gDbgString); } } break; } } } ContinueDebugEvent( debugEvent.dwProcessId, debugEvent.dwThreadId, dwContinueStatus); } // // If we need to remove the patching on exit, it means we created a // temporary injector dll, we should delete that now // if (gRemovePatchOnExit) { DeleteFile(gInjectorDllPath.c_str()); } //IHU_DBG_LOG(TRC_STRACE, HX_LEVEL_INFO, (L"Total thread count = %d\n", threadCount)); funcExit: return; }
dictionary* INI::LoadIniFile(HINSTANCE hInstance, LPSTR inifile) { dictionary* ini = NULL; // First attempt to load INI from exe HRSRC hi = FindResource(hInstance, MAKEINTRESOURCE(1), RT_INI_FILE); if(hi) { HGLOBAL hg = LoadResource(hInstance, hi); PBYTE pb = (PBYTE) LockResource(hg); DWORD* pd = (DWORD*) pb; if(*pd == INI_RES_MAGIC) { ini = iniparser_load((char *) &pb[RES_MAGIC_SIZE], true); if(!ini) { Log::Warning("Could not load embedded INI file"); } } } // Check if we have already loaded an embedded INI file - if so // then we only need to load and merge the INI file (if present) if(ini && iniparser_getboolean(ini, ALLOW_INI_OVERRIDE, 1)) { dictionary* ini2 = iniparser_load(inifile); if(ini2) { for(int i = 0; i < ini2->n; i++) { char* key = ini2->key[i]; char* value = ini2->val[i]; iniparser_setstr(ini, key, value); } iniparser_freedict(ini2); } } else if(!ini) { ini = iniparser_load(inifile); if(ini == NULL) { Log::Error("Could not load INI file: %s", inifile); return NULL; } } // Expand environment variables ExpandVariables(ini); // Now check if we have an external file to load char* iniFileLocation = iniparser_getstr(ini, INI_FILE_LOCATION); if(iniFileLocation) { Log::Info("Loading INI keys from file location: %s", iniFileLocation); dictionary* ini3 = iniparser_load(iniFileLocation); if(ini3) { for(int i = 0; i < ini3->n; i++) { char* key = ini3->key[i]; char* value = ini3->val[i]; iniparser_setstr(ini, key, value); } iniparser_freedict(ini3); } else { Log::Warning("Could not load INI keys from file: %s", iniFileLocation); } } // Attempt to parse registry location to include keys if present ParseRegistryKeys(ini); iniparser_setstr(ini, MODULE_INI, inifile); // Add module name to ini TCHAR filename[MAX_PATH], filedir[MAX_PATH]; GetModuleFileName(hInstance, filename, MAX_PATH); iniparser_setstr(ini, MODULE_NAME, filename); // strip off filename to get module directory GetFileDirectory(filename, filedir); iniparser_setstr(ini, MODULE_DIR, filedir); // stip off filename to get ini directory GetFileDirectory(inifile, filedir); iniparser_setstr(ini, INI_DIR, filedir); // Log init Log::Init(hInstance, iniparser_getstr(ini, LOG_FILE), iniparser_getstr(ini, LOG_LEVEL), ini); Log::Info("Module Name: %s", filename); Log::Info("Module INI: %s", inifile); Log::Info("Module Dir: %s", filedir); Log::Info("INI Dir: %s", filedir); // Store a reference to be used by JNI functions g_ini = ini; return ini; }
//----------------------------------------------------------------------------- // Name: CWaveFile::Open() // Desc: Opens a wave file for reading //----------------------------------------------------------------------------- HRESULT CWaveFile::Open( LPTSTR strFileName, WAVEFORMATEX* pwfx, DWORD dwFlags ) { HRESULT hr; m_dwFlags = dwFlags; m_bIsReadingFromMemory = FALSE; if( m_dwFlags == WAVEFILE_READ ) { if( strFileName == NULL ) return E_INVALIDARG; SAFE_DELETE_ARRAY( m_pwfx ); m_hmmio = mmioOpen( strFileName, NULL, MMIO_ALLOCBUF | MMIO_READ ); if( NULL == m_hmmio ) { HRSRC hResInfo; HGLOBAL hResData; DWORD dwSize; VOID* pvRes; // Loading it as a file failed, so try it as a resource if( NULL == ( hResInfo = FindResource( NULL, strFileName, TEXT("WAVE") ) ) ) { if( NULL == ( hResInfo = FindResource( NULL, strFileName, TEXT("WAV") ) ) ) return DXTRACE_ERR( TEXT("FindResource"), E_FAIL ); } if( NULL == ( hResData = LoadResource( NULL, hResInfo ) ) ) return DXTRACE_ERR( TEXT("LoadResource"), E_FAIL ); if( 0 == ( dwSize = SizeofResource( NULL, hResInfo ) ) ) return DXTRACE_ERR( TEXT("SizeofResource"), E_FAIL ); if( NULL == ( pvRes = LockResource( hResData ) ) ) return DXTRACE_ERR( TEXT("LockResource"), E_FAIL ); m_pResourceBuffer = new CHAR[ dwSize ]; memcpy( m_pResourceBuffer, pvRes, dwSize ); MMIOINFO mmioInfo; ZeroMemory( &mmioInfo, sizeof(mmioInfo) ); mmioInfo.fccIOProc = FOURCC_MEM; mmioInfo.cchBuffer = dwSize; mmioInfo.pchBuffer = (CHAR*) m_pResourceBuffer; m_hmmio = mmioOpen( NULL, &mmioInfo, MMIO_ALLOCBUF | MMIO_READ ); } if( FAILED( hr = ReadMMIO() ) ) { // ReadMMIO will fail if its an not a wave file mmioClose( m_hmmio, 0 ); return DXTRACE_ERR( TEXT("ReadMMIO"), hr ); } if( FAILED( hr = ResetFile() ) ) return DXTRACE_ERR( TEXT("ResetFile"), hr ); // After the reset, the size of the wav file is m_ck.cksize so store it now m_dwSize = m_ck.cksize; } else { m_hmmio = mmioOpen( strFileName, NULL, MMIO_ALLOCBUF | MMIO_READWRITE | MMIO_CREATE ); if( NULL == m_hmmio ) return DXTRACE_ERR( TEXT("mmioOpen"), E_FAIL ); if( FAILED( hr = WriteMMIO( pwfx ) ) ) { mmioClose( m_hmmio, 0 ); return DXTRACE_ERR( TEXT("WriteMMIO"), hr ); } if( FAILED( hr = ResetFile() ) ) return DXTRACE_ERR( TEXT("ResetFile"), hr ); } return hr; }
Resource::Resource (const TCHAR* name) : hf(0), hr(0) { hf = FindResource(NULL, name, MAKEINTRESOURCE(RT_RCDATA)); if (hf) hr = LoadResource(NULL, hf); }
BOOL CWindowsMetaFile::GetMetaFile(HINSTANCE hInstance, LPCSTR pszResource, LPCSTR pszType, ALDUS_WMF_HEADER* pAldusHeader, METAHEADER* pHeader, HMETAFILE* phMetaFile) { BOOL fSuccess = FALSE; ASSERT(hInstance != NULL); ASSERT(pszResource != NULL); ASSERT(pszType != NULL); HRSRC hrResource; hrResource = FindResource(hInstance, pszResource, pszType); if (hrResource != NULL) { HGLOBAL hResource; hResource = LoadResource(hInstance, hrResource); if (hResource != NULL) { LPBYTE pResource; #ifdef WIN32 DWORD dwGlobalSize = 0; #else DWORD dwGlobalSize = GlobalSize(hResource); #endif pResource = (LPBYTE)LockResource(hResource); if (pResource != NULL) { ASSERT((dwGlobalSize == 0) || (dwGlobalSize >= sizeof(ALDUS_WMF_HEADER)+sizeof(METAHEADER))); if ((dwGlobalSize == 0) || (dwGlobalSize >= sizeof(ALDUS_WMF_HEADER)+sizeof(METAHEADER))) { // Save the Aldus header if the user has requested it. if (pAldusHeader != NULL) { *pAldusHeader = *((ALDUS_WMF_HEADER*)pResource); } // Validate the Aldus header. if (((ALDUS_WMF_HEADER*)pResource)->key == ALDUS_WMF_KEY) { // Save the metafile header if the user has requested it. if (pHeader != NULL) { *pHeader = *((METAHEADER*)(pResource+sizeof(ALDUS_WMF_HEADER))); } // Get the size from the metafile header. DWORD dwSize = ((METAHEADER*)(pResource+sizeof(ALDUS_WMF_HEADER)))->mtSize*2; if (dwGlobalSize != 0 && dwGlobalSize < sizeof(ALDUS_WMF_HEADER)+dwSize) { // This can be cause by the WMF files where mtSize includes the // size of the Aldus header. Attempt to adjust for this by // decreasing mtSize. dwSize -= sizeof(ALDUS_WMF_HEADER); } if (dwSize != 0) { ASSERT((dwGlobalSize == 0) || (dwGlobalSize >= sizeof(ALDUS_WMF_HEADER)+dwSize)); if ((dwGlobalSize == 0) || (dwGlobalSize >= sizeof(ALDUS_WMF_HEADER)+dwSize)) { // If the user wants a metafile handle, continue. // Otherwise, return TRUE. fSuccess = phMetaFile == NULL; if (!fSuccess) { *phMetaFile = NULL; // Allocate the memory to hold the metafile data. HGLOBAL hMetaFileData; hMetaFileData = GlobalAlloc(GMEM_MOVEABLE|GMEM_SHARE, dwSize); if (hMetaFileData != NULL) { LPVOID pMetaFileData; pMetaFileData = GlobalLock(hMetaFileData); if (pMetaFileData != NULL) { // Copy the meta file data from the resource into the new memory block. // We have now read the data, make a metafile from it. #ifdef WIN32 memcpy(pMetaFileData, (LPVOID)(pResource+sizeof(ALDUS_WMF_HEADER)), dwSize); *phMetaFile = ::SetMetaFileBitsEx(dwSize, (LPBYTE)pMetaFileData); GlobalUnlock(hMetaFileData); pMetaFileData = NULL; #else hmemcpy(pMetaFileData, (LPVOID)(pResource+sizeof(ALDUS_WMF_HEADER)), dwSize); *phMetaFile = ::SetMetaFileBits(hMetaFileData); if (*phMetaFile == NULL) { GlobalUnlock(hMetaFileData); pMetaFileData = NULL; } #endif fSuccess = *phMetaFile != NULL; } #ifdef WIN32 GlobalFree(hMetaFileData); hMetaFileData = NULL; #else if (*phMetaFile == NULL) { GlobalFree(hMetaFileData); hMetaFileData = NULL; } #endif } } } } } } GlobalUnlock(hResource); pResource = NULL; } FreeResource(hResource); hResource = NULL; } } return fSuccess; }
int loadIcon32(HGDIOBJ& image, HINSTANCE hInst, LPCTSTR id , int size , int bits, bool preferIcon) { image = 0; HRSRC hr; HGLOBAL hg; int imageType=-1; void * p = 0; if (!hInst) { FILE * file = fopen(id , "rb"); if (!file) goto end; fseek(file , 0 , SEEK_END); int size = ftell(file); rewind(file); if (size < SIZEOF_NEWHEADER) {fclose(file); return 0;} p = malloc(size); fread(p , 1 , size , file); fclose(file); } else { hr = FindResource(hInst , id , RT_GROUP_ICON); if (!hr) goto end; hg = LoadResource(hInst , hr); if (!hg) goto end; p = LockResource(hg); if (!p) goto end; } NEWHEADER * nh = (NEWHEADER *)p; RESDIR * rd; rd = (RESDIR *)((long)p+SIZEOF_NEWHEADER); RESDIR* found = 0; int rsize = 0; int sizev = size; // rozmiar pionowy for (int i = 0; i < nh->ResCount; i++ , rd++) { if (rd->ResInfo.Icon.Width == size || !found) { if (!size) size = rd->ResInfo.Icon.Width; if (rd->BitCount <= bits || !found) { //found = hInst?rd->IconCursorId & 0xFFFF : rd->IconCursorId; found = rd; rsize = rd->BytesInRes; sizev = rd->ResInfo.Icon.Width == rd->ResInfo.Icon.Height ?size : ceilf(float(size / rd->ResInfo.Icon.Width) * rd->ResInfo.Icon.Height); } if (rd->ResInfo.Icon.Width == size && rd->BitCount == bits) break; } if (hInst) rd = (RESDIR*)((char*)rd - 2); // Korygujemy pozycjê... } if (!found) goto end; void * p2 = 0; if (!hInst) { p2 = (char*)p + found->IconCursorId; } else { hr = FindResource(hInst , MAKEINTRESOURCE(found->IconCursorId & 0xFFFF) , RT_ICON); if (!hr) goto end; hg = LoadResource(hInst , hr); // = SizeofResource(hInst , hr); if (!hg || !rsize) goto end; p2 = LockResource(hg); if (!p2) goto end; } if (found->BitCount == 32 && (!isComctl(6,0) || !preferIcon)) { BITMAPV5HEADER bi; BITMAPV5HEADER* _bi = (BITMAPV5HEADER*)p2; ZeroMemory(&bi,sizeof(BITMAPV5HEADER)); bi.bV5Size = sizeof(BITMAPV5HEADER); bi.bV5Width = _bi->bV5Width; bi.bV5Height = _bi->bV5Height / 2; bi.bV5Planes = _bi->bV5Planes; bi.bV5BitCount = 32; bi.bV5Compression = BI_BITFIELDS; bi.bV5RedMask = 0x00FF0000; bi.bV5GreenMask = 0x0000FF00; bi.bV5BlueMask = 0x000000FF; bi.bV5AlphaMask = 0xFF000000; void * bmpData; char* _bmpData = (char*)p2 + _bi->bV5Size; HDC hdc; hdc = GetDC(NULL); // Create the DIB section with an alpha channel. image = (HGDIOBJ)CreateDIBSection(hdc, (BITMAPINFO *)&bi, DIB_RGB_COLORS, (void **)&bmpData, NULL, (DWORD)0); memcpy(bmpData, _bmpData, bi.bV5Width * bi.bV5Height * 4); ReleaseDC(0, hdc); if (found->ResInfo.Icon.Width != size || found->ResInfo.Icon.Height != sizev) { // zmiana rozmiaru } imageType = IMAGE_BITMAP; } else { image = (HGDIOBJ)CreateIconFromResourceEx((PBYTE)p2 , rsize , true , 0x00030000 , size , sizev , 0); imageType = IMAGE_ICON; } end: if (!hInst && p) free(p); return imageType; }
dlgHbaConfig::dlgHbaConfig(pgFrame *parent, pgHbaConfigLine *_line, pgConn *_conn) : DialogWithHelp((frmMain *)parent) { wxWindowBase::SetFont(settings->GetSystemFont()); LoadResource((wxWindow *)parent, wxT("dlgHbaConfig")); conn = _conn; userAdding = databaseAdding = false; // Icon SetIcon(*property_png_ico); RestorePosition(); line = _line; cbType->Append(wxT("local")); cbType->Append(wxT("host")); cbType->Append(wxT("hostssl")); cbType->Append(wxT("hostnossl")); cbDatabase->Append(wxT("all")); cbDatabase->Append(wxT("sameuser")); cbDatabase->Append(wxT("@<filename>")); if (conn) { // role is supported from 8.1 if (conn->BackendMinimumVersion(8, 1)) cbDatabase->Append(wxT("samerole")); else cbDatabase->Append(wxT("samegroup")); // replication is supported from 9.0 if (conn->BackendMinimumVersion(9, 0)) cbDatabase->Append(wxT("replication")); } else { cbDatabase->Append(wxT("samegroup")); cbDatabase->Append(wxT("samerole")); cbDatabase->Append(wxT("replication")); } cbUser->Append(wxT("all")); cbMethod->Append(wxT("trust")); cbMethod->Append(wxT("reject")); cbMethod->Append(wxT("md5")); cbMethod->Append(wxT("password")); cbMethod->Append(wxT("krb4")); cbMethod->Append(wxT("krb5")); cbMethod->Append(wxT("ident")); cbMethod->Append(wxT("pam")); if (conn) { // LDAP is supported from 8.2 if (conn->BackendMinimumVersion(8, 2)) cbMethod->Append(wxT("ldap")); // GSS/SSPI are supported from 8.3 if (conn->BackendMinimumVersion(8, 3)) { cbMethod->Append(wxT("gss")); cbMethod->Append(wxT("sspi")); } // CERT is supported from 8.4 // but crypt is no longer supported in 8.4 if (conn->BackendMinimumVersion(8, 4)) { cbMethod->Append(wxT("cert")); } else { cbMethod->Append(wxT("crypt")); } // Radius is supported from 9.0 if (conn->BackendMinimumVersion(9, 0)) { cbMethod->Append(wxT("radius")); } // Peer is supported from 9.1 if (conn->BackendMinimumVersion(9, 1)) { cbMethod->Append(wxT("peer")); } } else { // Add all version-dependent methods if we don't know what version we have. cbMethod->Append(wxT("ldap")); cbMethod->Append(wxT("gss")); cbMethod->Append(wxT("sspi")); cbMethod->Append(wxT("cert")); cbMethod->Append(wxT("crypt")); cbMethod->Append(wxT("radius")); cbMethod->Append(wxT("peer")); } if (conn) { pgSet *set = conn->ExecuteSet(wxT("SELECT datname FROM pg_database")); if (set) { while (!set->Eof()) { cbDatabase->Append(set->GetVal(0)); set->MoveNext(); } delete set; } wxString sql = wxT("SELECT usename FROM pg_user\n") wxT("UNION\n") wxT("SELECT 'group ' || groname FROM pg_group"); set = conn->ExecuteSet(sql); if (set) { while (!set->Eof()) { cbUser->Append(set->GetVal(0)); set->MoveNext(); } delete set; } } // Setup the default values chkEnabled->SetValue(!line->isComment); if(line->connectType != pgHbaConfigLine::PGC_INVALIDCONF) { database = line->database; user = line->user; cbType->SetSelection(line->connectType); cbMethod->SetSelection(line->method); cbDatabase->SetValue(database); cbUser->SetValue(user); txtIPaddress->SetValue(line->ipaddress); txtOption->SetValue(line->option); } wxCommandEvent noEvent; OnChange(noEvent); }
int CreateMainWindow(HINSTANCE hInstance, HWND hWnd, LPCTSTR name, int cmdbar_height) { HRSRC res; unsigned char *mem; int i; DLGTEMPLATE dlg; DLGITEMTEMPLATE item; RECT rect; int ratio_x, ratio_y; res = FindResource(hInstance, name, RT_DIALOG); if (res == NULL) { debug_printf(TEXT("error=%d\n"), GetLastError()); } mem = (unsigned char*)LockResource(LoadResource(NULL, res)); /* * DLGTEMPLATE structure */ dlg = *(DLGTEMPLATE*)mem; mem += sizeof(DLGTEMPLATE); GetClientRect(hWnd, &rect); rect.top += cmdbar_height; /* get client rect w/o command bar */ ratio_x = (rect.right - rect.left) * 100 / dlg.cx; ratio_y = (rect.bottom - rect.top) * 100 / dlg.cy; /* * menu resource */ if (*(WORD*)mem == 0xffff) { /* predefined menu */ mem += sizeof(WORD); debug_printf(TEXT("Dlg: menu=%04x\n"), *(WORD*)mem); mem += sizeof(WORD); } else if (*(WORD*)mem == 0x0000) { /* no menu */ mem += sizeof(WORD); debug_printf(TEXT("Dlg: menu=none\n")); } else { /* menu resource name */ debug_printf(TEXT("Dlg: menu=%s\n"), (TCHAR*)mem); while (*(WORD*)mem) { /* zero terminated */ mem += sizeof(WORD); } mem += sizeof(WORD); } /* * window class */ if (*(WORD*)mem == 0xffff) { /* predefined class */ mem += sizeof(WORD); debug_printf(TEXT("Dlg: class=%04x\n"), *(WORD*)mem); mem += sizeof(WORD); } else if (*(WORD*)mem == 0x0000) { /* default class */ mem += sizeof(WORD); debug_printf(TEXT("Dlg: class=none\n")); } else { /* class name */ debug_printf(TEXT("Dlg: class=%s\n"), (TCHAR*)mem); while (*(WORD*)mem) { /* zero terminated */ mem += sizeof(WORD); } mem += sizeof(WORD); } /* * window title */ debug_printf(TEXT("Dlg: title=%s\n"), (TCHAR*)mem); while (*(WORD*)mem) { /* zero terminated */ mem += sizeof(WORD); } mem += sizeof(WORD); if (dlg.style & DS_SETFONT) { /* font size */ debug_printf(TEXT("Dlg: font size=%d\n"), *(WORD*)mem); mem += sizeof(WORD); /* font name */ debug_printf(TEXT("Dlg: font name=%s ("), (TCHAR*)mem); while (*(WORD*)mem) { /* zero terminated */ debug_printf(TEXT("%04x"), *(WORD*)mem); mem += sizeof(WORD); } debug_printf(TEXT(")\n")); mem += sizeof(WORD); } /* * for each control */ for (i = 0; i < dlg.cdit; i++) { TCHAR *class_name = NULL; TCHAR *window_text = NULL; /* DWORD alignment */ if ((long)mem % sizeof(DWORD)) { mem = (unsigned char*)(((long)mem / sizeof(DWORD) + 1) * sizeof(DWORD)); } /* * DLGITEMTEMPLATE structure */ item = *(DLGITEMTEMPLATE*)mem; mem += sizeof(DLGITEMTEMPLATE); /* * control class */ if (*(WORD*)mem == 0xffff) { /* predefined system class */ mem += sizeof(WORD); switch (*(WORD*)mem) { case 0x0080: class_name = TEXT("BUTTON"); break; case 0x0081: class_name = TEXT("EDIT"); break; case 0x0082: class_name = TEXT("STATIC"); break; case 0x0083: class_name = TEXT("LISTBOX"); break; case 0x0084: class_name = TEXT("SCROLLBAR"); break; case 0x0085: class_name = TEXT("COMBOBOX"); break; default: debug_printf(TEXT("class=%04x "), *(WORD*)mem); break; } mem += sizeof(WORD); } else { /* class name */ class_name = (TCHAR*)mem; while (*(WORD*)mem) { /* zero terminated */ mem += sizeof(WORD); } mem += sizeof(WORD); } /* * window contents */ if (*(WORD*)mem == 0xffff) { /* resource */ mem += sizeof(WORD); debug_printf(TEXT("contents=%04x "), *(WORD*)mem); mem += sizeof(WORD); } else { /* text */ window_text = (TCHAR*)mem; while (*(WORD*)mem) { /* zero terminated */ mem += sizeof(WORD); } mem += sizeof(WORD); } if (item.id == 0xffff) { item.id = i + 1; } if (class_name) { debug_printf(TEXT("Control: %04x "), item.id); debug_printf(TEXT("class=%s "), class_name); debug_printf(TEXT("contents=%s "), window_text ? window_text : TEXT("")); CreateWindowEx( item.dwExtendedStyle, class_name, // Class window_text, // Title item.style, // Style item.x * ratio_x / 100, item.y * ratio_y / 100 + cmdbar_height, item.cx * ratio_x / 100, item.cy * ratio_y / 100, hWnd, // Parent handle (HMENU)item.id, // Control ID hInstance, // Instance handle NULL); // Creation } #if 0 /* DWORD alignment */ if ((long)mem % sizeof(DWORD)) { //mem = (unsigned char*)(((long)mem / sizeof(DWORD) + 1) * sizeof(DWORD)); } #endif /* * creation data */ debug_printf(TEXT("data=0x%x bytes\n"), *(WORD*)mem); mem += *(WORD*)mem; mem += sizeof(WORD); } return (0); }
BOOL APIENTRY GuiDlgAbout::DlgProc(HWND hwndDlg, UINT message, WPARAM wParam, LPARAM lParam) { #ifdef DEBUG //printf("GuiDlgAbout::DlgProc(): Message 0x%08X received.\n",message); #endif BYTE *logo = (BYTE *)LockResource(LoadResource(myInstance,FindResource(myInstance,MAKEINTRESOURCE(IDB_LOGO),RT_BITMAP))); char *license = (char *)LockResource(LoadResource(myInstance,FindResource(myInstance,MAKEINTRESOURCE(IDR_TEXT_LICENSE),"TEXT"))); char *history = (char *)LockResource(LoadResource(myInstance,FindResource(myInstance,MAKEINTRESOURCE(IDR_TEXT_HISTORY),"TEXT"))); TCITEM tci; switch (message) { case WM_INITDIALOG: tab_hwnd = NULL; // init tab control tci.mask = TCIF_TEXT; tci.pszText = " General "; SendDlgItemMessage(hwndDlg,IDC_ATABS,TCM_INSERTITEM,0,(LPARAM)&tci); tci.pszText = " License "; SendDlgItemMessage(hwndDlg,IDC_ATABS,TCM_INSERTITEM,1,(LPARAM)&tci); tci.pszText = " What's New "; SendDlgItemMessage(hwndDlg,IDC_ATABS,TCM_INSERTITEM,2,(LPARAM)&tci); // set default tab index SendDlgItemMessage(hwndDlg,IDC_ATABS,TCM_SETCURSEL,0,0); case WM_SYSCOLORCHANGE: case WM_UPDATE: // delete old tab window if (tab_hwnd) { DestroyWindow(tab_hwnd); tab_hwnd = NULL; } // display new tab window tab_index = (int)SendDlgItemMessage(hwndDlg,IDC_ATABS,TCM_GETCURSEL,0,0); switch (tab_index) { case 0: // fix logo *(DWORD *)&logo[0x28 + (logo[0x428] << 2)] = REVERSE(GetSysColor(COLOR_BTNFACE)); tab_hwnd = CreateDialogParam(myInstance,MAKEINTRESOURCE(IDD_ABT_ADPLUG),GetDlgItem(hwndDlg,IDC_ATABWND),(DLGPROC)TabDlgProc_Wrapper,(LPARAM)this); // plugin SetDlgItemText(tab_hwnd,IDC_PLUGIN_VER,PLUGIN_VER " (" __DATE__ /*" " __TIME__ */")"); break; case 1: tab_hwnd = CreateDialogParam(myInstance,MAKEINTRESOURCE(IDD_ABT_LICENSE),GetDlgItem(hwndDlg,IDC_ATABWND),(DLGPROC)TabDlgProc_Wrapper,(LPARAM)this); // license SetDlgItemText(tab_hwnd,IDC_LICENSE,license); break; case 2: tab_hwnd = CreateDialogParam(myInstance,MAKEINTRESOURCE(IDD_ABT_HISTORY),GetDlgItem(hwndDlg,IDC_ATABWND),(DLGPROC)TabDlgProc_Wrapper,(LPARAM)this); // history SetDlgItemText(tab_hwnd,IDC_HISTORY,history); break; } return FALSE; case WM_NOTIFY: switch (((NMHDR *)lParam)->code) { case TCN_SELCHANGE: PostMessage(hwndDlg,WM_UPDATE,0,0); return FALSE; } case WM_COMMAND: switch (LOWORD(wParam)) { case IDCANCEL: EndDialog(hwndDlg,wParam); return 0; } } return FALSE; }
/// \brief /// Create or return an existing prefab type with the passed filename. inline VPrefab *LoadPrefab(const char *szFilename) {return (VPrefab *)LoadResource(szFilename);}
dlgSearchObject::dlgSearchObject(frmMain *p, pgDatabase *db) { parent = p; header = wxT(""); currentdb = db; wxWindowBase::SetFont(settings->GetSystemFont()); LoadResource(p, wxT("dlgSearchObject")); // Icon appearanceFactory->SetIcons(this); RestorePosition(); btnSearch->Disable(); lcResults->InsertColumn(0, _("Type")); lcResults->InsertColumn(1, _("Name")); lcResults->InsertColumn(2, _("Path")); // Mapping table between local language and english, // because in SQL we're using only english and translate it later // to the local language. aMap[_("All types")] = wxT("All types"); aMap[_("Schemas")] = wxT("Schemas"); aMap[_("Tables")] = wxT("Tables"); aMap[_("Columns")] = wxT("Columns"); aMap[_("Triggers")] = wxT("Triggers"); aMap[_("Views")] = wxT("Views"); aMap[_("Rules")] = wxT("Rules"); aMap[_("Indexes")] = wxT("Indexes"); aMap[_("Functions")] = wxT("Functions"); aMap[_("Aggregates")] = wxT("Aggregates"); aMap[_("Trigger Functions")] = wxT("Trigger Functions"); aMap[_("Constraints")] = wxT("Constraints"); aMap[_("Sequences")] = wxT("Sequences"); aMap[_("Types")] = wxT("Types"); aMap[_("Domains")] = wxT("Domains"); aMap[_("Languages")] = wxT("Languages"); aMap[_("Conversions")] = wxT("Conversions"); aMap[_("Casts")] = wxT("Casts"); aMap[_("Login Roles")] = wxT("Login Roles"); aMap[_("Group Roles")] = wxT("Group Roles"); aMap[_("FTS Configurations")] = wxT("FTS Configurations"); aMap[_("FTS Dictionaries")] = wxT("FTS Dictionaries"); aMap[_("FTS Parsers")] = wxT("FTS Parsers"); aMap[_("FTS Templates")] = wxT("FTS Templates"); aMap[_("Foreign Data Wrappers")] = wxT("Foreign Data Wrappers"); aMap[_("Foreign Servers")] = wxT("Foreign Servers"); aMap[_("Foreign Tables")] = wxT("Foreign Tables"); aMap[_("User Mappings")] = wxT("User Mappings"); aMap[_("Operators")] = wxT("Operators"); aMap[_("Operator Classes")] = wxT("Operator Classes"); aMap[_("Operator Families")] = wxT("Operator Families"); aMap[_("Extensions")] = wxT("Extensions"); aMap[_("Collations")] = wxT("Collations"); cbType->Clear(); cbType->Append(_("All types")); cbType->Append(_("Schemas")); cbType->Append(_("Tables")); cbType->Append(_("Columns")); cbType->Append(_("Triggers")); cbType->Append(_("Views")); cbType->Append(_("Rules")); cbType->Append(_("Indexes")); cbType->Append(_("Functions")); cbType->Append(_("Aggregates")); cbType->Append(_("Trigger Functions")); cbType->Append(_("Constraints")); cbType->Append(_("Sequences")); cbType->Append(_("Types")); cbType->Append(_("Languages")); cbType->Append(_("Domains")); cbType->Append(_("Conversions")); cbType->Append(_("Casts")); cbType->Append(_("Login Roles")); cbType->Append(_("Group Roles")); cbType->Append(_("FTS Configurations")); cbType->Append(_("FTS Dictionaries")); cbType->Append(_("FTS Parsers")); cbType->Append(_("FTS Templates")); if(currentdb->BackendMinimumVersion(8, 4)) { cbType->Append(_("Foreign Data Wrappers")); cbType->Append(_("Foreign Servers")); cbType->Append(_("User Mappings")); } if(currentdb->BackendMinimumVersion(9, 1)) { cbType->Append(_("Foreign Tables")); } cbType->Append(_("Operators")); cbType->Append(_("Operator Classes")); cbType->Append(_("Operator Families")); if(currentdb->BackendMinimumVersion(9, 1)) { cbType->Append(_("Extensions")); cbType->Append(_("Collations")); } cbType->SetSelection(0); txtPattern->SetFocus(); }
HBITMAP LoadImageFromResources( _In_ UINT Width, _In_ UINT Height, _In_ PCWSTR Name ) { UINT width = 0; UINT height = 0; UINT frameCount = 0; BOOLEAN isSuccess = FALSE; ULONG resourceLength = 0; HGLOBAL resourceHandle = NULL; HRSRC resourceHandleSource = NULL; WICInProcPointer resourceBuffer = NULL; BITMAPINFO bitmapInfo = { 0 }; HBITMAP bitmapHandle = NULL; PBYTE bitmapBuffer = NULL; IWICStream* wicStream = NULL; IWICBitmapSource* wicBitmapSource = NULL; IWICBitmapDecoder* wicDecoder = NULL; IWICBitmapFrameDecode* wicFrame = NULL; IWICImagingFactory* wicFactory = NULL; IWICBitmapScaler* wicScaler = NULL; WICPixelFormatGUID pixelFormat; WICRect rect = { 0, 0, Width, Height }; __try { // Create the ImagingFactory if (FAILED(CoCreateInstance(&CLSID_WICImagingFactory1, NULL, CLSCTX_INPROC_SERVER, &IID_IWICImagingFactory, &wicFactory))) __leave; // Find the resource if ((resourceHandleSource = FindResource(PluginInstance->DllBase, Name, L"PNG")) == NULL) __leave; // Get the resource length resourceLength = SizeofResource(PluginInstance->DllBase, resourceHandleSource); // Load the resource if ((resourceHandle = LoadResource(PluginInstance->DllBase, resourceHandleSource)) == NULL) __leave; if ((resourceBuffer = (WICInProcPointer)LockResource(resourceHandle)) == NULL) __leave; // Create the Stream if (FAILED(IWICImagingFactory_CreateStream(wicFactory, &wicStream))) __leave; // Initialize the Stream from Memory if (FAILED(IWICStream_InitializeFromMemory(wicStream, resourceBuffer, resourceLength))) __leave; if (FAILED(IWICImagingFactory_CreateDecoder(wicFactory, &GUID_ContainerFormatPng, NULL, &wicDecoder))) __leave; if (FAILED(IWICBitmapDecoder_Initialize(wicDecoder, (IStream*)wicStream, WICDecodeMetadataCacheOnLoad))) __leave; // Get the Frame count if (FAILED(IWICBitmapDecoder_GetFrameCount(wicDecoder, &frameCount)) || frameCount < 1) __leave; // Get the Frame if (FAILED(IWICBitmapDecoder_GetFrame(wicDecoder, 0, &wicFrame))) __leave; // Get the WicFrame image format if (FAILED(IWICBitmapFrameDecode_GetPixelFormat(wicFrame, &pixelFormat))) __leave; // Check if the image format is supported: if (IsEqualGUID(&pixelFormat, &GUID_WICPixelFormat32bppPBGRA)) // GUID_WICPixelFormat32bppRGB { wicBitmapSource = (IWICBitmapSource*)wicFrame; } else { // Convert the image to the correct format: if (FAILED(WICConvertBitmapSource(&GUID_WICPixelFormat32bppPBGRA, (IWICBitmapSource*)wicFrame, &wicBitmapSource))) __leave; IWICBitmapFrameDecode_Release(wicFrame); } bitmapInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bitmapInfo.bmiHeader.biWidth = rect.Width; bitmapInfo.bmiHeader.biHeight = -((LONG)rect.Height); bitmapInfo.bmiHeader.biPlanes = 1; bitmapInfo.bmiHeader.biBitCount = 32; bitmapInfo.bmiHeader.biCompression = BI_RGB; HDC hdc = CreateCompatibleDC(NULL); bitmapHandle = CreateDIBSection(hdc, &bitmapInfo, DIB_RGB_COLORS, (PVOID*)&bitmapBuffer, NULL, 0); ReleaseDC(NULL, hdc); // Check if it's the same rect as the requested size. //if (width != rect.Width || height != rect.Height) if (FAILED(IWICImagingFactory_CreateBitmapScaler(wicFactory, &wicScaler))) __leave; if (FAILED(IWICBitmapScaler_Initialize(wicScaler, wicBitmapSource, rect.Width, rect.Height, WICBitmapInterpolationModeFant))) __leave; if (FAILED(IWICBitmapScaler_CopyPixels(wicScaler, &rect, rect.Width * 4, rect.Width * rect.Height * 4, bitmapBuffer))) __leave; isSuccess = TRUE; } __finally { if (wicScaler) { IWICBitmapScaler_Release(wicScaler); } if (wicBitmapSource) { IWICBitmapSource_Release(wicBitmapSource); } if (wicStream) { IWICStream_Release(wicStream); } if (wicDecoder) { IWICBitmapDecoder_Release(wicDecoder); } if (wicFactory) { IWICImagingFactory_Release(wicFactory); } if (resourceHandle) { FreeResource(resourceHandle); } } return bitmapHandle; }
static void test_initial_focus(void) { /* Test 1: * This test intentionally returns FALSE in response to WM_INITDIALOG * without setting focus to a control. This is not allowed according to * MSDN, but it is exactly what MFC's CFormView does. * * Since the WM_INITDIALOG handler returns FALSE without setting the focus, * the focus should initially be NULL. Later, when we manually set focus to * the dialog, the default handler should set focus to the first control that * is "visible, not disabled, and has the WS_TABSTOP style" (MSDN). Because the * second radio button has been checked, it should be the first control * that meets these criteria and should receive the focus. */ g_bInitialFocusInitDlgResult = FALSE; g_hwndInitialFocusT1 = (HWND) -1; g_hwndInitialFocusT2 = (HWND) -1; g_styleInitialFocusT1 = -1; g_styleInitialFocusT2 = -1; DialogBoxA(g_hinst, "RADIO_TEST_DIALOG", NULL, delayFocusDlgWinProc); ok (((g_styleInitialFocusT1 & WS_TABSTOP) == 0), "Error in wrc - Detected WS_TABSTOP as default style for GROUPBOX\n"); ok (((g_styleInitialFocusT2 & WS_VISIBLE) == 0), "Modal dialogs should not be shown until the message queue first goes empty\n"); ok ((g_hwndInitialFocusT1 == NULL), "Error in initial focus when WM_INITDIALOG returned FALSE: " "Expected NULL focus, got %s (%p).\n", GetHwndString(g_hwndInitialFocusT1), g_hwndInitialFocusT1); ok ((g_hwndInitialFocusT2 == g_hwndButton2), "Error after first SetFocus() when WM_INITDIALOG returned FALSE: " "Expected the second button (%p), got %s (%p).\n", g_hwndButton2, GetHwndString(g_hwndInitialFocusT2), g_hwndInitialFocusT2); /* Test 2: * This is the same as above, except WM_INITDIALOG is made to return TRUE. * This should cause the focus to go to the second radio button right away * and stay there (until the user indicates otherwise). */ g_bInitialFocusInitDlgResult = TRUE; g_hwndInitialFocusT1 = (HWND) -1; g_hwndInitialFocusT2 = (HWND) -1; g_styleInitialFocusT1 = -1; g_styleInitialFocusT2 = -1; DialogBoxA(g_hinst, "RADIO_TEST_DIALOG", NULL, delayFocusDlgWinProc); ok ((g_hwndInitialFocusT1 == g_hwndButton2), "Error in initial focus when WM_INITDIALOG returned TRUE: " "Expected the second button (%p), got %s (%p).\n", g_hwndButton2, GetHwndString(g_hwndInitialFocusT1), g_hwndInitialFocusT1); ok ((g_hwndInitialFocusT2 == g_hwndButton2), "Error after first SetFocus() when WM_INITDIALOG returned TRUE: " "Expected the second button (%p), got %s (%p).\n", g_hwndButton2, GetHwndString(g_hwndInitialFocusT2), g_hwndInitialFocusT2); /* Test 3: * If the dialog has DS_CONTROL and it's not visible then we shouldn't change focus */ { HWND hDlg; HRSRC hResource; HANDLE hTemplate; DLGTEMPLATE* pTemplate; hResource = FindResourceA(g_hinst,"FOCUS_TEST_DIALOG", RT_DIALOG); hTemplate = LoadResource(g_hinst, hResource); pTemplate = LockResource(hTemplate); g_hwndInitialFocusT1 = 0; hDlg = CreateDialogIndirectParamA(g_hinst, pTemplate, NULL, focusDlgWinProc, 0); ok (hDlg != 0, "Failed to create test dialog.\n"); ok ((g_hwndInitialFocusT1 == 0), "Focus should not be set for an invisible DS_CONTROL dialog %p.\n", g_hwndInitialFocusT1); DestroyWindow(hDlg); } }
/*! @brief このメソッドは WM_INITDIALOG のメッセージに応答して呼び出されます。 */ BOOL CInspectUsefulToolsDlg::OnInitDialog() { CDialog::OnInitDialog(); // このダイアログのアイコンを設定します。アプリケーションのメイン ウィンドウがダイアログでない場合、 // Framework は、この設定を自動的に行います。 SetIcon(m_hIcon, TRUE); // 大きいアイコンの設定 //SetIcon(m_hIcon, FALSE); // 小さいアイコンの設定 // メニューの初期化 InitializeMenuTree(); InitializeContents(); // タイトルの設定 CString strAppName = CString((LPCTSTR)IDS_APP_NAME); this->SetWindowText(strAppName); CLSID clsid; if (CLSIDFromProgID(OLESTR("Excel.Application"), &clsid) == NOERROR){ // Excel がインストールされている LPUNKNOWN lpUnk; HRESULT hr; LPDISPATCH lpDispatch; BOOL bOpenExcel = FALSE; if (GetActiveObject(clsid, NULL, &lpUnk) == NOERROR){ hr = lpUnk->QueryInterface(IID_IDispatch, (LPVOID*)&lpDispatch); lpUnk->Release(); if (hr == NOERROR) { //すでにExcelが起動されている状態であればAttachDispatch m_inXLApp.AttachDispatch(lpDispatch,TRUE); bOpenExcel = TRUE; } } if (m_inXLApp.m_lpDispatch == NULL) { bOpenExcel = m_inXLApp.CreateDispatch(clsid); m_bOpenXL = TRUE; } if (bOpenExcel == TRUE) { // Excelファイルの初期化 CWorkbooks inWorkbooks = m_inXLApp.get_Workbooks(); COleVariant varNull; varNull.ChangeType(VT_NULL); HRSRC hrSrc = FindResource(AfxGetApp()->m_hInstance, MAKEINTRESOURCE(IDR_MACRO_EXCEL_RCDATA), RT_RCDATA); if (hrSrc != NULL) { HGLOBAL hGlobal = LoadResource(AfxGetApp()->m_hInstance, hrSrc); if (hGlobal != NULL) { char *rcData = (char *)LockResource(hGlobal); /* リソースサイズの取得 */ DWORD dwSize = SizeofResource(AfxGetApp()->m_hInstance, hrSrc); TCHAR szFilePath[MAX_PATH]; GetTempPath(MAX_PATH, szFilePath); TCHAR szFileName[MAX_PATH]; GetTempFileName(szFilePath, _T("SubTools_"), 0, szFileName); CFile inFile; inFile.Open(szFileName, CFile::modeWrite); inFile.Write(rcData, dwSize); inFile.Close(); strTempFilePath = szFileName; m_inXLBook = inWorkbooks.Open(szFileName , varNull, varNull, varNull, varNull, varNull, varNull, varNull, varNull, varNull, varNull, varNull, varNull,varNull, varNull); m_bOpenBook = TRUE; } } } } return TRUE; }
CSize CPopupWnd::GetContentDlgSize( CDialog* pDlg, UINT nID ) { CSize sizeDlg; typedef struct { WORD dlgVer; WORD signature; DWORD helpID; DWORD exStyle; DWORD style; WORD cDlgItems; short x; short y; short cx; short cy; // 后面的属性不能直接用,要根据具体的情况分析,是变长结构 // ... } DLGTEMPLATEEX; // LPCTSTR lpszName = MAKEINTRESOURCE( nID ); HINSTANCE hInstance = AfxFindResourceHandle( lpszName, RT_DIALOG ); HRSRC hResource = ::FindResource( hInstance, lpszName, RT_DIALOG ); HGLOBAL hTemplate = LoadResource( hInstance, hResource); DLGTEMPLATE* pTemplate; WORD *pDlgTemplateTemp = NULL; int nPageWidth = 0; int nPageHeight = 0; pTemplate = (DLGTEMPLATE*)(LPCDLGTEMPLATE)LockResource(hTemplate); // 判断是哪一种 dlg 模板 pDlgTemplateTemp = (WORD*)pTemplate; if ( pDlgTemplateTemp[1] == 0xFFFF ) { // 扩展模板 DLGTEMPLATEEX *pTemplateEx = (DLGTEMPLATEEX*)pTemplate; nPageWidth = pTemplateEx->cx; nPageHeight = pTemplateEx->cy; } else { nPageWidth = pTemplate->cx; nPageHeight = pTemplate->cy; } // UnlockResource(hTemplate); // dialog模板使用的是 dialog unit, 需要转换成 pixel unit CRect rectTemp( 0, 0, nPageWidth, nPageHeight); ::MapDialogRect( pDlg->GetSafeHwnd(), &rectTemp ); sizeDlg.cx = rectTemp.Width(); sizeDlg.cy = rectTemp.Height(); // return sizeDlg; }
ResourceManager::ResourceManager(std::string category, int propsId, int jarId, int jniId) { m_resourceCategory = category; m_resourcePropsId = propsId; m_resourceJarId = jarId; // // Load the Properties // DEBUG("Initialize properties..."); std::string propsidstr = this->idToResourceName(propsId); HRSRC resprop = FindResource(NULL, propsidstr.c_str(), category.c_str()); if (resprop != NULL) { int mainsize = 0; mainsize = SizeofResource(NULL, resprop); // char mainbuf[mainsize+1]; HGLOBAL main = LoadResource(NULL, resprop); m_props.setData((const char*)main, mainsize); } else { m_lastError = "Can't find resource 'main name'"; return; } // // Split the arguments // m_arguments = StringUtils::split(getProperty(KEY_ARGUMENTS, ""), " \t\n\r", "\"\'"); // // loads the jar information // std::string jaridstr = this->idToResourceName(jarId); HRSRC resjar = FindResource(NULL, jaridstr.c_str(), category.c_str()); if (resjar != NULL) { m_jarSize = SizeofResource(NULL, resjar); m_jarHandler = LoadResource(NULL, resjar); } else { m_lastError = "Can't find JAR resource!"; return; } m_jnismoothSize = this->getResourceSize(jniId); m_jnismoothHandler = this->getResource(jniId); // // Extract the java properties from the Property // std::string jpropcountstr = m_props.get("javapropertiescount"); string exepath = FileUtils::getExecutablePath(); string exename = FileUtils::getExecutableFileName(); string computername = FileUtils::getComputerName(); int jpropcount = StringUtils::parseInt(jpropcountstr); DEBUG("Number of Java Parameters: "+jpropcountstr); for (int i=0; i<jpropcount; i++) { string namekey = string("javaproperty_name_") + StringUtils::toString(i); string valuekey = string("javaproperty_value_") + StringUtils::toString(i); string name = m_props.get(namekey); string value = m_props.get(valuekey); DEBUG("Setting up java properties SOURCE: " + name + "=" + value + " : property if exist: " +getProperty(name,"")); value = StringUtils::replaceEnvironmentVariable(value); value = StringUtils::replace(value, "${EXECUTABLEPATH}", exepath); value = StringUtils::replace(value, "${EXECUTABLENAME}", exename); value = StringUtils::replace(value, "${COMPUTERNAME}", computername); JavaProperty jprop(name, value); m_javaProperties.push_back(jprop); DEBUG("Setting up java properties DESTINATION: " + name + "=" + value); } std::string curdirmodifier = m_props.get(ResourceManager::KEY_CURRENTDIR); if (curdirmodifier.length()>0) { int pos = string::npos; if ( (pos=curdirmodifier.find("${EXECUTABLEPATH}")) != string::npos) { m_currentDirectory = FileUtils::concFile(exepath, curdirmodifier.substr(pos + string("${EXECUTABLEPATH}").size())); // m_currentDirectory = StringUtils::replace(curdirmodifier, "${EXECUTABLEPATH}", exepath); } else { DEBUG(string("Currentdirectory =") + curdirmodifier); m_currentDirectory = curdirmodifier; // m_currentDirectory = FileUtils::concFile(FileUtils::getExecutablePath(), curdirmodifier); m_currentDirectory = StringUtils::replaceEnvironmentVariable(m_currentDirectory); } } else { m_currentDirectory = ""; } // printf("CURDIR SET TO: [%s]\n", m_currentDirectory.c_str()); }
void CWebServer::OnRequest(CWebClientSocket* pClient, CStringA& hdr, CStringA& body) { CPath p(AToT(pClient->m_path)); CStringA ext = p.GetExtension().MakeLower(); CStringA mime; if (ext.IsEmpty()) { mime = "text/html"; } else { m_mimes.Lookup(ext, mime); } hdr = "HTTP/1.0 200 OK\r\n"; bool fHandled = false, fCGI = false; if (!fHandled && m_webroot.IsDirectory()) { CStringA tmphdr; fHandled = fCGI = CallCGI(pClient, tmphdr, body, mime); if (fHandled) { tmphdr.Replace("\r\n", "\n"); CAtlList<CStringA> hdrlines; ExplodeMin(tmphdr, hdrlines, '\n'); POSITION pos = hdrlines.GetHeadPosition(); while (pos) { POSITION cur = pos; CAtlList<CStringA> sl; CStringA key = Explode(hdrlines.GetNext(pos), sl, ':', 2); if (sl.GetCount() < 2) { continue; } key.Trim().MakeLower(); if (key == "content-type") { mime = sl.GetTail().Trim(); hdrlines.RemoveAt(cur); } else if (key == "content-length") { hdrlines.RemoveAt(cur); } } tmphdr = Implode(hdrlines, "\r\n"); hdr += tmphdr + "\r\n"; } } RequestHandler rh = NULL; if (!fHandled && m_internalpages.Lookup(pClient->m_path, rh) && (pClient->*rh)(hdr, body, mime)) { if (mime.IsEmpty()) { mime = "text/html"; } CString redir; if (pClient->m_get.Lookup("redir", redir) || pClient->m_post.Lookup("redir", redir)) { if (redir.IsEmpty()) { redir = '/'; } hdr = "HTTP/1.0 302 Found\r\n" "Location: " + CStringA(redir) + "\r\n"; return; } fHandled = true; } if (!fHandled && m_webroot.IsDirectory()) { fHandled = LoadPage(0, body, UTF8To16(pClient->m_path)); } UINT resid; if (!fHandled && m_downloads.Lookup(pClient->m_path, resid) && (LoadResource(resid, body, _T("FILE")) || LoadResource(resid, body, _T("PNG")))) { if (mime.IsEmpty()) { mime = "application/octet-stream"; } fHandled = true; } if (!fHandled) { hdr = mime == "text/html" ? "HTTP/1.0 301 Moved Permanently\r\n" "Location: /404.html\r\n" : "HTTP/1.0 404 Not Found\r\n"; return; } if ((mime == "text/html" || mime == "text/javascript") && !fCGI) { if (mime == "text/html") { hdr += "Expires: Thu, 19 Nov 1981 08:52:00 GMT\r\n" "Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0\r\n" "Pragma: no-cache\r\n"; CStringA debug; if (AfxGetAppSettings().fWebServerPrintDebugInfo) { debug += "<br><hr>\r\n"; debug += "<div id=\"debug\">"; CStringA key; POSITION pos; { CStringA value; pos = pClient->m_hdrlines.GetStartPosition(); while (pos) { pClient->m_hdrlines.GetNextAssoc(pos, key, value); debug += "HEADER[" + key + "] = " + value + "\r\n"; } } debug += "cmd: " + pClient->m_cmd + "\r\n"; debug += "path: " + pClient->m_path + "\r\n"; debug += "ver: " + pClient->m_ver + "\r\n"; { CString value; pos = pClient->m_get.GetStartPosition(); while (pos) { pClient->m_get.GetNextAssoc(pos, key, value); debug += "GET[" + HtmlSpecialChars(key) + "] = " + HtmlSpecialChars(UTF8(value)) + "\r\n"; } pos = pClient->m_post.GetStartPosition(); while (pos) { pClient->m_post.GetNextAssoc(pos, key, value); debug += "POST[" + HtmlSpecialChars(key) + "] = " + HtmlSpecialChars(UTF8(value)) + "\r\n"; } pos = pClient->m_cookie.GetStartPosition(); while (pos) { pClient->m_cookie.GetNextAssoc(pos, key, value); debug += "COOKIE[" + HtmlSpecialChars(key) + "] = " + HtmlSpecialChars(UTF8(value)) + "\r\n"; } pos = pClient->m_request.GetStartPosition(); while (pos) { pClient->m_request.GetNextAssoc(pos, key, value); debug += "REQUEST[" + HtmlSpecialChars(key) + "] = " + HtmlSpecialChars(UTF8(value)) + "\r\n"; } } debug += "</div>"; } body.Replace("[debug]", debug); } body.Replace("[browserpath]", "/browser.html"); body.Replace("[commandpath]", "/command.html"); body.Replace("[controlspath]", "/controls.html"); body.Replace("[indexpath]", "/index.html"); body.Replace("[path]", pClient->m_path); body.Replace("[setposcommand]", CMD_SETPOS); body.Replace("[setvolumecommand]", CMD_SETVOLUME); body.Replace("[wmcname]", "wm_command"); // TODO: add more general tags to replace } // gzip if (AfxGetAppSettings().fWebServerUseCompression && !body.IsEmpty() && hdr.Find("Content-Encoding:") < 0 && ext != ".png" && ext != ".jpeg" && ext != ".gif") do { CStringA accept_encoding; pClient->m_hdrlines.Lookup("accept-encoding", accept_encoding); accept_encoding.MakeLower(); CAtlList<CStringA> sl; ExplodeMin(accept_encoding, sl, ','); if (!sl.Find("gzip")) { break; } // Allocate deflate state z_stream strm; strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; int ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 15 + 16, 8, Z_DEFAULT_STRATEGY); if (ret != Z_OK) { ASSERT(0); break; } int gzippedBuffLen = body.GetLength(); BYTE* gzippedBuff = DEBUG_NEW BYTE[gzippedBuffLen]; // Compress strm.avail_in = body.GetLength(); strm.next_in = (Bytef*)(LPCSTR)body; strm.avail_out = gzippedBuffLen; strm.next_out = gzippedBuff; ret = deflate(&strm, Z_FINISH); if (ret != Z_STREAM_END || strm.avail_in != 0) { ASSERT(0); deflateEnd(&strm); delete [] gzippedBuff; break; } gzippedBuffLen -= strm.avail_out; memcpy(body.GetBufferSetLength(gzippedBuffLen), gzippedBuff, gzippedBuffLen); // Clean up deflateEnd(&strm); delete [] gzippedBuff; hdr += "Content-Encoding: gzip\r\n"; } while (0); CStringA content; content.Format( "Content-Type: %s\r\n" "Content-Length: %d\r\n", mime, body.GetLength()); hdr += content; }
void IImportFON( HWND hWnd, const char *path ) { // FON files are really just resource modules IMakeNewFont(); HMODULE file = LoadLibraryEx( path, nil, LOAD_LIBRARY_AS_DATAFILE | DONT_RESOLVE_DLL_REFERENCES ); if( file == nil ) { char msg[ 512 ], msg2[ 1024 ]; FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nil, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)msg, sizeof( msg ), nil ); sprintf( msg2, "Failure importing FON file: can't open as resource library (%s)", msg ); MessageBox( hWnd, msg2, "Error", MB_OK | MB_ICONEXCLAMATION ); } else { hsTArray<ResRecord *> resList; if( EnumResourceNames( file, "Font", ResEnumProc, (LPARAM)&resList ) ) { // Put up a list of the resources so the user can choose which one ResRecord *res = (ResRecord *)DialogBoxParam( gInstance, MAKEINTRESOURCE( IDD_FONCHOOSER ), hWnd, ResListWndProc, (LPARAM)&resList ); if( res != nil ) { // Load the resource into a ram stream hsRAMStream stream; HGLOBAL glob = LoadResource( file, res->fHandle ); if( glob != nil ) { void *data = LockResource( glob ); if( data != nil ) { stream.Write( SizeofResource( file, res->fHandle ), data ); stream.Rewind(); if( !gFont->LoadFromFNTStream( &stream ) ) MessageBox( hWnd, "Failure importing FON file: can't parse resource as FNT", "Error", MB_OK | MB_ICONEXCLAMATION ); } } } } else { char msg[ 512 ], msg2[ 1024 ]; FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nil, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)msg, sizeof( msg ), nil ); sprintf( msg2, "Failure importing FON file: can't enumerate resources (%s)", msg ); MessageBox( hWnd, msg2, "Error", MB_OK | MB_ICONEXCLAMATION ); } uint32_t i; for( i = 0; i < resList.GetCount(); i++ ) delete resList[ i ]; resList.Reset(); FreeLibrary( file ); } IUpdateInfo( hWnd ); }
//-------------------------------------------------------------------------------------- HRESULT CRatingsDB::LoadDB() { // Find resource will pick the right ID_GDF_XML_STR based on the current language HRSRC hrsrc = FindResource( nullptr, MAKEINTRESOURCE(ID_RATINGS_XML), L"DATA" ); if( hrsrc ) { HGLOBAL hgResource = LoadResource( nullptr, hrsrc ); if( hgResource ) { BYTE* pResourceBuffer = (BYTE*)LockResource( hgResource ); if( pResourceBuffer ) { DWORD dwGDFXMLSize = SizeofResource( nullptr, hrsrc ); if( dwGDFXMLSize ) { // HGLOBAL from LoadResource() needs to be copied for CreateStreamOnHGlobal() to work HGLOBAL hgResourceCopy = GlobalAlloc( GMEM_MOVEABLE, dwGDFXMLSize ); if( hgResourceCopy ) { LPVOID pCopy = GlobalLock( hgResourceCopy ); if( pCopy ) { CopyMemory( pCopy, pResourceBuffer, dwGDFXMLSize ); GlobalUnlock( hgResource ); IStream* piStream = nullptr; HRESULT hr = CreateStreamOnHGlobal( hgResourceCopy, TRUE, &piStream ); if( SUCCEEDED(hr) && piStream ) { IXMLDOMDocument *pDoc = nullptr; // Load the XML into a IXMLDOMDocument object hr = CoCreateInstance( CLSID_DOMDocument, nullptr, CLSCTX_INPROC_SERVER, IID_IXMLDOMDocument, (void**)&pDoc ); if( SUCCEEDED(hr) ) { IPersistStreamInit* pPersistStreamInit = nullptr; hr = pDoc->QueryInterface( IID_IPersistStreamInit, (void**) &pPersistStreamInit ); if( SUCCEEDED(hr) ) { hr = pPersistStreamInit->Load( piStream ); if( SUCCEEDED(hr) ) { // Get the root node to the XML doc and store it pDoc->QueryInterface( IID_IXMLDOMNode, (void**)&m_pRootNode ); } SAFE_RELEASE( pPersistStreamInit ); } SAFE_RELEASE( pDoc ); } SAFE_RELEASE( piStream ); } } GlobalFree( hgResourceCopy ); } } } } } if( m_pRootNode ) return S_OK; else return E_FAIL; }
bool W7EUtils::CTempResource::GetFilePath(std::wstring &strPath) { if (m_strFilePath.empty()) { wchar_t szTempPath[MAX_PATH]; DWORD dwTemp = GetTempPath(_countof(szTempPath), szTempPath); if (dwTemp != 0 && dwTemp < _countof(szTempPath)) { HRSRC hResource = FindResource(m_hInstance, MAKEINTRESOURCE(m_iResourceId), L"BINARY"); if (hResource) { HGLOBAL hLoadedResource = LoadResource(m_hInstance, hResource); if (hLoadedResource) { LPVOID pLockedResource = LockResource(hLoadedResource); if (pLockedResource) { DWORD dwResourceSize = SizeofResource(m_hInstance, hResource); if (0 != dwResourceSize) { wchar_t szTempFilePath[MAX_PATH]; if (0 != GetTempFileName(szTempPath, L"w7e", 0, szTempFilePath)) { HANDLE hFile = CreateFile(szTempFilePath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (INVALID_HANDLE_VALUE != hFile) { DWORD dwBytesWritten = 0; if (WriteFile(hFile, pLockedResource, dwResourceSize, &dwBytesWritten, NULL) && dwBytesWritten == dwResourceSize) { m_strFilePath = szTempFilePath; } CloseHandle(hFile); if (m_strFilePath.empty()) { DeleteFile(szTempFilePath); } } } } } } } } } if (!m_strFilePath.empty()) { strPath = m_strFilePath; return true; } strPath.clear(); return false; }
/*** IDirectXFile methods ***/ static HRESULT WINAPI IDirectXFileImpl_CreateEnumObject(IDirectXFile* iface, LPVOID pvSource, DXFILELOADOPTIONS dwLoadOptions, LPDIRECTXFILEENUMOBJECT* ppEnumObj) { IDirectXFileImpl *This = impl_from_IDirectXFile(iface); IDirectXFileEnumObjectImpl* object; HRESULT hr; LPBYTE file_buffer; DWORD file_size; DWORD bytes_written; TRACE("(%p/%p)->(%p,%x,%p)\n", This, iface, pvSource, dwLoadOptions, ppEnumObj); if (!ppEnumObj) return DXFILEERR_BADVALUE; /* Only lowest 4 bits are relevant in DXFILELOADOPTIONS */ dwLoadOptions &= 0xF; hr = IDirectXFileEnumObjectImpl_Create(&object); if (FAILED(hr)) return hr; if (dwLoadOptions == DXFILELOAD_FROMFILE) { HANDLE hFile, file_mapping; TRACE("Open source file '%s'\n", (char*)pvSource); hFile = CreateFileA(pvSource, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); if (hFile == INVALID_HANDLE_VALUE) { TRACE("File '%s' not found\n", (char*)pvSource); return DXFILEERR_FILENOTFOUND; } file_size = GetFileSize(hFile, NULL); file_mapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL); CloseHandle(hFile); if (!file_mapping) { hr = DXFILEERR_BADFILETYPE; goto error; } object->mapped_memory = MapViewOfFile(file_mapping, FILE_MAP_READ, 0, 0, 0); CloseHandle(file_mapping); if (!object->mapped_memory) { hr = DXFILEERR_BADFILETYPE; goto error; } file_buffer = object->mapped_memory; } else if (dwLoadOptions == DXFILELOAD_FROMRESOURCE) { HRSRC resource_info; HGLOBAL resource_data; LPDXFILELOADRESOURCE lpdxflr = pvSource; TRACE("Source in resource (module = %p, name = %s, type = %s)\n", lpdxflr->hModule, debugstr_a(lpdxflr->lpName), debugstr_a(lpdxflr->lpType)); resource_info = FindResourceA(lpdxflr->hModule, lpdxflr->lpName, lpdxflr->lpType); if (!resource_info) { hr = DXFILEERR_RESOURCENOTFOUND; goto error; } file_size = SizeofResource(lpdxflr->hModule, resource_info); resource_data = LoadResource(lpdxflr->hModule, resource_info); if (!resource_data) { hr = DXFILEERR_BADRESOURCE; goto error; } file_buffer = LockResource(resource_data); if (!file_buffer) { hr = DXFILEERR_BADRESOURCE; goto error; } } else if (dwLoadOptions == DXFILELOAD_FROMMEMORY) { LPDXFILELOADMEMORY lpdxflm = pvSource; TRACE("Source in memory at %p with size %d\n", lpdxflm->lpMemory, lpdxflm->dSize); file_buffer = lpdxflm->lpMemory; file_size = lpdxflm->dSize; } else { FIXME("Source type %d is not handled yet\n", dwLoadOptions); hr = DXFILEERR_NOTDONEYET; goto error; } TRACE("File size is %d bytes\n", file_size); if (TRACE_ON(d3dxof_dump)) { static USHORT num; char tmp[12]; HANDLE file; sprintf(tmp, "file%05u.x", num++); file = CreateFileA(tmp, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, 0, NULL); if (file != INVALID_HANDLE_VALUE) { WriteFile(file, file_buffer, file_size, &bytes_written, NULL); CloseHandle(file); } } object->pDirectXFile = This; object->buf.pdxf = This; object->buf.token_present = FALSE; object->buf.buffer = file_buffer; object->buf.rem_bytes = file_size; hr = parse_header(&object->buf, &object->decomp_buffer); if (FAILED(hr)) goto error; /* Check if there are templates defined before the object */ if (!parse_templates(&object->buf, TRUE)) { hr = DXFILEERR_PARSEERROR; goto error; } if (TRACE_ON(d3dxof)) { ULONG i; TRACE("Registered templates (%d):\n", This->nb_xtemplates); for (i = 1; i < This->nb_xtemplates; i++) DPRINTF("%s - %s\n", This->xtemplates[i].name, debugstr_guid(&This->xtemplates[i].class_id)); } *ppEnumObj = &object->IDirectXFileEnumObject_iface; return DXFILE_OK; error: IDirectXFileEnumObject_Release(&object->IDirectXFileEnumObject_iface); *ppEnumObj = NULL; return hr; }
/* * Extract an icon set from the exe and save it as .ico */ static BOOL SaveIcon(const char* filename) { HGLOBAL res_handle; HRSRC res; WORD i; BYTE* res_data; DWORD res_size, Size, offset; HANDLE hFile = INVALID_HANDLE_VALUE; BOOL r = FALSE; GRPICONDIR* icondir; icondir = (GRPICONDIR*)GetResource(hMainInstance, MAKEINTRESOURCEA(IDI_ICON), _RT_GROUP_ICON, "icon", &res_size, FALSE); hFile = CreateFileA(filename, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, CREATE_NEW, 0, 0); if (hFile == INVALID_HANDLE_VALUE) { uprintf("Unable to create icon '%s': %s.\n", filename, WindowsErrorString()); goto out; } // Write .ico header if ((!WriteFile(hFile, icondir, 3*sizeof(WORD), &Size, NULL)) || (Size != 3*sizeof(WORD))) { uprintf("Couldn't write icon header: %s.\n", WindowsErrorString()); goto out; } // Write icon data offset = 3*sizeof(WORD) + icondir->idCount*sizeof(ICONDIRENTRY); for (i=0; i<icondir->idCount; i++) { // Write the common part of ICONDIRENTRY if ( (!WriteFile(hFile, &icondir->idEntries[i], sizeof(GRPICONDIRENTRY)-sizeof(WORD), &Size, NULL)) || (Size != sizeof(GRPICONDIRENTRY)-sizeof(WORD)) ) { uprintf("Couldn't write ICONDIRENTRY[%d]: %s.\n", i, WindowsErrorString()); goto out; } res = FindResourceA(hMainInstance, MAKEINTRESOURCEA(icondir->idEntries[i].nID), _RT_ICON); // Write the DWORD offset if ( (!WriteFile(hFile, &offset, sizeof(offset), &Size, NULL)) || (Size != sizeof(offset)) ) { uprintf("Couldn't write ICONDIRENTRY[%d] offset: %s.\n", i, WindowsErrorString()); goto out; } offset += SizeofResource(NULL, res); } for (i=0; i<icondir->idCount; i++) { // Write icon data res = FindResourceA(hMainInstance, MAKEINTRESOURCEA(icondir->idEntries[i].nID), _RT_ICON); res_handle = LoadResource(NULL, res); res_data = (BYTE*)LockResource(res_handle); res_size = SizeofResource(NULL, res); if ( (!WriteFile(hFile, res_data, res_size, &Size, NULL)) || (Size != res_size) ) { uprintf("Couldn't write icon data #%d: %s.\n", i, WindowsErrorString()); goto out; } } uprintf("Created: %s\n", filename); r = TRUE; out: safe_closehandle(hFile); return r; }
void CWebServer::OnRequest(CWebClientSocket* pClient, CStringA& hdr, CStringA& body) { CPath p(pClient->m_path); CStringA ext = p.GetExtension().MakeLower(); CStringA mime; if (ext.IsEmpty()) { mime = "text/html"; } else { m_mimes.Lookup(ext, mime); } hdr = "HTTP/1.0 200 OK\r\n"; bool fHandled = false, fCGI = false; if (!fHandled && m_webroot.IsDirectory()) { CStringA tmphdr; fHandled = fCGI = CallCGI(pClient, tmphdr, body, mime); if (fHandled) { tmphdr.Replace("\r\n", "\n"); CAtlList<CStringA> hdrlines; ExplodeMin(tmphdr, hdrlines, '\n'); POSITION pos = hdrlines.GetHeadPosition(); while (pos) { POSITION cur = pos; CAtlList<CStringA> sl; CStringA key = Explode(hdrlines.GetNext(pos), sl, ':', 2); if (sl.GetCount() < 2) { continue; } key.Trim().MakeLower(); if (key == "content-type") { mime = sl.GetTail().Trim(); hdrlines.RemoveAt(cur); } else if (key == "content-length") { hdrlines.RemoveAt(cur); } } tmphdr = Implode(hdrlines, '\n'); tmphdr.Replace("\n", "\r\n"); hdr += tmphdr + "\r\n"; } } RequestHandler rh = NULL; if (!fHandled && m_internalpages.Lookup(pClient->m_path, rh) && (pClient->*rh)(hdr, body, mime)) { if (mime.IsEmpty()) { mime = "text/html"; } CString redir; if (pClient->m_get.Lookup(_T("redir"), redir) || pClient->m_post.Lookup(_T("redir"), redir)) { if (redir.IsEmpty()) { redir = '/'; } hdr = "HTTP/1.0 302 Found\r\n" "Location: " + CStringA(redir) + "\r\n"; return; } fHandled = true; } if (!fHandled && m_webroot.IsDirectory()) { fHandled = LoadPage(0, body, pClient->m_path); } UINT resid; CStringA res; if (!fHandled && m_downloads.Lookup(pClient->m_path, resid) && (LoadResource(resid, res, _T("FILE")) || LoadResource(resid, res, _T("PNG")))) { if (mime.IsEmpty()) { mime = "application/octet-stream"; } memcpy(body.GetBufferSetLength(res.GetLength()), res.GetBuffer(), res.GetLength()); fHandled = true; } if (!fHandled) { hdr = mime == "text/html" ? "HTTP/1.0 301 Moved Permanently\r\n" "Location: /404.html\r\n" : "HTTP/1.0 404 Not Found\r\n"; return; } if ((mime == "text/html" || mime == "text/javascript") && !fCGI) { if (mime == "text/html") { hdr += "Expires: Thu, 19 Nov 1981 08:52:00 GMT\r\n" "Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0\r\n" "Pragma: no-cache\r\n"; CStringA debug; if (AfxGetAppSettings().fWebServerPrintDebugInfo) { debug += "<br><hr>\r\n"; debug += "<div id=\"debug\">"; CString key, value; POSITION pos; pos = pClient->m_hdrlines.GetStartPosition(); while (pos) { pClient->m_hdrlines.GetNextAssoc(pos, key, value); debug += "HEADER[" + key + "] = " + value + "\r\n"; } debug += "cmd: " + pClient->m_cmd + "\r\n"; debug += "path: " + pClient->m_path + "\r\n"; debug += "ver: " + pClient->m_ver + "\r\n"; pos = pClient->m_get.GetStartPosition(); while (pos) { pClient->m_get.GetNextAssoc(pos, key, value); debug += "GET[" + key + "] = " + value + "\r\n"; } pos = pClient->m_post.GetStartPosition(); while (pos) { pClient->m_post.GetNextAssoc(pos, key, value); debug += "POST[" + key + "] = " + value + "\r\n"; } pos = pClient->m_cookie.GetStartPosition(); while (pos) { pClient->m_cookie.GetNextAssoc(pos, key, value); debug += "COOKIE[" + key + "] = " + value + "\r\n"; } pos = pClient->m_request.GetStartPosition(); while (pos) { pClient->m_request.GetNextAssoc(pos, key, value); debug += "REQUEST[" + key + "] = " + value + "\r\n"; } debug += "</div>"; } body.Replace("[debug]", debug); } body.Replace("[browserpath]", "/browser.html"); body.Replace("[commandpath]", "/command.html"); body.Replace("[controlspath]", "/controls.html"); body.Replace("[indexpath]", "/index.html"); body.Replace("[path]", CStringA(pClient->m_path)); body.Replace("[setposcommand]", CMD_SETPOS); body.Replace("[setvolumecommand]", CMD_SETVOLUME); body.Replace("[wmcname]", "wm_command"); // TODO: add more general tags to replace } // gzip if (AfxGetAppSettings().fWebServerUseCompression && hdr.Find("Content-Encoding:") < 0) do { CString accept_encoding; pClient->m_hdrlines.Lookup(_T("accept-encoding"), accept_encoding); accept_encoding.MakeLower(); CAtlList<CString> sl; ExplodeMin(accept_encoding, sl, ','); if (!sl.Find(_T("gzip"))) { break; } CHAR path[_MAX_PATH], fn[_MAX_PATH]; if (!GetTempPathA(_MAX_PATH, path) || !GetTempFileNameA(path, "mpc_gz", 0, fn)) { break; } gzFile gf = gzopen(fn, "wb9"); if (!gf || gzwrite(gf, (LPVOID)(LPCSTR)body, body.GetLength()) != body.GetLength()) { if (gf) { gzclose(gf); } DeleteFileA(fn); break; } gzclose(gf); FILE* f = NULL; if (fopen_s(&f, fn, "rb")) { DeleteFileA(fn); break; } fseek(f, 0, 2); CHAR* s = body.GetBufferSetLength(ftell(f)); fseek(f, 0, 0); int len = (int)fread(s, 1, body.GetLength(), f); ASSERT(len == body.GetLength()); #ifndef _DEBUG UNREFERENCED_PARAMETER(len); #endif fclose(f); DeleteFileA(fn); hdr += "Content-Encoding: gzip\r\n"; } while (0); CStringA content; content.Format( "Content-Type: %s\r\n" "Content-Length: %d\r\n", mime, body.GetLength()); hdr += content; }
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { static int nLineCount,lineNo; static int cyClient, cxChar, cyChar; static int xScroll; static HGLOBAL hResource; static HWND hwndScroll; static HWND hScroll; CHAR *szText; HINSTANCE hInstance; HDC hdc; PAINTSTRUCT ps; RECT clientRect; int i; switch(msg) { case WM_CREATE: hInstance = ((LPCREATESTRUCT)lParam)->hInstance; lineNo = 0; //Load Text resource hResource = LoadResource(hInstance, FindResource(hInstance, TEXT("ANNABELLEE"), TEXT("TEXT"))); szText = (CHAR *)LockResource(hResource); //Create Scrollbar hScroll = CreateWindow(TEXT("scrollbar"), NULL, SB_VERT | WS_CHILD | WS_VISIBLE, 0, 0, 0, 0, hwnd, (HMENU)1, hInstance, NULL); //calculate line count while(*szText != '\0' && *szText != '\\') { if (*szText == '\n') ++nLineCount; szText = AnsiNext(szText); } *szText == '\0'; //Get char size cxChar = LOWORD(GetDialogBaseUnits()); cyChar = HIWORD(GetDialogBaseUnits()); xScroll = GetSystemMetrics(SM_CXVSCROLL); //Setup scroll SetScrollRange(hScroll, SB_CTL, 0, nLineCount, TRUE); SetScrollPos(hScroll, SB_CTL, 0, TRUE); break; case WM_SIZE: { MoveWindow(hScroll, LOWORD(lParam) - xScroll, 0, xScroll, HIWORD(lParam), TRUE); cyClient = HIWORD(lParam); SetFocus(hScroll); break; } case WM_SETFOCUS: { SetFocus(hScroll); break; } case WM_VSCROLL: { switch(wParam) { case SB_TOP: lineNo = 0; break; case SB_BOTTOM: lineNo = nLineCount; break; case SB_LINEDOWN: lineNo++; break; case SB_LINEUP: lineNo--; break; case SB_PAGEDOWN: lineNo += cyClient / cyChar; break; case SB_PAGEUP: lineNo -= cyClient / cyChar; break; default: break; } lineNo = max(0, lineNo); lineNo = min(lineNo, nLineCount); SetScrollPos(hScroll, SB_CTL, lineNo, TRUE); InvalidateRect(hwnd, NULL, TRUE); break; } case WM_PAINT: { hdc = BeginPaint(hwnd, &ps); GetClientRect(hwnd, &clientRect); clientRect.left += cxChar; clientRect.top += cyChar*(1 - lineNo); szText = (CHAR *)LockResource(hResource); DrawTextA(hdc, szText, -1, &clientRect, DT_TOP); EndPaint(hwnd, &ps); break; } case WM_DESTROY: { FreeResource(hResource); PostQuitMessage(0); break; } } return DefWindowProc(hwnd, msg, wParam, lParam); }
void GLTexture::LoadTGAResource(char *name) { // struct to cast the resource into struct TGAstruct { GLubyte TGAcompare[12]; // Used to compare TGA header GLubyte header[6]; // First 6 useful bytes of the header }; GLubyte TGAheader[12] = {0,0,2,0,0,0,0,0,0,0,0,0};// Uncompressed TGA header GLuint bytesPerPixel; // Holds the number of bytes per pixel used GLuint imageSize; // Used to store the image size GLuint temp; // Temporary variable GLuint type = GL_RGBA; // Set the default type to RBGA (32 BPP) GLubyte *imageData; // Image data (up to 32 Bits) GLuint bpp; // Image color depth in bits per pixel. // Find the targa in the "TGA" resources HRSRC hrsrc = FindResource(0, name, "TGA"); // If you can't find it then return if (hrsrc==0) return; // Load the targa HGLOBAL resource = LoadResource(0, hrsrc); // If you can't load it then return if (resource==0) return; // Load it into the buffer void *buffer = LockResource(resource); // Cast it into the targa struct TGAstruct *top = (TGAstruct*)buffer; // Make sure it checks out against our comparison header if (memcmp(TGAheader,top,sizeof(TGAheader)) != 0) return; // Determine the TGA width and height (highbyte*256+lowbyte) width = top->header[1] * 256 + top->header[0]; height = top->header[3] * 256 + top->header[2]; // Check to make sure the targa is valid and is 24 bit or 32 bit if(width <=0 || // Is the width less than or equal to zero height <=0 || // Is the height less than or equal to zero (top->header[4] != 24 && top->header[4] != 32)) // Is it 24 or 32 bit? { // If anything didn't check out then close the file and return return; } bpp = top->header[4]; // Grab the bits per pixel bytesPerPixel = bpp / 8; // Divide by 8 to get the bytes per pixel imageSize = width * height * bytesPerPixel; // Calculate the memory required for the data // Allocate the memory for the image data imageData = new GLubyte[imageSize]; // Load the data in memcpy(imageData, (GLubyte*)buffer+18, imageSize); // Loop through the image data and swap the 1st and 3rd bytes (red and blue) for(GLuint i = 0; i < int(imageSize); i += bytesPerPixel) { temp = imageData[i]; imageData[i] = imageData[i + 2]; imageData[i + 2] = temp; } // Set the type if (bpp == 24) type = GL_RGB; // Generate the OpenGL texture id glGenTextures(1, &texture[0]); // Bind this texture to its id glBindTexture(GL_TEXTURE_2D, texture[0]); // Use mipmapping filter glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); // Generate the mipmaps gluBuild2DMipmaps(GL_TEXTURE_2D, type, width, height, type, GL_UNSIGNED_BYTE, imageData); // Cleanup free(imageData); free(buffer); free(top); }
int CDialog::DoModal() { // can be constructed with a resource template or InitModalIndirect ASSERT(m_lpszTemplateName != NULL || m_hDialogTemplate != NULL || m_lpDialogTemplate != NULL); // load resource as necessary LPCDLGTEMPLATE lpDialogTemplate = m_lpDialogTemplate; HGLOBAL hDialogTemplate = m_hDialogTemplate; HINSTANCE hInst = AfxGetResourceHandle(); if (m_lpszTemplateName != NULL) { hInst = AfxFindResourceHandle(m_lpszTemplateName, RT_DIALOG); HRSRC hResource = ::FindResource(hInst, m_lpszTemplateName, RT_DIALOG); hDialogTemplate = LoadResource(hInst, hResource); } if (hDialogTemplate != NULL) lpDialogTemplate = (LPCDLGTEMPLATE)LockResource(hDialogTemplate); // return -1 in case of failure to load the dialog template resource if (lpDialogTemplate == NULL) return -1; // disable parent (before creating dialog) HWND hWndParent = PreModal(); AfxUnhookWindowCreate(); BOOL bEnableParent = FALSE; if (hWndParent != NULL && ::IsWindowEnabled(hWndParent)) { ::EnableWindow(hWndParent, FALSE); bEnableParent = TRUE; } TRY { // create modeless dialog AfxHookWindowCreate(this); if (CreateDlgIndirect(lpDialogTemplate, CWnd::FromHandle(hWndParent), hInst)) { if (m_nFlags & WF_CONTINUEMODAL) { // enter modal loop DWORD dwFlags = MLF_SHOWONIDLE; if (GetStyle() & DS_NOIDLEMSG) dwFlags |= MLF_NOIDLEMSG; VERIFY(RunModalLoop(dwFlags) == m_nModalResult); } // hide the window before enabling the parent, etc. if (m_hWnd != NULL) SetWindowPos(NULL, 0, 0, 0, 0, SWP_HIDEWINDOW| SWP_NOSIZE|SWP_NOMOVE|SWP_NOACTIVATE|SWP_NOZORDER); } } CATCH_ALL(e) { DELETE_EXCEPTION(e); m_nModalResult = -1; } END_CATCH_ALL if (bEnableParent) ::EnableWindow(hWndParent, TRUE); if (hWndParent != NULL && ::GetActiveWindow() == m_hWnd) ::SetActiveWindow(hWndParent); // destroy modal window DestroyWindow(); PostModal(); // unlock/free resources as necessary if (m_lpszTemplateName != NULL || m_hDialogTemplate != NULL) UnlockResource(hDialogTemplate); if (m_lpszTemplateName != NULL) FreeResource(hDialogTemplate); return m_nModalResult; }
//////////////////////////// // Unpack plugins to 0.csx, 1.csx etc. bool CRuntime::UnpackPlugins(int startresource) { // Store the old current directory, but look for DLLs for plugin loading etc in the temp directory char oldCurrentDirectory[MAX_PATH]; GetCurrentDirectory(MAX_PATH, oldCurrentDirectory); SetCurrentDirectory(tempDir); // Get number of plugins char strbuf[256]; if (LoadString(GetModuleHandle(NULL), IDS_numPlugins, strbuf, 256) == 0) throw runtime_error("Error unpacking resources (1)"); numPlugins = atoi(strbuf); // If over 1000 plugins or negative, probably undefined string - show error if (numPlugins < 0 || numPlugins > 1000) throw runtime_error("Error unpacking resources (2)"); // Loop all plugin resources for (int i = 0; i < numPlugins; i++) { CString curFile; curFile.Format("%s%d.csx", tempDir, i); // Create the file for writing FILE* f = fopen(CSTR(curFile), "wb"); if (f == NULL) { CString msg; msg.Format("Error unpacking resources (3): could not create file %s (%d)", curFile, errno); throw runtime_error((const char*)msg); } // Get the resource data HRSRC resLoad = FindResource(NULL, MAKEINTRESOURCE(startresource + i), "DLLBLOCK"); int e = GetLastError(); CString s; s.Format("Error unpacking resources (4): %d", e); if (resLoad == NULL) throw runtime_error((const char*)s); HGLOBAL resData = LoadResource(NULL, resLoad); LPCSTR dllData = (LPCSTR)LockResource(resData); // Write the resource data to disk fwrite(dllData, 1, SizeofResource(NULL, resLoad), f); fclose(f); FreeResource(resData); // Load up this module PluginModule plugin; plugin.module = LoadLibrary(CSTR(curFile)); if (plugin.module == NULL) { CString msg; msg.Format("Failed to load plugin %s (%d)", curFile, GetLastError()); throw runtime_error((const char*)msg); } //DWORD e = GetLastError(); // Get proc addresses plugin.RTCreateObject = (LPRTCREATEOBJECT)GetProcAddress(plugin.module, "RTCreateObject"); plugin.RTDestroyObject = (LPRTDESTROYOBJECT)GetProcAddress(plugin.module, "RTDestroyObject"); plugin.RTWindowProc = (PLUGINWNDPROC)GetProcAddress(plugin.module, "RTWindowProc"); // Initialise LPRTDLLLOAD RTDllLoad = (LPRTDLLLOAD)GetProcAddress(plugin.module, "RTDllLoad"); // Handle vectors PluginModuleVectors emv; pluginvecs.push_back(emv); PluginModuleVectors* pv = &(pluginvecs.back()); MicroAceTool mat(&(pv->CndRoutines), &(pv->ActRoutines), &(pv->ExpRoutines), &(pv->ExpNames)); // Load vectors plugin.ideFlags = RTDllLoad(&mat); // Get the plugin routine tables plugin.pvCndRoutines = &(pv->CndRoutines); plugin.pvActRoutines = &(pv->ActRoutines); plugin.pvExpRoutines = &(pv->ExpRoutines); plugin.pvExpNames = &(pv->ExpNames); // Make all expression names lowercase vector<CString>::iterator j; for (j = plugin.pvExpNames->begin(); j != plugin.pvExpNames->end(); j++) j->MakeLower(); // Add to plugins list plugins.push_back(plugin); } // Restore current directory SetCurrentDirectory(oldCurrentDirectory); return true; }
int wmain (int argc,wchar_t ** argv) { CAppData::stdfunc(); SetRegKey(argc,argv); if (!SetLanguageSpecifigHandles(argv[0])) return 1; CArrayFP<CDatabase*> aDatabases; WORD wCurrentThread=0; aDatabases.Add(CDatabase::FromDefaults(TRUE)); aDatabases[0]->SetNamePtr(alloccopy(L"DEFAULTX")); aDatabases[0]->SetThreadId(wCurrentThread); int i,helps=0; #ifndef WIN32 if (getenv("TZ")==NULL) fprintf(stderr,"Timezone is not set. Database may contain invalid file times.\nFor example type "SET TZ=GMT+1" for central european time.\n"); #endif for (i=1;i<argc;i++) { if (argv[i][0]=='-' || argv[i][0]=='/') { switch (argv[i][1]) { case L'X': if (argv[i][2]==L'\0') { if (i<argc-1) i++; // RegKeyName already set } break; case 'l': case 'L': if (wcsncmp(aDatabases.GetLast()->GetName(),L"PARAMX",6)!=0 && wcsncmp(aDatabases.GetLast()->GetName(),L"DEFAULTX",8)!=0) wprintf(ID2W(IDS_UPDATEDB32CANNOTCHANGELOADED),aDatabases.GetLast()->GetName()); else if (argv[i][2]=='1') { aDatabases.GetLast()->AddLocalRoots(); aDatabases.GetLast()->SetNamePtr(alloccopy(L"PARAMX")); } else { CStringW* pStr; if (argv[i][2]==L'\0' && i+1<argc) pStr=new CStringW(argv[++i]); else pStr=new CStringW(argv[i]+2); if ((*pStr)[0]==L'\"') pStr->DelChar(0); if (pStr->LastChar()==L'\"') pStr->DelLastChar(); while (pStr->LastChar()==L'\\') pStr->DelLastChar(); if (pStr->GetLength()>1) { if ((*pStr)[1]==':' && pStr->GetLength()==2) aDatabases.GetLast()->AddRoot(pStr->GiveBuffer()); else if (FileSystem::IsDirectory(*pStr)) aDatabases.GetLast()->AddRoot(pStr->GiveBuffer()); else fwprintf(stderr,ID2W(IDS_UPDATEDB32DIRECTORYISNOTVALID),(LPCWSTR)*pStr); } else fwprintf(stderr,ID2W(IDS_UPDATEDB32DIRECTORYISNOTVALID),(LPCWSTR)*pStr); delete pStr; aDatabases.GetLast()->SetNamePtr(alloccopy(L"PARAMX")); } break; case 'e': if (wcsncmp(aDatabases.GetLast()->GetName(),L"PARAMX",6)!=0 && wcsncmp(aDatabases.GetLast()->GetName(),L"DEFAULTX",8)!=0) wprintf(ID2W(IDS_UPDATEDB32CANNOTCHANGELOADED),aDatabases.GetLast()->GetName()); else { CStringW* pStr; if (argv[i][2]=='\0' && i+1<argc) pStr=new CStringW(argv[++i]); else pStr=new CStringW(argv[i]+2); if ((*pStr)[0]==L'\"') pStr->DelChar(0); if (pStr->LastChar()==L'\"') pStr->DelLastChar(); while (pStr->LastChar()==L'\\') pStr->DelLastChar(); if (pStr->GetLength()>0) aDatabases.GetLast()->SetExcludedFiles(*pStr); aDatabases.GetLast()->SetNamePtr(alloccopy(L"PARAMX")); } break; case 'E': if (wcsncmp(aDatabases.GetLast()->GetName(),L"PARAMX",6)!=0 && wcsncmp(aDatabases.GetLast()->GetName(),L"DEFAULTX",8)!=0) wprintf(ID2W(IDS_UPDATEDB32CANNOTCHANGELOADED),aDatabases.GetLast()->GetName()); else { CStringW* pStr; if (argv[i][2]=='\0' && i+1<argc) pStr=new CStringW(argv[++i]); else pStr=new CStringW(argv[i]+2); if ((*pStr)[0]==L'\"') pStr->DelChar(0); if (pStr->LastChar()==L'\"') pStr->DelLastChar(); while (pStr->LastChar()==L'\\') pStr->DelLastChar(); if (pStr->GetLength()>1) { if (!aDatabases.GetLast()->AddExcludedDirectory(*pStr)) fwprintf(stderr,ID2W(IDS_UPDATEDB32DIRECTORYISNOTVALID),(LPCWSTR)*pStr); } else fwprintf(stderr,ID2W(IDS_UPDATEDB32DIRECTORYISNOTVALID),(LPCWSTR)*pStr); delete pStr; aDatabases.GetLast()->SetNamePtr(alloccopy(L"PARAMX")); } break; case 't': case 'T': if (wcsncmp(aDatabases.GetLast()->GetName(),L"PARAMX",6)!=0 && wcsncmp(aDatabases.GetLast()->GetName(),L"DEFAULTX",8)!=0) wprintf(ID2W(IDS_UPDATEDB32CANNOTCHANGELOADED),aDatabases.GetLast()->GetName()); else if (argv[i][2]==L'c' || argv[i][2]==L'C') { if (argv[i][3]==L'\0') aDatabases.GetLast()->SetCreatorPtr(alloccopy(argv[++i])); else aDatabases.GetLast()->SetCreatorPtr(alloccopy(argv[i]+2)); aDatabases.GetLast()->SetNamePtr(alloccopy(L"PARAMX")); } else if (argv[i][2]==L'd' || argv[i][2]==L'D') { if (argv[i][3]==L'\0') aDatabases.GetLast()->SetDescriptionPtr(alloccopy(argv[++i])); else aDatabases.GetLast()->SetDescriptionPtr(alloccopy(argv[i]+2)); aDatabases.GetLast()->SetNamePtr(alloccopy(L"PARAMX")); } break; case 'i': case 'I': if (wcsncmp(aDatabases.GetLast()->GetName(),L"PARAMX",6)!=0 && wcsncmp(aDatabases.GetLast()->GetName(),L"DEFAULTX",8)!=0) wprintf(ID2W(IDS_UPDATEDB32CANNOTCHANGELOADED),aDatabases.GetLast()->GetName()); else { aDatabases.GetLast()->SetFlag(CDatabase::flagIncrementalUpdate,TRUE); aDatabases.GetLast()->SetNamePtr(alloccopy(L"PARAMX")); } break; case 'c': case 'C': if (wcsncmp(aDatabases.GetLast()->GetName(),L"PARAMX",6)!=0 && wcsncmp(aDatabases.GetLast()->GetName(),L"DEFAULTX",8)!=0) wprintf(ID2W(IDS_UPDATEDB32CANNOTCHANGELOADED),aDatabases.GetLast()->GetName()); else if (argv[i][2]==L'A' || argv[i][2]==L'a') { aDatabases.GetLast()->SetFlag(CDatabase::flagAnsiCharset,TRUE); aDatabases.GetLast()->SetNamePtr(alloccopy(L"PARAMX")); } else if (argv[i][2]==L'U' || argv[i][2]==L'u') { aDatabases.GetLast()->SetFlag(CDatabase::flagAnsiCharset,FALSE); aDatabases.GetLast()->SetNamePtr(alloccopy(L"PARAMX")); } break; case 'N': case 'n': wCurrentThread++; break; case 'q': case 'Q': nQuiet=TRUE; break; case 'v': case 'V': printf("%s\n",szVersionStr); return 0; case 'd': { // Using database file CStringW sFile; if (argv[i][2]=='\0') sFile=argv[++i]; else sFile=(argv[i]+2); if (aDatabases.GetSize()==1 && wcscmp(aDatabases[0]->GetName(),L"DEFAULTX")==0) { aDatabases[0]->SetNamePtr(alloccopy(L"PARAMX")); aDatabases[0]->SetArchiveNamePtr(sFile.GiveBuffer()); } else { CDatabase* pDatabase=CDatabase::FromFile(sFile,(int)sFile.GetLength()); if (pDatabase!=NULL) { aDatabases.Add(pDatabase); pDatabase->SetNamePtr(alloccopy(L"PARAMX")); pDatabase->SetThreadId(wCurrentThread); } } } break; case 'D': { // Loading database 'name' from registry, cannot be changed CStringW sName; if (argv[i][2]=='\0') sName=argv[++i]; else sName=(argv[i]+2); if (CDatabase::FindByName(aDatabases,sName,(int)sName.GetLength())==NULL) { CDatabase* pDatabase=CDatabase::FromName(HKCU, CString(g_szRegKey)+"\\Databases",sName); if (pDatabase!=NULL) { pDatabase->SetFlag(CDatabase::flagGlobalUpdate); // Is only default loaded if (aDatabases.GetSize()==1 && wcscmp(aDatabases[0]->GetName(),L"DEFAULTX")==0) { delete aDatabases[0]; aDatabases[0]=pDatabase; } else { aDatabases.Add(pDatabase); pDatabase->SetThreadId(wCurrentThread); } } } } break; case 'h': case 'H': case '?': helps=1; break; default: helps=1; break; } } } if (helps==1) { #ifdef WIN32 fprintf(stdout,"%s\n",szVersionStr); #else fprintf(stdout,"%s\nusage updatedb",szVersionStr); #endif HRSRC hRc=FindResource(GetLanguageSpecificResourceHandle(),MAKEINTRESOURCE(IDR_UPDATEDBHELP),"HELPTEXT"); HGLOBAL hGlobal=LoadResource(GetLanguageSpecificResourceHandle(),hRc); LPCSTR pStr=(LPCSTR)LockResource(hGlobal); // Counting length int len; for (len=0;pStr[len]!='\0';len++) { if (pStr[len]=='E' && pStr[len+1]=='O' && pStr[len+2]=='F') break; } fwrite(pStr,1,len,stdout); FreeLibrary(GetLanguageSpecificResourceHandle()); return 1; } // Checking databases // First, check that there is database if (aDatabases.GetSize()==0) CDatabase::LoadFromRegistry(HKCU,CString(g_szRegKey)+"\\Databases",aDatabases); else if (aDatabases.GetSize()==1 && wcsncmp(aDatabases[0]->GetName(),L"DEFAULTX",8)==0) { aDatabases.RemoveAll(); CDatabase::LoadFromRegistry(HKCU,CString(g_szRegKey)+"\\Databases",aDatabases); // No registry values? if (aDatabases.GetSize()==0) { aDatabases.Add(CDatabase::FromDefaults(TRUE)); aDatabases[0]->SetNamePtr(alloccopy(L"DEFAULTX")); } } CDatabase::CheckValidNames(aDatabases); CDatabase::CheckDoubleNames(aDatabases); for (int i=0;i<aDatabases.GetSize();) { if (!aDatabases[i]->IsGloballyUpdated()) aDatabases.RemoveAt(i); else { if ((wcsncmp(aDatabases[i]->GetName(),L"PARAMX",6)==0 || wcsncmp(aDatabases[i]->GetName(),L"DEFAULTX",8)==0)) { BOOL bNameChanged=FALSE; if (aDatabases[i]->GetRoots()==0) { BOOL bFree; LPWSTR pFile=aDatabases[i]->GetResolvedArchiveName(bFree); CDatabaseInfo* pDatabaseInfo=CDatabaseInfo::GetFromFile(pFile); if (bFree) delete[] pFile; if (pDatabaseInfo!=NULL) { CDatabase* pDatabase; if (!pDatabaseInfo->sExtra2.IsEmpty()) pDatabase=CDatabase::FromExtraBlock(pDatabaseInfo->sExtra2); if (pDatabase==NULL && !pDatabaseInfo->sExtra1.IsEmpty()) pDatabase=CDatabase::FromExtraBlock(pDatabaseInfo->sExtra1); wprintf(ID2W(IDS_UPDATEDB32USINGEXISTINGSETTINGS), aDatabases[i]->GetArchiveName(),pDatabase->GetName()); pDatabase->SetArchiveType(aDatabases[i]->GetArchiveType()); pDatabase->SetArchiveName(aDatabases[i]->GetArchiveName()); delete aDatabases[i]; aDatabases[i]=pDatabase; delete pDatabaseInfo; bNameChanged=TRUE; } } if (!bNameChanged) { ULONG_PTR nFirst=LastCharIndex(aDatabases[i]->GetArchiveName(),L'\\')+1; int nLength=LastCharIndex(aDatabases[i]->GetArchiveName()+nFirst,L'.'); if (nLength==-1) nLength=istrlenw(aDatabases[i]->GetArchiveName()+nFirst); aDatabases[i]->SetNamePtr(alloccopy(aDatabases[i]->GetArchiveName()+nFirst,nLength)); } } i++; } } // Starting to update WORD dwTheads=CDatabase::CheckIDs(aDatabases); if (dwTheads==0) { FreeLibrary(GetLanguageSpecificResourceHandle()); return FALSE; } if (dwTheads==1) { CDatabaseUpdater Updater(aDatabases,aDatabases.GetSize(),UpdateProc); Updater.Update(FALSE); } else { WORD wThread; ppUpdaters=new CDatabaseUpdater*[dwTheads+1]; for (wThread=0;wThread<dwTheads;wThread++) { ppUpdaters[wThread]=new CDatabaseUpdater(aDatabases,aDatabases.GetSize(), UpdateProc,wThread,(DWORD)0); } ppUpdaters[dwTheads]=NULL; // Starting DWORD dwRunning=0; UpdateError ueCode; for (wThread=0;wThread<dwTheads;wThread++) { ueCode=ppUpdaters[wThread]->Update(TRUE); if (ueCode==ueSuccess) dwRunning++; else { delete ppUpdaters[wThread]; ppUpdaters[wThread]=UPDATER_EXITED(ueCode); } } if (dwRunning==0) delete ppUpdaters; else { while (ppUpdaters!=NULL) Sleep(100); } } FinishRegKey(); FreeLibrary(GetLanguageSpecificResourceHandle()); return 1; }
static BOOL CALLBACK register_manifest( HMODULE module, const WCHAR *type, WCHAR *res_name, LONG_PTR arg ) { #ifdef __i386__ static const char current_arch[] = "x86"; #elif defined __x86_64__ static const char current_arch[] = "amd64"; #else static const char current_arch[] = "none"; #endif static const WCHAR manifestW[] = {'W','I','N','E','_','M','A','N','I','F','E','S','T'}; const struct dll_data *dll_data = (const struct dll_data*)arg; xmlbuf_t buffer; xmlstr_t elem, attr_name, attr_value; xmlstr_t name, version, arch, key, lang; BOOL end = FALSE, error; const char *manifest; SIZE_T len; HRSRC rsrc; if (IS_INTRESOURCE(res_name) || strncmpW( res_name, manifestW, sizeof(manifestW)/sizeof(WCHAR) )) return TRUE; rsrc = FindResourceW( module, res_name, type ); manifest = LoadResource( module, rsrc ); len = SizeofResource( module, rsrc ); buffer.ptr = manifest; buffer.end = manifest + len; name.ptr = version.ptr = arch.ptr = key.ptr = lang.ptr = NULL; name.len = version.len = arch.len = key.len = lang.len = 0; while (next_xml_elem( &buffer, &elem )) { if (!xmlstr_cmp( &elem, "assemblyIdentity" )) continue; while (next_xml_attr( &buffer, &attr_name, &attr_value, &error, &end )) { if (xmlstr_cmp(&attr_name, "name")) name = attr_value; else if (xmlstr_cmp(&attr_name, "version")) version = attr_value; else if (xmlstr_cmp(&attr_name, "processorArchitecture")) arch = attr_value; else if (xmlstr_cmp(&attr_name, "publicKeyToken")) key = attr_value; else if (xmlstr_cmp(&attr_name, "language")) lang = attr_value; } if (!error && name.ptr && version.ptr && arch.ptr && key.ptr) { if (!lang.ptr) { lang.ptr = "none"; lang.len = strlen( lang.ptr ); } if (!arch.len) /* fixup the architecture */ { char *new_buffer = HeapAlloc( GetProcessHeap(), 0, len + sizeof(current_arch) ); memcpy( new_buffer, manifest, arch.ptr - manifest ); strcpy( new_buffer + (arch.ptr - manifest), current_arch ); memcpy( new_buffer + strlen(new_buffer), arch.ptr, len - (arch.ptr - manifest) ); arch.ptr = current_arch; arch.len = strlen( current_arch ); if (create_winsxs_dll( dll_data->name, &arch, &name, &key, &version, &lang, dll_data->data, dll_data->size )) create_manifest( &arch, &name, &key, &version, &lang, new_buffer, len + arch.len ); HeapFree( GetProcessHeap(), 0, new_buffer ); } else { if (create_winsxs_dll( dll_data->name, &arch, &name, &key, &version, &lang, dll_data->data, dll_data->size )) create_manifest( &arch, &name, &key, &version, &lang, manifest, len ); } } } return TRUE; }
CTuopList::CTuopList(WContainerWidget *parent ): WContainerWidget(parent) { OBJECT objRes=LoadResource("default", "localhost"); if( objRes !=INVALID_VALUE ) { MAPNODE ResNode=GetResourceNode(objRes); if( ResNode != INVALID_VALUE ) { #ifdef Tuopu FindNodeValue(ResNode,"IDS_Tuopu",strMainTitle); FindNodeValue(ResNode,"IDS_Tuopu_List",strTitle); FindNodeValue(ResNode,"IDS_Tuopu1",strNameUse); FindNodeValue(ResNode,"IDS_Delete_Tuop_Affirm",strDel); FindNodeValue(ResNode,"IDS_Tuop_List_Null",strNullList); FindNodeValue(ResNode,"IDS_Tuopu1",strTuopTip); #else FindNodeValue(ResNode,"IDS_Maintain",strMainTitle);//Ecc展示视图 FindNodeValue(ResNode,"IDS_Maintain_List",strTitle);//Ecc展示视图列表 FindNodeValue(ResNode,"IDS_Maintain1",strNameUse);//展示图 FindNodeValue(ResNode,"IDS_Delete_Maintain_Affirm",strDel);//确认删除选中展示视图吗? FindNodeValue(ResNode,"IDS_Maintain_List_Null",strNullList);//Ecc展示视图列表为空 FindNodeValue(ResNode,"IDS_Maintian1",strTuopTip);//Ecc展示视图 #endif FindNodeValue(ResNode,"IDS_Name",strLoginLabel); FindNodeValue(ResNode,"IDS_Edit",strNameEdit); FindNodeValue(ResNode,"IDS_Edit",strEditTip); FindNodeValue(ResNode,"IDS_Delete",strDeleteType); FindNodeValue(ResNode,"IDS_ConfirmCancel",szButNum); FindNodeValue(ResNode,"IDS_Affirm",szButMatch); FindNodeValue(ResNode,"IDS_Delete_Tuop_Affirm",strDel); FindNodeValue(ResNode,"IDS_Edit",strEditTip); FindNodeValue(ResNode,"IDS_Delete",strDeleteType); FindNodeValue(ResNode,"IDS_ConfirmCancel",szButNum); FindNodeValue(ResNode,"IDS_Affirm",szButMatch); FindNodeValue(ResNode,"IDS_All_Select",strAllSel); FindNodeValue(ResNode,"IDS_None_Select",strAllNotSel); FindNodeValue(ResNode,"IDS_Invert_Select",strFanSel); FindNodeValue(ResNode,"IDS_Delete",strDelete); FindNodeValue(ResNode,"IDS_Sort",szSort); FindNodeValue(ResNode,"IDS_TuopDown",szTuopDown); FindNodeValue(ResNode,"IDS_SortNum",szSortNum); FindNodeValue(ResNode,"IDS_Refresh_GUI",strRefresh); FindNodeValue(ResNode,"IDS_Del_Con",strDelCon); FindNodeValue(ResNode,"IDS_Save_Sort",strSaveSort); FindNodeValue(ResNode,"IDS_ReturnSave",strReturnSave); //IDS_Sort = 排序 FindNodeValue(ResNode,"IDS_Sort",strSort); //IDS_TUOPU_SORT_LIST = 拓扑排序列表 FindNodeValue(ResNode,"IDS_TUOPU_SORT_LIST",strTuoPuSortList); //IDS_Name = 名称 FindNodeValue(ResNode,"IDS_Name",strName); //IDS_SEQUENCE_NO = 序号 FindNodeValue(ResNode,"IDS_SEQUENCE_NO",strSequenceNo); //IDS_Affirm = 确定 FindNodeValue(ResNode,"IDS_Affirm",strAffirm); } CloseResource(objRes); } bFirst =true; ShowMainTable(); }