/*func*------------------------------------------------------------------------ create the given bitmap from the GR resources (for uncommented and commented case) in :bScreen - false: get bitmap of printer element true : get bitmap of screen element nIDBitmap - desired bitmap bCommented - false: bitmap is uncommented true : Bitmap is commented out:pointer to the bitmap info -----------------------------------------------------------------------------*/ LPBITMAPINFO GDIHelper::CreateBmInfo(bool bScreen, UINT nIDBitmap, bool bCommented, bool bSFCmanual) { HRSRC hRsrc; HGLOBAL hGlobal; LPBITMAPINFOHEADER lpbih, lpbiht; COLORMAP cm[2]; int i, iNumColors; RGBQUAD *pRGBQuad; hRsrc = FindResource(::GetModuleHandle(NULL), MAKEINTRESOURCE(nIDBitmap + IDB_GR_ICONCMT), RT_BITMAP); ASSERT(hRsrc); hGlobal = LoadResource(::GetModuleHandle(NULL), hRsrc); ASSERT(hGlobal); if( (hRsrc== NULL) || (hGlobal == NULL) ) { return NULL; } lpbih = (LPBITMAPINFOHEADER)LockResource(hGlobal); if( lpbih == NULL ) { FreeResource(hGlobal); return NULL; } if( lpbih->biBitCount <= 8 ) iNumColors = (1 << lpbih->biBitCount); else iNumColors = 0; // No palette needed for 24 BPP DIB if( lpbih->biClrUsed > 0 ) iNumColors = lpbih->biClrUsed; // Use biClrUsed // 16 colors fix! if( iNumColors != 16 ) { UnlockResource(hGlobal); FreeResource(hGlobal); return NULL; } // alloc memory for header, color map and color values i = lpbih->biSize + iNumColors * sizeof(RGBQUAD) + (lpbih->biWidth * lpbih->biHeight * lpbih->biBitCount) / 8; lpbiht = (LPBITMAPINFOHEADER)::malloc(i); if( lpbiht == NULL ) { UnlockResource(hGlobal); FreeResource(hGlobal); return NULL; } memcpy(lpbiht, lpbih, i); pRGBQuad = (RGBQUAD*) ((LPBYTE)lpbiht + (UINT)lpbih->biSize); cm[0].from = COL_UNUSED; cm[0].to = GetColor(bScreen, (bSFCmanual ? CO_ELEMBK_SFC : CO_ELEMBK)); cm[1].from = GetColor(bScreen, CO_NORMAL); cm[1].to = GetColor(bScreen, (bCommented ? CO_COMMENT : CO_NORMAL)); for( i=0; i<iNumColors; i++ ) { if( RGB( pRGBQuad[i].rgbRed, pRGBQuad[i].rgbGreen, pRGBQuad[i].rgbBlue) == cm[0].from ) { pRGBQuad[i].rgbRed = GetRValue(cm[0].to); pRGBQuad[i].rgbGreen = GetGValue(cm[0].to); pRGBQuad[i].rgbBlue = GetBValue(cm[0].to); } else if( bCommented && RGB( pRGBQuad[i].rgbRed, pRGBQuad[i].rgbGreen, pRGBQuad[i].rgbBlue) == cm[1].from ) { pRGBQuad[i].rgbRed = GetRValue(cm[1].to); pRGBQuad[i].rgbGreen = GetGValue(cm[1].to); pRGBQuad[i].rgbBlue = GetBValue(cm[1].to); } } UnlockResource(hGlobal); FreeResource(hGlobal); return (LPBITMAPINFO)lpbiht; }
/*********************************************************************** * create_app_icon_images */ CFArrayRef create_app_icon_images(void) { HRSRC res_info; HGLOBAL res_data; GRPICONDIR *icon_dir; CFMutableArrayRef images = NULL; int i; TRACE("()\n"); res_info = NULL; EnumResourceNamesW(NULL, (LPCWSTR)RT_GROUP_ICON, get_first_resource, (LONG_PTR)&res_info); if (!res_info) { WARN("found no RT_GROUP_ICON resource\n"); return NULL; } if (!(res_data = LoadResource(NULL, res_info))) { WARN("failed to load RT_GROUP_ICON resource\n"); return NULL; } if (!(icon_dir = LockResource(res_data))) { WARN("failed to lock RT_GROUP_ICON resource\n"); goto cleanup; } images = CFArrayCreateMutable(NULL, icon_dir->idCount, &kCFTypeArrayCallBacks); if (!images) { WARN("failed to create images array\n"); goto cleanup; } for (i = 0; i < icon_dir->idCount; i++) { int width = icon_dir->idEntries[i].bWidth; int height = icon_dir->idEntries[i].bHeight; BOOL found_better_bpp = FALSE; int j; LPCWSTR name; HGLOBAL icon_res_data; BYTE *icon_bits; if (!width) width = 256; if (!height) height = 256; /* If there's another icon at the same size but with better color depth, skip this one. We end up making CGImages that are all 32 bits per pixel, so Cocoa doesn't get the original color depth info to pick the best representation itself. */ for (j = 0; j < icon_dir->idCount; j++) { int jwidth = icon_dir->idEntries[j].bWidth; int jheight = icon_dir->idEntries[j].bHeight; if (!jwidth) jwidth = 256; if (!jheight) jheight = 256; if (j != i && jwidth == width && jheight == height && icon_dir->idEntries[j].wBitCount > icon_dir->idEntries[i].wBitCount) { found_better_bpp = TRUE; break; } } if (found_better_bpp) continue; name = MAKEINTRESOURCEW(icon_dir->idEntries[i].nID); res_info = FindResourceW(NULL, name, (LPCWSTR)RT_ICON); if (!res_info) { WARN("failed to find RT_ICON resource %d with ID %hd\n", i, icon_dir->idEntries[i].nID); continue; } icon_res_data = LoadResource(NULL, res_info); if (!icon_res_data) { WARN("failed to load icon %d with ID %hd\n", i, icon_dir->idEntries[i].nID); continue; } icon_bits = LockResource(icon_res_data); if (icon_bits) { static const BYTE png_magic[] = { 0x89, 0x50, 0x4e, 0x47 }; CGImageRef cgimage = NULL; if (!memcmp(icon_bits, png_magic, sizeof(png_magic))) { CFDataRef data = CFDataCreate(NULL, (UInt8*)icon_bits, icon_dir->idEntries[i].dwBytesInRes); if (data) { CGDataProviderRef provider = CGDataProviderCreateWithCFData(data); CFRelease(data); if (provider) { cgimage = CGImageCreateWithPNGDataProvider(provider, NULL, FALSE, kCGRenderingIntentDefault); CGDataProviderRelease(provider); } } } if (!cgimage) { HICON icon; icon = CreateIconFromResourceEx(icon_bits, icon_dir->idEntries[i].dwBytesInRes, TRUE, 0x00030000, width, height, 0); if (icon) { cgimage = create_cgimage_from_icon(icon, width, height); DestroyIcon(icon); } else WARN("failed to create icon %d from resource with ID %hd\n", i, icon_dir->idEntries[i].nID); } if (cgimage) { CFArrayAppendValue(images, cgimage); CGImageRelease(cgimage); } } else WARN("failed to lock RT_ICON resource %d with ID %hd\n", i, icon_dir->idEntries[i].nID); FreeResource(icon_res_data); } cleanup: if (images && !CFArrayGetCount(images)) { CFRelease(images); images = NULL; } FreeResource(res_data); return images; }
/* * Redirect one window for one client */ int compRedirectWindow (ClientPtr pClient, WindowPtr pWin, int update) { CompWindowPtr cw = GetCompWindow (pWin); CompClientWindowPtr ccw; CompScreenPtr cs = GetCompScreen(pWin->drawable.pScreen); WindowPtr pLayerWin; Bool anyMarked = FALSE; if (pWin == cs->pOverlayWin) { return Success; } if (!pWin->parent) return BadMatch; /* * Only one Manual update is allowed */ if (cw && update == CompositeRedirectManual) for (ccw = cw->clients; ccw; ccw = ccw->next) if (ccw->update == CompositeRedirectManual) return BadAccess; /* * Allocate per-client per-window structure * The client *could* allocate multiple, but while supported, * it is not expected to be common */ ccw = malloc(sizeof (CompClientWindowRec)); if (!ccw) return BadAlloc; ccw->id = FakeClientID (pClient->index); ccw->update = update; /* * Now make sure there's a per-window structure to hang this from */ if (!cw) { cw = malloc(sizeof (CompWindowRec)); if (!cw) { free(ccw); return BadAlloc; } cw->damage = DamageCreate (compReportDamage, compDestroyDamage, DamageReportNonEmpty, FALSE, pWin->drawable.pScreen, pWin); if (!cw->damage) { free(ccw); free(cw); return BadAlloc; } anyMarked = compMarkWindows (pWin, &pLayerWin); /* Make sure our borderClip is correct for ValidateTree */ RegionNull(&cw->borderClip); RegionCopy(&cw->borderClip, &pWin->borderClip); cw->borderClipX = pWin->drawable.x; cw->borderClipY = pWin->drawable.y; cw->update = CompositeRedirectAutomatic; cw->clients = 0; cw->oldx = COMP_ORIGIN_INVALID; cw->oldy = COMP_ORIGIN_INVALID; cw->damageRegistered = FALSE; cw->damaged = FALSE; cw->pOldPixmap = NullPixmap; dixSetPrivate(&pWin->devPrivates, CompWindowPrivateKey, cw); } ccw->next = cw->clients; cw->clients = ccw; if (!AddResource (ccw->id, CompositeClientWindowType, pWin)) return BadAlloc; if (ccw->update == CompositeRedirectManual) { if (!anyMarked) anyMarked = compMarkWindows (pWin, &pLayerWin); if (cw->damageRegistered) { DamageUnregister (&pWin->drawable, cw->damage); cw->damageRegistered = FALSE; } cw->update = CompositeRedirectManual; } else if (cw->update == CompositeRedirectAutomatic && !cw->damageRegistered) { if (!anyMarked) anyMarked = compMarkWindows (pWin, &pLayerWin); } if (!compCheckRedirect (pWin)) { FreeResource (ccw->id, RT_NONE); return BadAlloc; } if (anyMarked) compHandleMarkedWindows (pWin, pLayerWin); return Success; }
static int ProcAppleWMSelectInput (register ClientPtr client) { REQUEST(xAppleWMSelectInputReq); WMEventPtr pEvent, pNewEvent, *pHead; XID clientResource; int i; REQUEST_SIZE_MATCH (xAppleWMSelectInputReq); i = dixLookupResourceByType((pointer *)&pHead, eventResource, EventType, client, DixWriteAccess); if (stuff->mask != 0) { if (i == Success && pHead) { /* check for existing entry. */ for (pEvent = *pHead; pEvent; pEvent = pEvent->next) { if (pEvent->client == client) { pEvent->mask = stuff->mask; updateEventMask (pHead); return Success; } } } /* build the entry */ pNewEvent = (WMEventPtr) xalloc (sizeof (WMEventRec)); if (!pNewEvent) return BadAlloc; pNewEvent->next = 0; pNewEvent->client = client; pNewEvent->mask = stuff->mask; /* * add a resource that will be deleted when * the client goes away */ clientResource = FakeClientID (client->index); pNewEvent->clientResource = clientResource; if (!AddResource (clientResource, ClientType, (pointer)pNewEvent)) return BadAlloc; /* * create a resource to contain a pointer to the list * of clients selecting input. This must be indirect as * the list may be arbitrarily rearranged which cannot be * done through the resource database. */ if (i != Success || !pHead) { pHead = (WMEventPtr *) xalloc (sizeof (WMEventPtr)); if (!pHead || !AddResource (eventResource, EventType, (pointer)pHead)) { FreeResource (clientResource, RT_NONE); return BadAlloc; } *pHead = 0; } pNewEvent->next = *pHead; *pHead = pNewEvent; updateEventMask (pHead); } else if (stuff->mask == 0) { /* delete the interest */ if (i == Success && pHead) { pNewEvent = 0; for (pEvent = *pHead; pEvent; pEvent = pEvent->next) { if (pEvent->client == client) break; pNewEvent = pEvent; } if (pEvent) { FreeResource (pEvent->clientResource, ClientType); if (pNewEvent) pNewEvent->next = pEvent->next; else *pHead = pEvent->next; xfree (pEvent); updateEventMask (pHead); } } } else { client->errorValue = stuff->mask; return BadValue; } return Success; }
// code taken from LoadJpegResourceAsRGB and WCS's ImageInputFormat.cpp // memory is allocated with operator new[], caller is responsible for freeing int LoadPNGResourceAsRGBA(unsigned short ImageID, unsigned char *&Red, unsigned char *&Green, unsigned char *&Blue, unsigned char *&Alpha, unsigned long int &Width, unsigned long int &Height) { int Success = 0; HRSRC ResHandle = NULL; png_structp png_ptr; png_infop info_ptr, end_info; png_uint_32 width, height; int bit_depth, color_type, interlace_type, number_of_passes = 1, Pass; int row_stride = 0; short Cols, Rows; unsigned char *InterleaveBuf = NULL, *RBuf, *GBuf, *BBuf, *ABuf, BytesPerPixel; WORD LOGOID = ImageID; bool AllIsWell = false, DoAlpha = false, AlphaFailed = false; unsigned long int InScan, PixelCol, WorkRow; Width = Height = 0; Red = Green = Blue = Alpha = NULL; // passing NULL as Instance means 'me you moron' if(ImagePNGRsc = LockResource(LoadResource(NULL, ResHandle = FindResource(NULL, MAKEINTRESOURCE(LOGOID), "PNGIMAGE")))) { ImagePNGSize = SizeofResource(NULL, ResHandle); ImagePNGRscCur = (unsigned char *)ImagePNGRsc; // use as byte stream if(png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, (png_voidp)NULL, NULL, NULL)) { if(info_ptr = png_create_info_struct(png_ptr)) { if(end_info = png_create_info_struct(png_ptr)) { AllIsWell = true; } // if else { png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL); } // else } // if else { png_destroy_read_struct(&png_ptr, (png_infopp)NULL, (png_infopp)NULL); } // else } // if if(!AllIsWell) { FreeResource(ImagePNGRsc); ImagePNGRsc = NULL; return(0); } // if if (setjmp(png_jmpbuf(png_ptr))) { // If we get here, the PNG code has signaled an error. // We need to clean up the PNG object, close the input file, and return. if(InterleaveBuf) delete [] InterleaveBuf; // AppMem_Free(InterleaveBuf, row_stride); InterleaveBuf = NULL; InterleaveBuf = NULL; if(!Success) { delete [] Red; Red = NULL; delete [] Green; Green = NULL; delete [] Blue; Blue = NULL; delete [] Alpha; Alpha = NULL; } // if png_destroy_read_struct(&png_ptr, &info_ptr, &end_info); return(Success); } // if //png_init_io(png_ptr, fh); // for FILE IO png_set_read_fn(png_ptr, ImagePNGRsc, PNG_user_read_data); // for custom memory IO (read only) png_read_info(png_ptr, info_ptr); png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, NULL, NULL); if (color_type == PNG_COLOR_TYPE_PALETTE) png_set_palette_to_rgb(png_ptr); if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) png_set_gray_1_2_4_to_8(png_ptr); if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) png_set_tRNS_to_alpha(png_ptr); if (bit_depth == 16) png_set_strip_16(png_ptr); if (color_type & PNG_COLOR_MASK_ALPHA) { DoAlpha = true; BytesPerPixel = 4; } // if else { DoAlpha = false; BytesPerPixel = 3; } // else if (interlace_type == PNG_INTERLACE_ADAM7) { //number_of_passes = png_set_interlace_handling(png_ptr); //GlobalApp->StatusLog->PostStockError(WCS_LOG_ERR_READ_FAIL, "Interlaced PNG currently not supported."); AllIsWell = 0; } // if if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { png_set_gray_to_rgb(png_ptr); } // if if(AllIsWell) { png_read_update_info(png_ptr, info_ptr); Width = Cols = (short)width; Height = Rows = (short)height; Red = new unsigned char[Cols * Rows]; Green = new unsigned char[Cols * Rows]; Blue = new unsigned char[Cols * Rows]; if(DoAlpha) { Alpha = new unsigned char[Cols * Rows]; if(!Alpha) { AlphaFailed = true; } // if } // if row_stride = width * BytesPerPixel; InterleaveBuf = new unsigned char[row_stride]; if(InterleaveBuf && Red && Green && Blue && !AlphaFailed) // everything ok? { // Clear bitmaps memset(Red, 0, Cols * Rows); memset(Green, 0, Cols * Rows); memset(Blue, 0, Cols * Rows); if(DoAlpha && Alpha) { memset(Alpha, 0, Cols * Rows); } // if for(Pass = 0; Pass < number_of_passes; Pass++) { for(WorkRow = 0; WorkRow < height; WorkRow++) { RBuf = &Red[WorkRow * Cols]; GBuf = &Green[WorkRow * Cols]; BBuf = &Blue[WorkRow * Cols]; if(DoAlpha) ABuf = &Alpha[WorkRow * Cols]; if(number_of_passes != 1) { // interleave requires read-in and interleaving from our // buffers into the InterleaveBuf so the png code can add // to exisitng data for(InScan = PixelCol = 0; PixelCol < (unsigned)Cols; PixelCol++) { InterleaveBuf[InScan++] = RBuf[PixelCol]; InterleaveBuf[InScan++] = GBuf[PixelCol]; InterleaveBuf[InScan++] = BBuf[PixelCol]; if(DoAlpha) InterleaveBuf[InScan++] = ABuf[PixelCol]; } // for } // if png_read_row(png_ptr, InterleaveBuf, NULL); for(InScan = PixelCol = 0; PixelCol < (unsigned)Cols; PixelCol++) { RBuf[PixelCol] = InterleaveBuf[InScan++]; GBuf[PixelCol] = InterleaveBuf[InScan++]; BBuf[PixelCol] = InterleaveBuf[InScan++]; if(DoAlpha) ABuf[PixelCol] = InterleaveBuf[InScan++]; } // for } // for } // for if((WorkRow == height) && (Pass == number_of_passes)) { Success = 1; png_read_end(png_ptr, end_info); } // if } // if } // if AllIsWell png_destroy_read_struct(&png_ptr, &info_ptr, &end_info); if(InterleaveBuf) delete [] InterleaveBuf; InterleaveBuf = NULL; } // if if(ImagePNGRsc) { FreeResource(ImagePNGRsc); ImagePNGRsc = NULL; } // if return(Success); } // LoadPNGResourceAsRGBA
static bool LoadMind(const TCHAR* filename, int &line) { TCHAR* fullname = GetFullName(filename); HCURSOR newCur = LoadCursor(NULL, MAKEINTRESOURCE(IDC_WAIT)); HCURSOR oldCur = SetCursor(newCur); #ifdef DEBUG_LOAD_TIME unsigned __int64 t = __rdtsc(); #endif Mind* mind = new Mind(); line = -1; try { mind->Load(fullname); } catch (Mind::CorruptedMind c) { line = c.line; delete mind; if (fullname != filename) delete[] fullname; SetCursor(oldCur); return false; } catch (...) { delete mind; if (fullname != filename) delete[] fullname; SetCursor(oldCur); return false; } if (fullname != filename) delete[] fullname; #ifdef DEBUG_LOAD_TIME t = __rdtsc() - t; char dest[101]; mir_snprintf(dest, "%I64d ticks\n", t / 3200000); MessageBoxA(NULL, dest, NULL, 0); //exit(0); #endif SetCursor(oldCur); HRSRC hRes = FindResource(hInst, MAKEINTRESOURCE(IDR_SMILES), _T("SMILES")); if (!hRes) { delete mind; return false; } DWORD size = SizeofResource(hInst, hRes); if (!size) { delete mind; return false; } HGLOBAL hGlob = LoadResource(hInst, hRes); if (!hGlob) { delete mind; return false; } void *data = LockResource(hGlob); if (!data) { FreeResource(hGlob); delete mind; return false; } bool res = true; try { mind->LoadSmiles(data, size); } catch (...) { res = false; } UnlockResource(data); FreeResource(hGlob); if (!res) { delete mind; return false; } delete bot; bot = new TalkBot(*mind); delete mind; UpdateEngine(); return true; }
BOOL CRRECToolbar::Create( CWnd* parent, CRect& rc ) /* ============================================================ Function : CRRECToolbar::Create Description : Creates the toolbar control Access : Public Return : BOOL - "TRUE" if success Parameters : CWnd* parent - Parent editor CRect& rc - Rectangle to place toolbar in. Usage : Called from the parent editor ============================================================*/ { BOOL result = FALSE; HINSTANCE hInstance = AfxFindResourceHandle( MAKEINTRESOURCE( TOOLBAR_CONTROL ), RT_TOOLBAR ); if(!hInstance) return FALSE; HRSRC hRsrc = ::FindResource( hInstance, MAKEINTRESOURCE( TOOLBAR_CONTROL ), RT_TOOLBAR ); if( !hRsrc ) return FALSE; HGLOBAL hGlobal = LoadResource( hInstance, hRsrc ); if (hGlobal == NULL) return FALSE; CToolBarData* pData = ( CToolBarData* ) LockResource( hGlobal ); if (pData == NULL) return FALSE; ASSERT( pData->wVersion == 1 ); TBBUTTON tb, tbSep; memset ( &tb, 0, sizeof( tb ) ); memset ( &tbSep, 0, sizeof( tbSep ) ); result = CToolBarCtrl::Create(WS_VISIBLE|WS_CHILD, rc, parent, TOOLBAR_CONTROL); if( result ) { SetButtonStructSize( sizeof ( tb ) ); CSize sz ( pData->wWidth, pData->wHeight ); SetBitmapSize( sz ); sz.cx += 4; sz.cy += 4; SetButtonSize( sz ); // Loop through adding buttons. tb.fsState = TBSTATE_ENABLED; tb.fsStyle = TBSTYLE_BUTTON; tb.iString = -1; tb.iBitmap = 0; tbSep.iString = -1; tbSep.fsStyle = TBSTYLE_SEP; for( WORD w = 0; w < pData->wItemCount; w++ ) { if ( pData->items()[ w ] == 0 ) AddButtons( 1, &tbSep ); else { tb.idCommand = pData->items()[ w ]; AddButtons( 1, &tb ); tb.iBitmap++; } } HBITMAP hBitmap = (HBITMAP) ::LoadImage( hInstance, MAKEINTRESOURCE( TOOLBAR_CONTROL ), IMAGE_BITMAP, 0,0, LR_LOADMAP3DCOLORS ); if( !hBitmap ) return FALSE; BITMAP bm; memset( &bm, 0, sizeof ( bm ) ); ::GetObject( hBitmap, sizeof ( bm ), &bm ); AddBitmap( bm.bmWidth / pData->wWidth, CBitmap::FromHandle ( hBitmap ) ); UnlockResource( hGlobal ); FreeResource( hGlobal ); ///////////////////////////////////// // Map in combo boxes // CRect rect; TBBUTTONINFO tbi; tbi.cbSize = sizeof( TBBUTTONINFO ); tbi.cx = FONT_COMBO_WIDTH; tbi.dwMask = TBIF_SIZE | 0x80000000; // By index SetButtonInfo( FONT_NAME_POS, &tbi ); GetItemRect( FONT_NAME_POS, &rect ); rect.bottom += COMBO_HEIGHT; // The font name combo if( m_font.Create( WS_CHILD | WS_VSCROLL | WS_VISIBLE | CBS_AUTOHSCROLL | CBS_DROPDOWN | CBS_SORT | CBS_HASSTRINGS, rect, this, DROPDOWN_FONT ) ) { m_font.SetFont( CFont::FromHandle( ( HFONT ) ::GetStockObject( ANSI_VAR_FONT ) ) ); m_font.FillCombo(); tbi.cx = COMBO_WIDTH; SetButtonInfo( FONT_SIZE_POS, &tbi ); GetItemRect( FONT_SIZE_POS, &rect ); rect.bottom += COMBO_HEIGHT; // The font size combo if( m_size.Create( WS_CHILD | WS_VISIBLE | CBS_AUTOHSCROLL | CBS_DROPDOWNLIST | CBS_HASSTRINGS, rect, this, DROPDOWN_SIZE ) ) { m_size.SetFont( CFont::FromHandle( ( HFONT ) ::GetStockObject( ANSI_VAR_FONT ) ) ); m_size.FillCombo(); CString color; CString defaultText; CString customText; color.LoadString( STRING_COLOR ); defaultText.LoadString( STRING_DEFAULT ); customText.LoadString( STRING_CUSTOM ); tbi.cx = COLOR_WIDTH; SetButtonInfo( FONT_COLOR_POS, &tbi ); GetItemRect( FONT_COLOR_POS, &rect ); // The color picker if( m_color.Create( color, WS_VISIBLE| WS_CHILD, rect, this, BUTTON_COLOR ) ) { m_color.SetDefaultText( defaultText ); m_color.SetCustomText( customText ); m_color.SetSelectionMode( CP_MODE_TEXT ); m_color.SetBkColour( RGB( 255, 255, 255 ) ); m_color.SetFont( CFont::FromHandle( ( HFONT ) ::GetStockObject( ANSI_VAR_FONT ) ) ); result = TRUE; } } } } return result; }
static int ProcShapeSelectInput(ClientPtr client) { REQUEST(xShapeSelectInputReq); WindowPtr pWin; ShapeEventPtr pShapeEvent, pNewShapeEvent, *pHead; XID clientResource; int rc; REQUEST_SIZE_MATCH(xShapeSelectInputReq); rc = dixLookupWindow(&pWin, stuff->window, client, DixReceiveAccess); if (rc != Success) return rc; rc = dixLookupResourceByType((pointer *) &pHead, pWin->drawable.id, ShapeEventType, client, DixWriteAccess); if (rc != Success && rc != BadValue) return rc; switch (stuff->enable) { case xTrue: if (pHead) { /* check for existing entry. */ for (pShapeEvent = *pHead; pShapeEvent; pShapeEvent = pShapeEvent->next) { if (pShapeEvent->client == client) return Success; } } /* build the entry */ pNewShapeEvent = malloc(sizeof(ShapeEventRec)); if (!pNewShapeEvent) return BadAlloc; pNewShapeEvent->next = 0; pNewShapeEvent->client = client; pNewShapeEvent->window = pWin; /* * add a resource that will be deleted when * the client goes away */ clientResource = FakeClientID(client->index); pNewShapeEvent->clientResource = clientResource; if (!AddResource(clientResource, ClientType, (pointer) pNewShapeEvent)) return BadAlloc; /* * create a resource to contain a pointer to the list * of clients selecting input. This must be indirect as * the list may be arbitrarily rearranged which cannot be * done through the resource database. */ if (!pHead) { pHead = malloc(sizeof(ShapeEventPtr)); if (!pHead || !AddResource(pWin->drawable.id, ShapeEventType, (pointer) pHead)) { FreeResource(clientResource, RT_NONE); return BadAlloc; } *pHead = 0; } pNewShapeEvent->next = *pHead; *pHead = pNewShapeEvent; break; case xFalse: /* delete the interest */ if (pHead) { pNewShapeEvent = 0; for (pShapeEvent = *pHead; pShapeEvent; pShapeEvent = pShapeEvent->next) { if (pShapeEvent->client == client) break; pNewShapeEvent = pShapeEvent; } if (pShapeEvent) { FreeResource(pShapeEvent->clientResource, ClientType); if (pNewShapeEvent) pNewShapeEvent->next = pShapeEvent->next; else *pHead = pShapeEvent->next; free(pShapeEvent); } } break; default: client->errorValue = stuff->enable; return BadValue; } return Success; }
////////////////////////////////////////////////////////////////////////////////////////////////// // // Load string from resource with special langID // BOOL LoadStringExx( HINSTANCE hInst, // Hinstance of lib WORD wLangID, // Language ID of resource PRES_STRING_INFO pInfo // Pointer to the string info ) { HRSRC hFindRes; // Handle of the resources has been found HGLOBAL hLoadRes; // Handle of the resources has been loaded LPVOID pRes; // Pointer to the resources UINT nBlockID; // String block ID pInfo->dwFileOffset = 0; // String offset in the file pInfo->dwBytes = 0; // String length, in bytes pInfo->pszText = NULL; nBlockID = pInfo->uStringID / 16 + 1; __try { // find the string block hFindRes = FindResourceEx(hInst, RT_STRING, MAKEINTRESOURCE(nBlockID), wLangID); if(!hFindRes ) { __leave; } hLoadRes = LoadResource(hInst, hFindRes); if(!hLoadRes ) { __leave; } pRes = LockResource(hLoadRes); if(!pRes ) { __leave; } WCHAR* pParse = (WCHAR *)pRes; // Pointer to the String block UINT nIndex = pInfo->uStringID % 16; // Calculate the string index int nLen; UINT i; // 16 strings per block for( i = 0; i < (nIndex & 15); i++ ) { pParse += 1 + (int)*pParse; } // OK, we get it nLen = (UINT)*pParse; // The length of the target string. pParse += 1; // Pointer to the target string // Main point, calculate the string offset pInfo->dwFileOffset = (DWORD) ( (DWORD_PTR)pParse - (DWORD_PTR)hInst ) + 1; pInfo->dwBytes = nLen * sizeof(WCHAR); // allocate memory pInfo->pszText = (LPWSTR)MALLOC((nLen + 1) * sizeof(WCHAR)); if (!pInfo->pszText) __leave; // copy string for return CopyMemory((LPVOID)pInfo->pszText, (LPVOID)pParse, pInfo->dwBytes); *(PWCHAR)((DWORD_PTR)pInfo->pszText + pInfo->dwBytes) = 0; //TRACEF(_T("String ID: %5d \t%s"), pszText); } __finally { // Clean up, free memory if (pRes) UnlockResource(pRes); if (hFindRes) FreeResource(hFindRes); } // if pointer is null, we return a NULL string if (!pInfo->pszText) { pInfo->pszText = (LPWSTR)MALLOC(sizeof(WCHAR)); pInfo->pszText[0] = 0; } return TRUE; } // LoadStringExx()
LPCSTRINGTEMPLATE TaLocale_GetStringResource (int ids, HINSTANCE *phInstFound) { // Strings are organized into heaps of String Tables, each table // holding 16 strings (regardless of their length). The first table's // first string index is for string #1. When searching for a string, // the string's table is the index given to FindResource. // LPCSTRINGTEMPLATE pst = NULL; LANGID lang = TaLocale_GetLanguage(); int iTable = (ids / 16) + 1; // 1 = first string table int iIndex = ids - ((iTable-1) * 16); // 0 = first string in the table HINSTANCE hInstance = NULL; size_t iModule = 0; for (; !pst && TaLocale_EnumModule (iModule, &hInstance); ++iModule) { HRSRC hr; if ((hr = FindResourceEx (hInstance, RT_STRING, MAKEINTRESOURCE( iTable ), lang)) == NULL) { // Our translation teams don't usually change the language // constants within .RC files, so we should look for English // language translations too. // if ((hr = FindResourceEx (hInstance, RT_STRING, MAKEINTRESOURCE( iTable ), MAKELANGID(LANG_ENGLISH,SUBLANG_ENGLISH_US))) == NULL) { // If we still can't find it, we'll take anything... // if ((hr = FindResource (hInstance, RT_STRING, MAKEINTRESOURCE( iTable ))) == NULL) continue; } } HGLOBAL hg; if ((hg = LoadResource (hInstance, hr)) != NULL) { const WORD *pTable; if ((pTable = (WORD*)LockResource (hg)) != NULL) { try { // Skip words in the string table until we reach the string // index we're looking for. // for (int iIndexWalk = iIndex; iIndexWalk && ((LPCSTRINGTEMPLATE)pTable)->cchString; --iIndexWalk) { pTable += 1 + ((LPCSTRINGTEMPLATE)pTable)->cchString; } if (IsValidStringTemplate ((LPCSTRINGTEMPLATE)pTable)) { pst = (LPCSTRINGTEMPLATE)pTable; if (phInstFound) *phInstFound = hInstance; } else { UnlockResource(pTable); FreeResource(hg); } } catch(...) { UnlockResource(pTable); FreeResource(hg); // If we walked off the end of the table, then the // string we want just wasn't there. } } } } return pst; }
INT_PTR CALLBACK DlgProcAbout(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) { static int iState = 0; switch (msg) { case WM_INITDIALOG: TranslateDialogDefault(hwndDlg); { TCHAR filename[MAX_PATH], *productCopyright; DWORD unused; DWORD verInfoSize; UINT blockSize; PVOID pVerInfo; GetModuleFileName(NULL,filename,SIZEOF(filename)); verInfoSize=GetFileVersionInfoSize(filename,&unused); pVerInfo=mir_alloc(verInfoSize); GetFileVersionInfo(filename,0,verInfoSize,pVerInfo); VerQueryValue(pVerInfo,_T("\\StringFileInfo\\000004b0\\LegalCopyright"),(LPVOID*)&productCopyright,&blockSize); SetDlgItemText(hwndDlg,IDC_DEVS,productCopyright); mir_free(pVerInfo); } { char productVersion[56], *p; int isAnsi = 0; TCHAR str[64]; CallService(MS_SYSTEM_GETVERSIONTEXT,SIZEOF(productVersion),(LPARAM)productVersion); // Hide Unicode from version text as it is assumed at this point p = strstr(productVersion, " Unicode"); if (p) *p = '\0'; else isAnsi = 1; mir_sntprintf(str,SIZEOF(str),_T(STR_VERSION_FORMAT), TranslateT("v"), productVersion, isAnsi?" ANSI":""); { TCHAR oldTitle[256], newTitle[256]; GetDlgItemText( hwndDlg, IDC_HEADERBAR, oldTitle, SIZEOF( oldTitle )); mir_sntprintf( newTitle, SIZEOF(newTitle), oldTitle, str ); SetDlgItemText( hwndDlg, IDC_HEADERBAR, newTitle ); } mir_sntprintf(str,SIZEOF(str),TranslateT("Built %s %s"),_T(__DATE__),_T(__TIME__)); SetDlgItemText(hwndDlg,IDC_BUILDTIME,str); } ShowWindow(GetDlgItem(hwndDlg, IDC_CREDITSFILE), SW_HIDE); { HRSRC hResInfo = FindResource(hMirandaInst,MAKEINTRESOURCE(IDR_CREDITS),_T("TEXT")); DWORD ResSize = SizeofResource(hMirandaInst,hResInfo); HGLOBAL hRes = LoadResource(hMirandaInst,hResInfo); char* pszMsg = (char*)LockResource(hRes); if (pszMsg) { char* pszMsgt = (char*)alloca(ResSize + 1); memcpy(pszMsgt, pszMsg, ResSize); pszMsgt[ResSize] = 0; TCHAR *ptszMsg; if (ResSize >=3 && pszMsgt[0] == '\xef' && pszMsgt[1] == '\xbb' && pszMsgt[2] == '\xbf') ptszMsg = Utf8DecodeT(pszMsgt + 3); else ptszMsg = mir_a2t_cp(pszMsgt, 1252); SetDlgItemText(hwndDlg, IDC_CREDITSFILE, ptszMsg); UnlockResource(pszMsg); mir_free(ptszMsg); } FreeResource(hRes); } Window_SetIcon_IcoLib(hwndDlg, SKINICON_OTHER_MIRANDA); return TRUE; case WM_COMMAND: switch( LOWORD( wParam )) { case IDOK: case IDCANCEL: DestroyWindow(hwndDlg); return TRUE; case IDC_CONTRIBLINK: if (iState) { iState = 0; SetDlgItemText(hwndDlg, IDC_CONTRIBLINK, TranslateT("Credits >")); ShowWindow(GetDlgItem(hwndDlg, IDC_DEVS), SW_SHOW); ShowWindow(GetDlgItem(hwndDlg, IDC_BUILDTIME), SW_SHOW); ShowWindow(GetDlgItem(hwndDlg, IDC_CREDITSFILE), SW_HIDE); } else { iState = 1; SetDlgItemText(hwndDlg, IDC_CONTRIBLINK, TranslateT("< Copyright")); ShowWindow(GetDlgItem(hwndDlg, IDC_DEVS), SW_HIDE); ShowWindow(GetDlgItem(hwndDlg, IDC_BUILDTIME), SW_HIDE); ShowWindow(GetDlgItem(hwndDlg, IDC_CREDITSFILE), SW_SHOW); } break; } break; case WM_CTLCOLOREDIT: case WM_CTLCOLORSTATIC: switch ( GetWindowLongPtr(( HWND )lParam, GWL_ID )) { case IDC_WHITERECT: case IDC_BUILDTIME: case IDC_CREDITSFILE: case IDC_DEVS: SetTextColor((HDC)wParam,GetSysColor(COLOR_WINDOWTEXT)); break; default: return FALSE; } SetBkColor((HDC)wParam, GetSysColor(COLOR_WINDOW)); return (INT_PTR)GetSysColorBrush(COLOR_WINDOW); case WM_DESTROY: Window_FreeIcon_IcoLib( hwndDlg ); { HFONT hFont=(HFONT)SendDlgItemMessage(hwndDlg,IDC_VERSION,WM_GETFONT,0,0); SendDlgItemMessage(hwndDlg,IDC_VERSION,WM_SETFONT,SendDlgItemMessage(hwndDlg,IDOK,WM_GETFONT,0,0),0); DeleteObject(hFont); } break; } return FALSE; }
static int ProcPanoramiXShmCreatePixmap(ClientPtr client) { ScreenPtr pScreen = NULL; PixmapPtr pMap = NULL; DrawablePtr pDraw; DepthPtr pDepth; int i, j, result, rc; ShmDescPtr shmdesc; REQUEST(xShmCreatePixmapReq); unsigned int width, height, depth; unsigned long size; PanoramiXRes *newPix; REQUEST_SIZE_MATCH(xShmCreatePixmapReq); client->errorValue = stuff->pid; if (!sharedPixmaps) return BadImplementation; LEGAL_NEW_RESOURCE(stuff->pid, client); rc = dixLookupDrawable(&pDraw, stuff->drawable, client, M_ANY, DixGetAttrAccess); if (rc != Success) return rc; VERIFY_SHMPTR(stuff->shmseg, stuff->offset, TRUE, shmdesc, client); width = stuff->width; height = stuff->height; depth = stuff->depth; if (!width || !height || !depth) { client->errorValue = 0; return BadValue; } if (width > 32767 || height > 32767) return BadAlloc; if (stuff->depth != 1) { pDepth = pDraw->pScreen->allowedDepths; for (i=0; i<pDraw->pScreen->numDepths; i++, pDepth++) if (pDepth->depth == stuff->depth) goto CreatePmap; client->errorValue = stuff->depth; return BadValue; } CreatePmap: size = PixmapBytePad(width, depth) * height; if (sizeof(size) == 4 && BitsPerPixel(depth) > 8) { if (size < width * height) return BadAlloc; } /* thankfully, offset is unsigned */ if (stuff->offset + size < size) return BadAlloc; VERIFY_SHMSIZE(shmdesc, stuff->offset, size, client); if(!(newPix = malloc(sizeof(PanoramiXRes)))) return BadAlloc; newPix->type = XRT_PIXMAP; newPix->u.pix.shared = TRUE; panoramix_setup_ids(newPix, client, stuff->pid); result = Success; FOR_NSCREENS(j) { ShmScrPrivateRec *screen_priv; pScreen = screenInfo.screens[j]; screen_priv = ShmGetScreenPriv(pScreen); pMap = (*screen_priv->shmFuncs->CreatePixmap)(pScreen, stuff->width, stuff->height, stuff->depth, shmdesc->addr + stuff->offset); if (pMap) { dixSetPrivate(&pMap->devPrivates, shmPixmapPrivateKey, shmdesc); shmdesc->refcnt++; pMap->drawable.serialNumber = NEXT_SERIAL_NUMBER; pMap->drawable.id = newPix->info[j].id; if (!AddResource(newPix->info[j].id, RT_PIXMAP, (pointer)pMap)) { (*pScreen->DestroyPixmap)(pMap); result = BadAlloc; break; } } else { result = BadAlloc; break; } } if(result == BadAlloc) { while(j--) { (*pScreen->DestroyPixmap)(pMap); FreeResource(newPix->info[j].id, RT_NONE); } free(newPix); } else AddResource(stuff->pid, XRT_PIXMAP, newPix); return result; }
int CWaitDlg::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)) { CDC* pDC = m_MessageCtrl.GetWindowDC(); CFont* pFont = pDC->SelectObject(m_MessageCtrl.GetFont()); CRect compRect; m_MessageCtrl.GetClientRect(compRect); m_MessageCtrl.SetWindowText(GetTextWithEllipsis(pDC,m_szMessage,compRect)); pDC->SelectObject(pFont); UINT nTimer = SetTimer(1,GRANULARITY,0); 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); KillTimer(nTimer); } } CATCH_ALL(e) { e->Delete(); 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; }
// Copied from MFC sources to enable a call to our CreateDlgIndirect() INT_PTR BaseDialog::DoModal() { 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); if (lpDialogTemplate == NULL) return -1; HWND hWndParent = PreModal(); AfxUnhookWindowCreate(); BOOL bEnableParent = FALSE; if (hWndParent && hWndParent != ::GetDesktopWindow() && ::IsWindowEnabled(hWndParent)) { ::EnableWindow(hWndParent, FALSE); bEnableParent = TRUE; } TRY { AfxHookWindowCreate(this); if (CreateDlgIndirect(lpDialogTemplate, CWnd::FromHandle(hWndParent), hInst)) { if (m_nFlags & WF_CONTINUEMODAL) { DWORD dwFlags = MLF_SHOWONIDLE; if (GetStyle() & DS_NOIDLEMSG) dwFlags |= MLF_NOIDLEMSG; RunModalLoop(dwFlags); } if (m_hWnd != NULL) { SetWindowPos(NULL, 0, 0, 0, 0, SWP_HIDEWINDOW| SWP_NOSIZE|SWP_NOMOVE|SWP_NOACTIVATE|SWP_NOZORDER); } } } CATCH_ALL(e) { e->Delete(); m_nModalResult = -1; } END_CATCH_ALL if (bEnableParent) ::EnableWindow(hWndParent, TRUE); if (hWndParent != NULL && ::GetActiveWindow() == m_hWnd) ::SetActiveWindow(hWndParent); DestroyWindow(); PostModal(); if (m_lpszTemplateName != NULL || m_hDialogTemplate != NULL) UnlockResource(hDialogTemplate); if (m_lpszTemplateName != NULL) FreeResource(hDialogTemplate); return m_nModalResult; }
void XGToolbarView::ChangeToolbar(short resID) { unsigned short i,len; if (fResID == resID) return; if (fOverTool != 0xFFFF) XGToolTip::CloseTip(); fResID = resID; #if OPT_MACOS == 1 Handle h; h = ::GetResource('Tool',fResID); Assert(h != NULL); ::HLock(h); fToolbar.SetSize((unsigned long)::GetHandleSize(h)); memcpy(*fToolbar,*h,fToolbar.GetSize()); ::HUnlock(h); ::ReleaseResource(h); #endif #if OPT_WINOS == 1 HRSRC hsrc; HGLOBAL h; void *data; hsrc = ::FindResource(_GInstance,MAKEINTRESOURCE(fResID),"Tool"); Assert(hsrc != NULL); h = LoadResource(_GInstance,hsrc); Assert(h != NULL); data = LockResource(h); /* * Now create the object */ fToolbar.SetSize(::SizeofResource(_GInstance,hsrc)); memcpy(*fToolbar,data,fToolbar.GetSize()); /* * Release the resource */ UnlockResource(h); FreeResource(h); #endif #if OPT_XWIN == 1 void *data; data = ::GetResourceData('Tool',fResID); Assert(data != NULL); fToolbar.SetSize(::GetResourceSize('Tool',fResID)); memcpy(*fToolbar,data,fToolbar.GetSize()); #endif fStatus.SetSize(len = GetToolLength()); for (i = 0; i < len; i++) fStatus.SetChar(i,0); fOverTool = 0xFFFF; /* * Redraw me */ InvalView(); }
static int XFixesSelectSelectionInput (ClientPtr pClient, Atom selection, WindowPtr pWindow, CARD32 eventMask) { int rc; SelectionEventPtr *prev, e; rc = XaceHook(XACE_SELECTION_ACCESS, pClient, selection, DixGetAttrAccess); if (rc != Success) return rc; for (prev = &selectionEvents; (e = *prev); prev = &e->next) { if (e->selection == selection && e->pClient == pClient && e->pWindow == pWindow) { break; } } if (!eventMask) { if (e) { FreeResource (e->clientResource, 0); } return Success; } if (!e) { e = (SelectionEventPtr) xalloc (sizeof (SelectionEventRec)); if (!e) return BadAlloc; e->next = 0; e->selection = selection; e->pClient = pClient; e->pWindow = pWindow; e->clientResource = FakeClientID(pClient->index); /* * Add a resource hanging from the window to * catch window destroy */ if (!LookupIDByType(pWindow->drawable.id, SelectionWindowType)) if (!AddResource (pWindow->drawable.id, SelectionWindowType, (pointer) pWindow)) { xfree (e); return BadAlloc; } if (!AddResource (e->clientResource, SelectionClientType, (pointer) e)) return BadAlloc; *prev = e; if (!CheckSelectionCallback ()) { FreeResource (e->clientResource, 0); return BadAlloc; } } e->eventMask = eventMask; return Success; }
//************************************************************************ BOOL CDirSnd::LoadWaveResource(LPSTR lpSound, HINSTANCE hInstance, BOOL b3D) // lpSound is a resource name //************************************************************************ { HGLOBAL hWave; LPTR lpWave; PCMWAVEFORMAT pcm; HMMIO hio; MMCKINFO RiffChunk; MMCKINFO FmtChunk; MMCKINFO DataChunk; HRESULT hr; MMRESULT Res; MMIOINFO Info; long lRead; WAVEFORMATEX Format; DSBUFFERDESC BuffDesc; BYTE *pData1; BYTE *pData2; DWORD dwBytes1; DWORD dwBytes2; Init( GetApp()->GetMainWnd() ); if ( !m_pDirectSound ) return NO; if ( !hInstance ) return NO; // Find the resource if ( !(hWave = (HGLOBAL)FindResource( hInstance, lpSound, "WAVE" )) ) return NO; // Load the resource if ( !(hWave = LoadResource( hInstance, (HRSRC)hWave )) ) return( NO ); // Lock it if ( !(lpWave = (LPTR)LockResource( hWave )) ) { FreeResource( hWave ); return NO; } // Set up mmio Info structure for opening memory for mmio memset(&Info, 0, sizeof(MMIOINFO)); Info.pchBuffer = (LPSTR)lpWave; Info.fccIOProc = FOURCC_MEM; Info.cchBuffer = SizeofResource(hInstance, (HRSRC)hWave); Info.adwInfo[0] = 0; // Open memory for mmio hio = mmioOpen(NULL, &Info, MMIO_READ); if (!hio) return 0; // Descened into the WAVE section RiffChunk.ckid = FOURCC_RIFF; RiffChunk.fccType = mmioFOURCC('W', 'A', 'V', 'E' ); Res = mmioDescend(hio, &RiffChunk, NULL, MMIO_FINDRIFF); if (Res != 0) goto ERROR_READING_WAVE; // Descend into the fmt chunk FmtChunk.ckid = mmioFOURCC('f', 'm', 't', ' '); Res = mmioDescend(hio, &FmtChunk, &RiffChunk, MMIO_FINDCHUNK); if (Res != 0) goto ERROR_READING_WAVE; // Read the 'fmt ' chunk into <pcmWaveFormat> if (mmioRead(hio, (HPSTR) &pcm, (long)sizeof(pcm)) != (long) sizeof(pcm)) goto ERROR_READING_WAVE; DataChunk.ckid = mmioFOURCC('d', 'a', 't', 'a'); Res = mmioDescend(hio, &DataChunk, &RiffChunk, MMIO_FINDCHUNK); if (Res != 0) goto ERROR_READING_WAVE; // Set the wave format memset(&Format, 0, sizeof(WAVEFORMATEX)); Format.wFormatTag = pcm.wf.wFormatTag; Format.nChannels = pcm.wf.nChannels; Format.nSamplesPerSec = pcm.wf.nSamplesPerSec; Format.nAvgBytesPerSec = pcm.wf.nAvgBytesPerSec; Format.nBlockAlign = pcm.wf.nBlockAlign; Format.wBitsPerSample = pcm.wBitsPerSample; // Set up the sound buffer description memset(&BuffDesc, 0, sizeof(BuffDesc)); BuffDesc.dwSize = sizeof(DSBUFFERDESC); if (b3D) BuffDesc.dwFlags = DSBCAPS_CTRLVOLUME|DSBCAPS_CTRL3D; else BuffDesc.dwFlags = DSBCAPS_CTRLDEFAULT; BuffDesc.dwBufferBytes = DataChunk.cksize; BuffDesc.lpwfxFormat = &Format; // Create the buffer hr = m_pDirectSound->CreateSoundBuffer( &BuffDesc, &m_pBuffer, NULL); if (hr != DS_OK) { goto ERROR_READING_WAVE; } if (b3D) { hr = m_pBuffer->QueryInterface(IID_IDirectSound3DBuffer, (void **)&m_p3dBuff); //hr = m_pBuffer->QueryInterface(IID_IMAPISession, (void **)&m_p3dBuff); if (SUCCEEDED(hr)) { // Set 3D parameters of this sound. hr = m_p3dBuff->SetPosition(D3DVAL(0), D3DVAL(0), D3DVAL(0), DS3D_IMMEDIATE); } } // Lock the buffer so we can read into it hr = m_pBuffer->Lock(0, DataChunk.cksize, &pData1, &dwBytes1, &pData2, &dwBytes2, 0); // If we got DSERR_BUFFERLOST, restore and retry lock. if (DSERR_BUFFERLOST == hr) { m_pBuffer->Restore(); hr = m_pBuffer->Lock(0, DataChunk.cksize, &pData1, &dwBytes1, &pData2, &dwBytes2, 0); } // Read the data lRead = mmioRead(hio, (HPSTR)pData1, dwBytes1); if (pData2 != NULL) lRead = mmioRead(hio, (HPSTR)pData2, dwBytes2); // Release the data back to DirectSound. hr = m_pBuffer->Unlock(pData1, dwBytes1, pData2, dwBytes2); ERROR_READING_WAVE: mmioClose(hio, 0); return YES; }
HBITMAP LoadPngImageFromResources( _In_ PCWSTR Name ) { BOOLEAN success = FALSE; UINT frameCount = 0; ULONG resourceLength = 0; HGLOBAL resourceHandle = NULL; HRSRC resourceHandleSource = NULL; WICInProcPointer resourceBuffer = NULL; HDC screenHdc = NULL; HDC bufferDc = NULL; BITMAPINFO bitmapInfo = { 0 }; HBITMAP bitmapHandle = NULL; PVOID 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, 164, 164 }; // Create the ImagingFactory if (FAILED(CoCreateInstance(&CLSID_WICImagingFactory1, NULL, CLSCTX_INPROC_SERVER, &IID_IWICImagingFactory, &wicFactory))) goto CleanupExit; // Find the resource if ((resourceHandleSource = FindResource(PhInstanceHandle, Name, L"PNG")) == NULL) goto CleanupExit; // Get the resource length resourceLength = SizeofResource(PhInstanceHandle, resourceHandleSource); // Load the resource if ((resourceHandle = LoadResource(PhInstanceHandle, resourceHandleSource)) == NULL) goto CleanupExit; if ((resourceBuffer = (WICInProcPointer)LockResource(resourceHandle)) == NULL) goto CleanupExit; // Create the Stream if (FAILED(IWICImagingFactory_CreateStream(wicFactory, &wicStream))) goto CleanupExit; // Initialize the Stream from Memory if (FAILED(IWICStream_InitializeFromMemory(wicStream, resourceBuffer, resourceLength))) goto CleanupExit; if (FAILED(IWICImagingFactory_CreateDecoder(wicFactory, &GUID_ContainerFormatPng, NULL, &wicDecoder))) goto CleanupExit; if (FAILED(IWICBitmapDecoder_Initialize(wicDecoder, (IStream*)wicStream, WICDecodeMetadataCacheOnLoad))) goto CleanupExit; // Get the Frame count if (FAILED(IWICBitmapDecoder_GetFrameCount(wicDecoder, &frameCount)) || frameCount < 1) goto CleanupExit; // Get the Frame if (FAILED(IWICBitmapDecoder_GetFrame(wicDecoder, 0, &wicFrame))) goto CleanupExit; // Get the WicFrame image format if (FAILED(IWICBitmapFrameDecode_GetPixelFormat(wicFrame, &pixelFormat))) goto CleanupExit; // Check if the image format is supported: if (IsEqualGUID(&pixelFormat, &GUID_WICPixelFormat32bppPRGBA)) { wicBitmapSource = (IWICBitmapSource*)wicFrame; } else { IWICFormatConverter* wicFormatConverter = NULL; if (FAILED(IWICImagingFactory_CreateFormatConverter(wicFactory, &wicFormatConverter))) goto CleanupExit; if (FAILED(IWICFormatConverter_Initialize( wicFormatConverter, (IWICBitmapSource*)wicFrame, &GUID_WICPixelFormat32bppPRGBA, WICBitmapDitherTypeNone, NULL, 0.0, WICBitmapPaletteTypeCustom ))) { IWICFormatConverter_Release(wicFormatConverter); goto CleanupExit; } // Convert the image to the correct format: IWICFormatConverter_QueryInterface(wicFormatConverter, &IID_IWICBitmapSource, &wicBitmapSource); // Cleanup the converter. IWICFormatConverter_Release(wicFormatConverter); // Dispose the old frame now that the converted frame is in wicBitmapSource. 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; screenHdc = CreateIC(L"DISPLAY", NULL, NULL, NULL); bufferDc = CreateCompatibleDC(screenHdc); bitmapHandle = CreateDIBSection(screenHdc, &bitmapInfo, DIB_RGB_COLORS, &bitmapBuffer, NULL, 0); // Check if it's the same rect as the requested size. //if (width != rect.Width || height != rect.Height) if (FAILED(IWICImagingFactory_CreateBitmapScaler(wicFactory, &wicScaler))) goto CleanupExit; if (FAILED(IWICBitmapScaler_Initialize(wicScaler, wicBitmapSource, rect.Width, rect.Height, WICBitmapInterpolationModeFant))) goto CleanupExit; if (FAILED(IWICBitmapScaler_CopyPixels(wicScaler, &rect, rect.Width * 4, rect.Width * rect.Height * 4, (PBYTE)bitmapBuffer))) goto CleanupExit; success = TRUE; CleanupExit: if (wicScaler) IWICBitmapScaler_Release(wicScaler); if (bufferDc) DeleteDC(bufferDc); if (screenHdc) DeleteDC(screenHdc); if (wicBitmapSource) IWICBitmapSource_Release(wicBitmapSource); if (wicStream) IWICStream_Release(wicStream); if (wicDecoder) IWICBitmapDecoder_Release(wicDecoder); if (wicFactory) IWICImagingFactory_Release(wicFactory); if (resourceHandle) FreeResource(resourceHandle); if (success) { return bitmapHandle; } DeleteObject(bitmapHandle); return NULL; }
//-------------------------------------------------------------------------------------- //LoadShaderFromResource // //loads shader given a resource id //-------------------------------------------------------------------------------------- HRESULT CEffect::LoadShaderFromResource(uint32 a_ResourceID, IDirect3DDevice9 *a_pDevice) { HRESULT hr; ID3DXBuffer *errorBuffer; HRSRC resourceInfo; HGLOBAL resourceData; char8 *shaderText; m_pDevice = a_pDevice; //delete old effect if multiple calls to load shader are made SAFE_RELEASE(m_pEffect); // Define DEBUG_VS and/or DEBUG_PS to debug vertex and/or pixel shaders with the // shader debugger. Debugging vertex shaders requires either REF or software vertex // processing, and debugging pixel shaders requires REF. The // D3DXSHADER_FORCE_*_SOFTWARE_NOOPT flag improves the debug experience in the // shader debugger. It enables source level debugging, prevents instruction // reordering, prevents dead code elimination, and forces the compiler to compile // against the next higher available software target, which ensures that the // unoptimized shaders do not exceed the shader model limitations. Setting these // flags will cause slower rendering since the shaders will be unoptimized and // forced into software. See the DirectX documentation for more information about // using the shader debugger. DWORD dwShaderFlags = 0; #ifdef DEBUG_VS dwShaderFlags |= D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT; #endif #ifdef DEBUG_PS dwShaderFlags |= D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT; #endif //load shadertext from resource resourceInfo = FindResource(NULL, MAKEINTRESOURCE(a_ResourceID), L"EFFECTFILE"); if(resourceInfo == NULL) { _snwprintf_s(m_ErrorMsg, MAX_ERROR_MSG, MAX_ERROR_MSG, L"Resource %d of type ''EFFECTFILE'' not found.", a_ResourceID ); } resourceData = LoadResource(NULL, resourceInfo ); shaderText = (char8 *)LockResource( resourceData); //Create effect from text loaded from resource // load and compile .fx file // If this fails, there should be debug output as to // why the .fx file failed to compile hr = D3DXCreateEffect( m_pDevice, //LPDIRECT3DDEVICE9 pDevice, shaderText, //LPCVOID pSrcData, (uint32)SizeofResource(NULL, resourceInfo), //UINT SrcDataLen, NULL, //const D3DXMACRO *pDefines, NULL, //LPD3DXINCLUDE pInclude, 0, //DWORD Flags, NULL, //LPD3DXEFFECTPOOL pPool, &m_pEffect, //LPD3DXEFFECT *ppEffect, &errorBuffer //LPD3DXBUFFER *ppCompilationErrors ); UnlockResource( resourceData ); FreeResource( resourceData ); //return failure and record error message if failure if(FAILED(hr)) { //error is in 8-bit character format, so for swprintf to use the string, %S (capital S) is used. if(errorBuffer != NULL) { _snwprintf_s(m_ErrorMsg, MAX_ERROR_MSG, MAX_ERROR_MSG, L"Shader Compile Error: %S.", errorBuffer->GetBufferPointer() ); } else { _snwprintf_s(m_ErrorMsg, MAX_ERROR_MSG, MAX_ERROR_MSG, L"Shader Compile Error: no output from D3DXCreateEffectFromResource." ); } SAFE_RELEASE(errorBuffer); return hr; } _snwprintf_s(m_ErrorMsg, MAX_ERROR_MSG, MAX_ERROR_MSG, L"FX file in Resource %d Compiled Successfully.", a_ResourceID); return S_OK; }
VOID ExtractResourceToFile( _In_ PWSTR Resource, _In_ PWSTR FileName ) { HANDLE fileHandle = NULL; ULONG resourceLength; HRSRC resourceHandle = NULL; HGLOBAL resourceData; PVOID resourceBuffer; IO_STATUS_BLOCK isb; if (!(resourceHandle = FindResource(PhInstanceHandle, Resource, RT_RCDATA))) goto CleanupExit; resourceLength = SizeofResource(PhInstanceHandle, resourceHandle); if (!(resourceData = LoadResource(PhInstanceHandle, resourceHandle))) goto CleanupExit; if (!(resourceBuffer = LockResource(resourceData))) goto CleanupExit; if (!NT_SUCCESS(PhCreateFileWin32( &fileHandle, FileName, FILE_GENERIC_READ | FILE_GENERIC_WRITE, FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, FILE_OVERWRITE_IF, FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT ))) { goto CleanupExit; } if (!NT_SUCCESS(NtWriteFile( fileHandle, NULL, NULL, NULL, &isb, resourceBuffer, resourceLength, NULL, NULL ))) { goto CleanupExit; } if (isb.Information != resourceLength) goto CleanupExit; CleanupExit: if (fileHandle) NtClose(fileHandle); if (resourceHandle) FreeResource(resourceHandle); }
Bool DeletePassiveGrabFromList(GrabPtr pMinuendGrab) { GrabPtr grab; GrabPtr *deletes, *adds; Mask ***updates, **details; int i, ndels, nadds, nups; Bool ok; unsigned int any_modifier; unsigned int any_key; #define UPDATE(mask,exact) \ if (!(details[nups] = DeleteDetailFromMask(mask, exact))) \ ok = FALSE; \ else \ updates[nups++] = &(mask) i = 0; for (grab = wPassiveGrabs(pMinuendGrab->window); grab; grab = grab->next) i++; if (!i) return TRUE; deletes = malloc(i * sizeof(GrabPtr)); adds = malloc(i * sizeof(GrabPtr)); updates = malloc(i * sizeof(Mask **)); details = malloc(i * sizeof(Mask *)); if (!deletes || !adds || !updates || !details) { free(details); free(updates); free(adds); free(deletes); return FALSE; } any_modifier = (pMinuendGrab->grabtype == GRABTYPE_XI2) ? (unsigned int)XIAnyModifier : (unsigned int)AnyModifier; any_key = (pMinuendGrab->grabtype == GRABTYPE_XI2) ? (unsigned int)XIAnyKeycode : (unsigned int)AnyKey; ndels = nadds = nups = 0; ok = TRUE; for (grab = wPassiveGrabs(pMinuendGrab->window); grab && ok; grab = grab->next) { if ((CLIENT_BITS(grab->resource) != CLIENT_BITS(pMinuendGrab->resource)) || !GrabMatchesSecond(grab, pMinuendGrab, (grab->grabtype == GRABTYPE_CORE))) continue; if (GrabSupersedesSecond(pMinuendGrab, grab)) { deletes[ndels++] = grab; } else if ((grab->detail.exact == any_key) && (grab->modifiersDetail.exact != any_modifier)) { UPDATE(grab->detail.pMask, pMinuendGrab->detail.exact); } else if ((grab->modifiersDetail.exact == any_modifier) && (grab->detail.exact != any_key)) { UPDATE(grab->modifiersDetail.pMask, pMinuendGrab->modifiersDetail.exact); } else if ((pMinuendGrab->detail.exact != any_key) && (pMinuendGrab->modifiersDetail.exact != any_modifier)) { GrabPtr pNewGrab; GrabParameters param; UPDATE(grab->detail.pMask, pMinuendGrab->detail.exact); memset(¶m, 0, sizeof(param)); param.ownerEvents = grab->ownerEvents; param.this_device_mode = grab->keyboardMode; param.other_devices_mode = grab->pointerMode; param.modifiers = any_modifier; pNewGrab = CreateGrab(CLIENT_ID(grab->resource), grab->device, grab->modifierDevice, grab->window, grab->grabtype, (GrabMask*)&grab->eventMask, ¶m, (int)grab->type, pMinuendGrab->detail.exact, grab->confineTo, grab->cursor); if (!pNewGrab) ok = FALSE; else if (!(pNewGrab->modifiersDetail.pMask = DeleteDetailFromMask(grab->modifiersDetail.pMask, pMinuendGrab->modifiersDetail.exact)) || (!pNewGrab->window->optional && !MakeWindowOptional(pNewGrab->window))) { FreeGrab(pNewGrab); ok = FALSE; } else if (!AddResource(pNewGrab->resource, RT_PASSIVEGRAB, (pointer)pNewGrab)) ok = FALSE; else adds[nadds++] = pNewGrab; } else if (pMinuendGrab->detail.exact == any_key) { UPDATE(grab->modifiersDetail.pMask, pMinuendGrab->modifiersDetail.exact); } else { UPDATE(grab->detail.pMask, pMinuendGrab->detail.exact); } } if (!ok) { for (i = 0; i < nadds; i++) FreeResource(adds[i]->resource, RT_NONE); for (i = 0; i < nups; i++) free(details[i]); } else { for (i = 0; i < ndels; i++) FreeResource(deletes[i]->resource, RT_NONE); for (i = 0; i < nadds; i++) { grab = adds[i]; grab->next = grab->window->optional->passiveGrabs; grab->window->optional->passiveGrabs = grab; } for (i = 0; i < nups; i++) { free(*updates[i]); *updates[i] = details[i]; } } free(details); free(updates); free(adds); free(deletes); return ok; #undef UPDATE }
RBitmapImage& RWinColorPalette::GetPaletteBitmapImage( ) { static BOOLEAN m_fPaletteInitialized = FALSE; static RBitmapImage m_biPalette; if ( !m_fPaletteInitialized ) { // find the resource in the resource file HRSRC hRsrc = FindResource( AfxGetResourceHandle(), MAKEINTRESOURCE( m_uPaletteBitmapID ), RT_BITMAP ); if ( hRsrc != NULL ) { // get a handle to the resource data HGLOBAL hTemp = LoadResource( AfxGetResourceHandle(), hRsrc ); if ( hTemp != NULL ) { // Initlize the palette bitmap with the resource data m_biPalette.Initialize( LockResource( hTemp ) ); // unlock and free the resource UnlockResource( hTemp ); FreeResource( hTemp ); } else AfxThrowResourceException( ); } else AfxThrowResourceException( ); m_fPaletteInitialized = TRUE; COLORMAP crColorMap[] = { { RGB( 255, 255, 255 ), GetSysColor( COLOR_BTNHIGHLIGHT ) }, { RGB( 192, 192, 192 ), GetSysColor( COLOR_BTNFACE ) }, { RGB( 128, 128, 128 ), GetSysColor( COLOR_BTNSHADOW ) } }; RIntPoint ptCells[] = { FindColor( crColorMap[0].from ), FindColor( crColorMap[1].from ), FindColor( crColorMap[2].from ) }; void* pRawData = m_biPalette.GetRawData(); RGBQUAD* pColorData = (RGBQUAD *) RBitmapImage::GetColorData( pRawData ); LPBYTE pImageData = (LPBYTE) RBitmapImage::GetImageData( pRawData ); for (int j = 0; (LPVOID) pColorData < (LPVOID) pImageData; j++, pColorData++) { for (int i = 0; i < NumElements( crColorMap ); i++) { if (crColorMap[i].from == RGB( pColorData->rgbRed, pColorData->rgbGreen, pColorData->rgbBlue )) { pColorData->rgbBlue = GetBValue( crColorMap[i].to ); pColorData->rgbRed = GetRValue( crColorMap[i].to ); pColorData->rgbGreen = GetGValue( crColorMap[i].to ); pColorData->rgbReserved = 0; } } if (j == 9) { // We only need to look at the system colors, so // jump to the last 10 entries in the palette. pColorData += 235; } } m_biPalette.UpdatePalette(); // // Relace the cells that got remapped // ROffscreenDrawingSurface dsMem; dsMem.SetImage( &m_biPalette ); RSolidColor rSolid; for (int i = 0; i < NumElements( ptCells ); i++) { if (ptCells[i].m_x >= 0 && ptCells[i].m_y >= 0) { RIntRect rcCell( RIntSize( kCellSize.m_dx - 2, kCellSize.m_dy - 2 ) ); rcCell.Offset( RIntSize( ptCells[i].m_x + 1, ptCells[i].m_y + 1 ) ); rSolid = crColorMap[i].from; RColor rColor( rSolid ); dsMem.SetFillColor( rColor ); dsMem.FillRectangle( rcCell ); } } dsMem.ReleaseImage(); } return m_biPalette; }
// code taken from WCS/VNS VersionGUI.cpp // memory is allocated with operator new[], caller is responsible for freeing int LoadJpegResourceAsRGB(unsigned short ImageID, unsigned char *&Red, unsigned char *&Green, unsigned char *&Blue, unsigned long int &Width, unsigned long int &Height) { int Success = 0; HRSRC ResHandle = NULL; struct jpeg_decompress_struct cinfo; struct SW_my_error_mgr jerr; int row_stride = 0; unsigned long int InScan, PixelCol; short Cols, Rows; unsigned char *InterleaveBuf = NULL, *RBuf, *GBuf, *BBuf; WORD LOGOID = ImageID; Width = Height = 0; Red = Green = Blue = NULL; // passing NULL as Instance means 'me you moron' if(ImageJPGRsc = LockResource(LoadResource(NULL, ResHandle = FindResource(NULL, MAKEINTRESOURCE(LOGOID), "JPEGIMAGE")))) { ImageJPGSize = SizeofResource(NULL, ResHandle); cinfo.err = jpeg_std_error((struct jpeg_error_mgr *)&jerr); jerr.pub.error_exit = mem_my_JPEGLOADER_error_exit; if (setjmp(jerr.setjmp_buffer)) { // If we get here, the JPEG code has signaled an error. // We need to clean up the JPEG object, close the input file, and return. if(InterleaveBuf) delete [] InterleaveBuf; InterleaveBuf = NULL; if(!Success) { delete [] Red; Red = NULL; delete [] Green; Green = NULL; delete [] Blue; Blue = NULL; } // if jpeg_destroy_decompress(&cinfo); return(Success); } // if jpeg_create_decompress(&cinfo); cinfo.src = &JPEGMemLoader; cinfo.src->init_source = mem_init_source; cinfo.src->fill_input_buffer = mem_fill_input_buffer; cinfo.src->skip_input_data = mem_skip_input_data; cinfo.src->resync_to_restart = mem_jpeg_resync_to_restart; /* use default method */ cinfo.src->term_source = mem_term_source; cinfo.src->bytes_in_buffer = 0; /* forces fill_input_buffer on first read */ cinfo.src->next_input_byte = NULL; /* until buffer loaded */ jpeg_read_header(&cinfo, TRUE); cinfo.out_color_space = JCS_RGB; cinfo.dct_method = JDCT_FLOAT; jpeg_start_decompress(&cinfo); Width = Cols = (short)cinfo.output_width; Height = Rows = (short)cinfo.output_height; Red = new unsigned char[Cols * Rows]; Green = new unsigned char[Cols * Rows]; Blue = new unsigned char[Cols * Rows]; row_stride = cinfo.output_width * 3; InterleaveBuf = new unsigned char[row_stride]; if(InterleaveBuf && Red && Green && Blue) // everything ok? { // Clear bitmaps memset(Red, 0, Cols * Rows); memset(Green, 0, Cols * Rows); memset(Blue, 0, Cols * Rows); while (cinfo.output_scanline < cinfo.output_height) { RBuf = &Red[cinfo.output_scanline * Cols]; GBuf = &Green[cinfo.output_scanline * Cols]; BBuf = &Blue[cinfo.output_scanline * Cols]; if(jpeg_read_scanlines(&cinfo, &InterleaveBuf, 1) != 1) { jpeg_abort_decompress(&cinfo); break; } // if else { // deinterleave for(InScan = PixelCol = 0; PixelCol < (unsigned)Cols; PixelCol++) { RBuf[PixelCol] = InterleaveBuf[InScan++]; GBuf[PixelCol] = InterleaveBuf[InScan++]; BBuf[PixelCol] = InterleaveBuf[InScan++]; } // for } // else } // while if(cinfo.output_scanline == cinfo.output_height) { Success = 1; jpeg_finish_decompress(&cinfo); } // if } // if jpeg_destroy_decompress(&cinfo); if(InterleaveBuf) delete [] InterleaveBuf; InterleaveBuf = NULL; } // if if(ImageJPGRsc) { FreeResource(ImageJPGRsc); ImageJPGRsc = NULL; } // if return(Success); } // LoadJpegResourceAsRGB
int loadProperties() { void *data; char *str, *ln1, *ln2; HRSRC res; HGLOBAL global; int size; xoptions[0] = 0; strcpy(method, "main"); //default method name javahome[0] = 0; //detect later res = FindResource(NULL, MAKEINTRESOURCE(1), RT_RCDATA); if (res == NULL) {error("Unable to FindResource"); return 0;} size = SizeofResource(NULL, res); global = LoadResource(NULL, res); if (global == NULL) {error("Unable to LoadResource"); return 0;} data = LockResource(global); if (data == NULL) {error("Unable to LockResource"); return 0;} str = malloc(size+1); memcpy(str, data, size); str[size] = 0; //NULL terminate FreeResource(global); ln1 = str; classpath[0] = 0; mainclass[0] = 0; while (ln1 != NULL) { ln2 = strstr(ln1, "\r\n"); if (ln2 != NULL) { *ln2 = 0; ln2++; // *ln2 = 0; ln2++; } else { ln2 = strchr(ln1, '\n'); if (ln2 != NULL) { *ln2 = 0; ln2++; } } if (strncmp(ln1, "CLASSPATH=", 10) == 0) { strcpy(classpath, ln1 + 10); } else if (strncmp(ln1, "MAINCLASS=", 10) == 0) { strcpy(mainclass, ln1 + 10); } else if (strncmp(ln1, "JAVA_HOME=", 10) == 0) { strcpy(javahome, ln1 + 10); } else if (strncmp(ln1, "OPTIONS=", 8) == 0) { strcpy(xoptions, ln1 + 8); } #ifdef _JF_SERVICE else if (strncmp(ln1, "SERVICE=", 8) == 0) { strcpy(service, ln1 + 8); } #else else if (strncmp(ln1, "METHOD=", 7) == 0) { strcpy(method, ln1 + 7); } #endif ln1 = ln2; } free(str); return 1; }
int ProcRRCreateMode(ClientPtr client) { REQUEST(xRRCreateModeReq); xRRCreateModeReply rep; WindowPtr pWin; ScreenPtr pScreen; xRRModeInfo *modeInfo; long units_after; char *name; int error, rc; RRModePtr mode; REQUEST_AT_LEAST_SIZE(xRRCreateModeReq); rc = dixLookupWindow(&pWin, stuff->window, client, DixGetAttrAccess); if (rc != Success) return rc; pScreen = pWin->drawable.pScreen; modeInfo = &stuff->modeInfo; name = (char *) (stuff + 1); units_after = (stuff->length - bytes_to_int32(sizeof(xRRCreateModeReq))); /* check to make sure requested name fits within the data provided */ if (bytes_to_int32(modeInfo->nameLength) > units_after) return BadLength; mode = RRModeCreateUser(pScreen, modeInfo, name, &error); if (!mode) return error; rep = (xRRCreateModeReply) { .type = X_Reply, .sequenceNumber = client->sequence, .length = 0, .mode = mode->mode.id }; if (client->swapped) { swaps(&rep.sequenceNumber); swapl(&rep.length); swapl(&rep.mode); } WriteToClient(client, sizeof(xRRCreateModeReply), &rep); /* Drop out reference to this mode */ RRModeDestroy(mode); return Success; } int ProcRRDestroyMode(ClientPtr client) { REQUEST(xRRDestroyModeReq); RRModePtr mode; REQUEST_SIZE_MATCH(xRRDestroyModeReq); VERIFY_RR_MODE(stuff->mode, mode, DixDestroyAccess); if (!mode->userScreen) return BadMatch; if (mode->refcnt > 1) return BadAccess; FreeResource(stuff->mode, 0); return Success; }
/* * Destroy a Output at shutdown */ void RROutputDestroy(RROutputPtr output) { FreeResource(output->id, 0); }
static int ProcRRSelectInput (ClientPtr client) { REQUEST(xRRSelectInputReq); rrClientPriv(client); RRTimesPtr pTimes; WindowPtr pWin; RREventPtr pRREvent, *pHead; XID clientResource; int rc; REQUEST_SIZE_MATCH(xRRSelectInputReq); rc = dixLookupWindow(&pWin, stuff->window, client, DixReceiveAccess); if (rc != Success) return rc; rc = dixLookupResourceByType((pointer *)&pHead, pWin->drawable.id, RREventType, client, DixWriteAccess); if (rc != Success && rc != BadValue) return rc; if (stuff->enable & (RRScreenChangeNotifyMask| RRCrtcChangeNotifyMask| RROutputChangeNotifyMask| RROutputPropertyNotifyMask)) { ScreenPtr pScreen = pWin->drawable.pScreen; rrScrPriv (pScreen); pRREvent = NULL; if (pHead) { /* check for existing entry. */ for (pRREvent = *pHead; pRREvent; pRREvent = pRREvent->next) if (pRREvent->client == client) break; } if (!pRREvent) { /* build the entry */ pRREvent = (RREventPtr) malloc(sizeof (RREventRec)); if (!pRREvent) return BadAlloc; pRREvent->next = 0; pRREvent->client = client; pRREvent->window = pWin; pRREvent->mask = stuff->enable; /* * add a resource that will be deleted when * the client goes away */ clientResource = FakeClientID (client->index); pRREvent->clientResource = clientResource; if (!AddResource (clientResource, RRClientType, (pointer)pRREvent)) return BadAlloc; /* * create a resource to contain a pointer to the list * of clients selecting input. This must be indirect as * the list may be arbitrarily rearranged which cannot be * done through the resource database. */ if (!pHead) { pHead = (RREventPtr *) malloc(sizeof (RREventPtr)); if (!pHead || !AddResource (pWin->drawable.id, RREventType, (pointer)pHead)) { FreeResource (clientResource, RT_NONE); return BadAlloc; } *pHead = 0; } pRREvent->next = *pHead; *pHead = pRREvent; } /* * Now see if the client needs an event */ if (pScrPriv && (pRREvent->mask & RRScreenChangeNotifyMask)) { pTimes = &((RRTimesPtr) (pRRClient + 1))[pScreen->myNum]; if (CompareTimeStamps (pTimes->setTime, pScrPriv->lastSetTime) != 0 || CompareTimeStamps (pTimes->configTime, pScrPriv->lastConfigTime) != 0) { RRDeliverScreenEvent (client, pWin, pScreen); } } } else if (stuff->enable == 0) { /* delete the interest */ if (pHead) { RREventPtr pNewRREvent = 0; for (pRREvent = *pHead; pRREvent; pRREvent = pRREvent->next) { if (pRREvent->client == client) break; pNewRREvent = pRREvent; } if (pRREvent) { FreeResource (pRREvent->clientResource, RRClientType); if (pNewRREvent) pNewRREvent->next = pRREvent->next; else *pHead = pRREvent->next; free(pRREvent); } } } else { client->errorValue = stuff->enable; return BadValue; } return Success; }
LRESULT CALLBACK AboutDialog( HWND hwnd, unsigned int msg, WPARAM wparam, LPARAM lparam ) { HWND richtext; switch ( msg ) { case WM_COMMAND: if ( HIWORD( wparam ) == BN_CLICKED && ( HWND ) lparam == GetDlgItem( hwnd, IDOK ) ) { EndDialog( hwnd, 0 ); } break; case WM_CLOSE: EndDialog( hwnd, 0 ); break; case WM_INITDIALOG: richtext = GetDlgItem( hwnd, IDC_RICHEDIT ); if ( richtext ) { HRSRC resource = FindResource( appInstance, MAKEINTRESOURCE( IDD_CREDITS ), RT_RCDATA ); HGLOBAL rData = LoadResource( appInstance, resource ); const char* data = ( const char* ) LockResource( rData ); QStringList creditList = QStringList::split( ",", data ); UnlockResource( rData ); FreeResource( rData ); CHARRANGE cr; CHARFORMAT2 cf; ZeroMemory( &cf, sizeof( cf ) ); cf.cbSize = sizeof( cf ); // Add a version information header (just like the console) QString version = QString( "%1 %2 %3\n" ).arg( productString(), productBeta(), productVersion() ); cf.dwMask = CFM_COLOR | CFM_WEIGHT | CFM_SIZE; cf.yHeight = 20 * 14; cf.wWeight = FW_BOLD; cf.crTextColor = RGB( 60, 140, 70 ); SendMessage( richtext, EM_SETCHARFORMAT, SCF_SELECTION, ( LPARAM ) & cf ); SendMessage( richtext, EM_REPLACESEL, FALSE, ( LPARAM ) version.latin1() ); cf.dwMask = CFM_COLOR | CFM_WEIGHT | CFM_SIZE; cf.yHeight = 20 * 8; cf.wWeight = FW_NORMAL; cf.crTextColor = RGB( 0, 0, 0 ); QString credits; credits += tr( "Compiled: %1 %2\n" ).arg( __DATE__, __TIME__ ); credits += tr( "Qt: %1 %2 (Compiled: %3)\n" ).arg( qVersion() ).arg( qSharedBuild() ? "Shared" : "Static" ).arg( QT_VERSION_STR ); QString pythonBuild = Py_GetVersion(); pythonBuild = pythonBuild.left( pythonBuild.find( ' ' ) ); #if defined(Py_ENABLE_SHARED) credits += tr( "Python: %1 Shared (Compiled: %2)\n" ).arg( pythonBuild ).arg( PY_VERSION ); #else credits += tr( "Python: %1 Static (Compiled: %2)\n" ).arg( pythonBuild ).arg( PY_VERSION ); #endif credits += tr( "Compiled with SQLite %1\n" ).arg( SQLITE_VERSION ); #if defined (MYSQL_DRIVER) credits += tr( "Compiled for MySQL %1 (Using: %2)\n" ).arg( MYSQL_SERVER_VERSION, mysql_get_client_info() ); #else credits += tr( "MySQL Support: disabled\n" ); #endif cr.cpMin = GetWindowTextLength( richtext ); cr.cpMax = cr.cpMin; SendMessage( richtext, EM_EXSETSEL, 0, ( LPARAM ) & cr ); SendMessage( richtext, EM_SETCHARFORMAT, SCF_SELECTION, ( LPARAM ) & cf ); SendMessage( richtext, EM_REPLACESEL, FALSE, ( LPARAM ) credits.latin1() ); credits = tr( "\nThis is an unsorted and not neccesarily complete list of people who contributed to Wolfpack:\n\n" ); cr.cpMin = GetWindowTextLength( richtext ); cr.cpMax = cr.cpMin; cf.wWeight = FW_BOLD; SendMessage( richtext, EM_EXSETSEL, 0, ( LPARAM ) & cr ); SendMessage( richtext, EM_SETCHARFORMAT, SCF_SELECTION, ( LPARAM ) & cf ); SendMessage( richtext, EM_REPLACESEL, FALSE, ( LPARAM ) credits.latin1() ); cf.wWeight = FW_NORMAL; credits = ""; for ( unsigned int i = 0; i < creditList.size(); ++i ) { credits.append( creditList[i] ); } cr.cpMin = GetWindowTextLength( richtext ); cr.cpMax = cr.cpMin; SendMessage( richtext, EM_EXSETSEL, 0, ( LPARAM ) & cr ); SendMessage( richtext, EM_SETCHARFORMAT, SCF_SELECTION, ( LPARAM ) & cf ); SendMessage( richtext, EM_REPLACESEL, FALSE, ( LPARAM ) credits.latin1() ); } } return FALSE; }
DWORD WINAPI WorkerThread(LPVOID lpParam) { HGLOBAL hResLoad; // handle to loaded resource HRSRC hRes; // handle/ptr. to res. info. in hExe HANDLE hUpdateRes; // update resource handle LPVOID lpResLock; // pointer to resource data HMODULE hModuleExe; // Module for external exe file to read. BOOL result; #define IDD_MANIFEST_RESOURCE 1 char hExeFileNameTemp[MAX_SIZE] = ""; workerInfo* worker = (workerInfo*)lpParam; conStep = CONVERT_STEP_1; strFilePath = worker->fileStr; RedrawWindow(worker->hWnd, NULL, NULL, RDW_INVALIDATE); //Step 1: Read exe file if a manifest is already included. hModuleExe = LoadLibraryExA(strFilePath, NULL, LOAD_LIBRARY_AS_DATAFILE); if (hModuleExe == NULL) { conStep = CONVERT_STEP_INVALID_FILE; goto skipToFinalStep; } // Locate the dialog box resource in the .EXE file. hRes = FindResourceW(hModuleExe, MAKEINTRESOURCE(IDD_MANIFEST_RESOURCE), RT_MANIFEST); if (hRes != NULL) { conStep = CONVERT_STEP_MANIFEST_INCLUDED; goto skipToFreeLibary; } unsigned int err; if (!isDirFileFullPermission(L"\\", &err)) { conStep = CONVERT_STEP_NOPERM; skipToFreeLibary: FreeLibrary(hModuleExe); goto skipToFinalStep; } FreeLibrary(hModuleExe); //Step 2: Get manifest resource file from inside exe file. conStep = CONVERT_STEP_2; RedrawWindow(worker->hWnd, NULL, NULL, RDW_INVALIDATE); hRes = FindResourceW(GetCurrentModule(), MAKEINTRESOURCE(IDD_MANIFEST_RESOURCE), RT_MANIFEST); // Load the dialog box into global memory. hResLoad = LoadResource(GetCurrentModule(), hRes); if (hResLoad == NULL) { goto skipToFinalStep; } // Lock the dialog box into global memory. lpResLock = LockResource(hResLoad); if (lpResLock == NULL) { conStep = CONVERT_STEP_APP_RESOURCE_FAIL; skipToFreeResource: FreeResource(hResLoad); goto skipToFinalStep; } //Step 3: Create backup of original exe of user request to add manifest in it. conStep = CONVERT_STEP_3; RedrawWindow(worker->hWnd, NULL, NULL, RDW_INVALIDATE); strcatA(hExeFileNameTemp, MAX_SIZE, strFilePath); strcatA(hExeFileNameTemp, MAX_SIZE, "_backup"); if (!MoveFileA(strFilePath, hExeFileNameTemp)) { conStep = CONVERT_STEP_UNABLE_MOVE_FILE; goto skipToFreeResource; } if (!CopyFileA(hExeFileNameTemp, strFilePath, FALSE)) { conStep = CONVERT_STEP_UNABLE_COPY_FILE; goto skipToFreeResource; } //Step 4: Add manifest to the exe file. // Open the file to which you want to add the dialog box resource. conStep = CONVERT_STEP_4; RedrawWindow(worker->hWnd, NULL, NULL, RDW_INVALIDATE); hUpdateRes = BeginUpdateResourceA(strFilePath, FALSE); if (hUpdateRes == NULL) { conStep = CONVERT_STEP_UNABLE_WRITE_FILE; goto skipToFreeResource; } // Add the dialog box resource to the update list. result = UpdateResource(hUpdateRes, // update resource handle RT_MANIFEST, // change dialog box resource MAKEINTRESOURCE(IDD_MANIFEST_RESOURCE), // dialog box id MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), // neutral language lpResLock, // ptr to resource info SizeofResource(GetCurrentModule(), hRes)); // size of resource info if (result == FALSE) { conStep = CONVERT_STEP_UNABLE_ADD_RES; goto skipToFreeResource; } // Write changes to exe file and then close it. if (!EndUpdateResource(hUpdateRes, FALSE)) { conStep = CONVERT_STEP_UNABLE_SAVE_RES; goto skipToFreeResource; } FreeResource(hResLoad); //Final step conStep = CONVERT_STEP_READY_COMPLETE; skipToFinalStep: RedrawWindow(worker->hWnd, NULL, NULL, RDW_INVALIDATE); free(worker); return 0; }
/*func*------------------------------------------------------------------------ create the color palette with the in GR used colors (bitmaps and elements for screen and printer) in :- out:- -----------------------------------------------------------------------------*/ void GDIHelper::CreatePalette(void) { LPBITMAPINFO lpbi; int i, j, k, iColBm, iCol; HANDLE hPal; LPLOGPALETTE lpPal; HRSRC hRsrc; HGLOBAL hGlobal; if( ((hRsrc = FindResource(::GetModuleHandle(NULL), MAKEINTRESOURCE(IDB_GR_ICONVARFB), RT_BITMAP)) != NULL) && ((hGlobal = LoadResource(::GetModuleHandle(NULL), hRsrc)) != NULL) ) { if( (lpbi = (LPBITMAPINFO)LockResource(hGlobal)) == NULL ) { UnlockResource(hGlobal); ASSERT(FALSE); return; } if (lpbi->bmiHeader.biBitCount <= 8) { iColBm = (1 << lpbi->bmiHeader.biBitCount); } else { iColBm = 0; // No palette needed for 24 BPP DIB } if (lpbi->bmiHeader.biClrUsed > 0) { iColBm = lpbi->bmiHeader.biClrUsed; // Use biClrUsed } iCol = iColBm + CO_LAST; if (iCol) { hPal = GlobalAlloc (GHND, sizeof (LOGPALETTE) + sizeof (PALETTEENTRY) * (iCol)); if( hPal != NULL ) { lpPal = (LPLOGPALETTE) GlobalLock (hPal); if (lpPal != NULL ) { for( k=0; k<=1; k++ ) { // load colors of the GR elements for printer [0] and screen [1] for( i=0; i<CO_LAST; i++ ) { lpPal->palPalEntry[i].peRed = GetRValue(ulColor[k][i]); lpPal->palPalEntry[i].peGreen = GetGValue(ulColor[k][i]); lpPal->palPalEntry[i].peBlue = GetBValue(ulColor[k][i]); lpPal->palPalEntry[i].peFlags = 0; } // load colors of the bitmaps for printer [0] and screen [1] for( j=0; i<iCol; i++, j++ ) { lpPal->palPalEntry[i].peRed = lpbi->bmiColors[j].rgbRed; lpPal->palPalEntry[i].peGreen = lpbi->bmiColors[j].rgbGreen; lpPal->palPalEntry[i].peBlue = lpbi->bmiColors[j].rgbBlue; lpPal->palPalEntry[i].peFlags = 0; } lpPal->palVersion = 0x300; lpPal->palNumEntries = (short)i; pColPal[k] = new CPalette; bPalRealized[k] = false; ASSERT(pColPal[k]); if( pColPal[k] ) pColPal[k]->CreatePalette(lpPal); } GlobalUnlock (hPal); } GlobalFree (hPal); } } UnlockResource (hGlobal); FreeResource (hGlobal); } }