Ejemplo n.º 1
0
static HBITMAP WRReadBitmap( BYTE *data, long offset, BOOL core, bitmap_info *info )
{
    DWORD               size;           /* generic size - used repeatedly */
    BYTE _HUGE          *mask_ptr;      /* pointer to bit array in memory */
    HDC                 hdc;
    HPALETTE            new_palette, old_palette;
    BITMAPINFO          *bm_info = NULL;
    BITMAPCOREINFO      *bm_core = NULL;
    HBITMAP             bitmap_handle;
    int                 pos;

    bitmap_handle = (HBITMAP)NULL;

    if( core ) {
        bm_core = WRReadCoreInfo( &data );
        if( bm_core == NULL ) {
            return( bitmap_handle );
        }
        size = BITS_TO_BYTES( bm_core->bmciHeader.bcWidth * bm_core->bmciHeader.bcBitCount,
                              bm_core->bmciHeader.bcHeight );
    } else {
        bm_info = WRReadDIBInfo( &data );
        if( bm_info == NULL ) {
            return( bitmap_handle );
        }
        size = BITS_TO_BYTES( bm_info->bmiHeader.biWidth * bm_info->bmiHeader.biBitCount,
                              bm_info->bmiHeader.biHeight );
    }

    pos = offset;
    mask_ptr = __halloc( size, 1 );
    if( mask_ptr != NULL ) {
        WRReadInPieces( mask_ptr, data, size );
        if( core ) {
            BITMAPCOREHEADER    *h;

            h = &bm_core->bmciHeader;
            /*
             * This will cause a GP Fault!
             */
            bitmap_handle = CreateBitmap( h->bcWidth, h->bcHeight, h->bcPlanes,
                                          h->bcBitCount, mask_ptr );
        } else {
            if( bm_info->bmiHeader.biBitCount < 9 ) {
                /* Bitmap has palette, create it */            
                new_palette = CreateDIBPalette( bm_info );
                if( new_palette != NULL ) {
                    hdc = GetDC( (HWND)NULL );
                    old_palette = SelectPalette( hdc, new_palette, FALSE );
                    RealizePalette( hdc );
                    bitmap_handle = CreateDIBitmap( hdc, &bm_info->bmiHeader, CBM_INIT,
                                                    mask_ptr, bm_info, DIB_RGB_COLORS );
                    SelectPalette( hdc, old_palette, FALSE );
                    DeleteObject( new_palette );
                    ReleaseDC( (HWND)NULL, hdc );
                }
            } else {
                /* Bitmap with no palette*/
                hdc = GetDC( (HWND)NULL );
                bitmap_handle = CreateDIBitmap( hdc, &bm_info->bmiHeader, CBM_INIT,
                                                mask_ptr, bm_info, DIB_RGB_COLORS );
                ReleaseDC( (HWND)NULL, hdc );
            }
        }
        __hfree( mask_ptr );
    }
    if( core ) {
        if( info != NULL ) {
            info->u.bm_core = bm_core;
        } else {
            MemFree( bm_core );
        }
    } else {
        if( info != NULL ) {
            info->u.bm_info = bm_info;
        } else {
            MemFree( bm_info );
        }
    }
    return( bitmap_handle );
}
BOOL CClientCapture::DrawBitmap(CDC *dc, HDC hDC, CRect *rect, CRect *dest, CBitmap &bitmap){

	//////////////////////////////////////////////////////
	// Create logical palette if device support a palette
	if( dc->GetDeviceCaps(RASTERCAPS) & RC_PALETTE )
	{
		UINT nSize = sizeof(LOGPALETTE) + (sizeof(PALETTEENTRY) * 256);
		LOGPALETTE *pLP = (LOGPALETTE *) new BYTE[nSize];
		pLP->palVersion = 0x300;

		pLP->palNumEntries = GetSystemPaletteEntries( *dc, 0, 255, pLP->palPalEntry );

		// Create the palette
		pal.CreatePalette( pLP );

		delete[] pLP;
	}
	// END CREATE PALETTE
	//////////////////////////////////////////////////////

	/////////////////////////////
	/////////////////////////////
	BITMAP			bm;
	BITMAPINFOHEADER	bi;
	DWORD			dwLen;
	HANDLE			handle;
	HDC 			hPDC;
	HPALETTE		hPal;

	ASSERT( bitmap.GetSafeHandle() );

	// If a palette has not been supplied use defaul palette
	hPal = (HPALETTE) pal.GetSafeHandle();
	if (hPal==NULL)
		hPal = (HPALETTE) GetStockObject(DEFAULT_PALETTE);

	// Get bitmap information
	bitmap.GetObject(sizeof(bm),(LPSTR)&bm);

	// Initialize the bitmapinfoheader
	bi.biSize		= sizeof(BITMAPINFOHEADER);
	bi.biWidth		= bm.bmWidth;
	bi.biHeight 		= bm.bmHeight;
	bi.biPlanes 		= 1;
	bi.biBitCount		= bm.bmPlanes * bm.bmBitsPixel;
	bi.biCompression	= BI_RGB;
	bi.biSizeImage		= 0;
	bi.biXPelsPerMeter	= 0;
	bi.biYPelsPerMeter	= 0;
	bi.biClrUsed		= 0;
	bi.biClrImportant	= 0;

	// Compute the size of the  infoheader and the color table
	int nColors = (1 << bi.biBitCount);
	if( nColors > 256 ) 
		nColors = 0;
	dwLen  = bi.biSize + nColors * sizeof(RGBQUAD);

	// We need a device context to get the DIB from
	hPDC = dc->GetSafeHdc();

	//hDC = GetDC(NULL);
	hPal = SelectPalette(hPDC,hPal,FALSE);
	RealizePalette(hPDC);

	
	// Allocate enough memory to hold bitmapinfoheader and color table
	if(hDIB) GlobalFree( hDIB );

	hDIB = GlobalAlloc(GMEM_FIXED,dwLen);

	if (!hDIB){
		SelectPalette(hPDC,hPal,FALSE);
		return NULL;
	}

	lpbi = (LPBITMAPINFOHEADER)hDIB;

	*lpbi = bi;

	// Call GetDIBits with a NULL lpBits param, so the device driver 
	// will calculate the biSizeImage field 
	GetDIBits(hPDC, (HBITMAP)bitmap.GetSafeHandle(), 0L, (DWORD)bi.biHeight,
			(LPBYTE)NULL, (LPBITMAPINFO)lpbi, (DWORD)DIB_RGB_COLORS);

	bi = *lpbi;

	// If the driver did not fill in the biSizeImage field, then compute it
	// Each scan line of the image is aligned on a DWORD (32bit) boundary
	if (bi.biSizeImage == 0){
		bi.biSizeImage = ((((bi.biWidth * bi.biBitCount) + 31) & ~31) / 8) 
						* bi.biHeight;
	}

	// Realloc the buffer so that it can hold all the bits
	dwLen += bi.biSizeImage;
	if (handle = GlobalReAlloc(hDIB, dwLen, GMEM_MOVEABLE))
		hDIB = handle;
	else{
		GlobalFree(hDIB);
		hDIB = 0;
		// Reselect the original palette
		SelectPalette(hDC,hPal,FALSE);

		return NULL;
	}

	// Get the bitmap bits
	lpbi = (LPBITMAPINFOHEADER)hDIB;
	m_pBMI = (LPBITMAPINFO)hDIB;
	m_pBits = (LPBYTE)hDIB + (bi.biSize + nColors * sizeof(RGBQUAD));
	///////////////////////////////////////////////
	///////////////////////////////////////////////

	HPALETTE hOldPal = NULL;        // Previous palette
	
	// Get the DIB's palette, then select it into DC
	if (&pal != NULL)
	{
		hPal = (HPALETTE) pal.m_hObject;
		
		// Select as background since we have
		// already realized in forground if needed
		hOldPal = ::SelectPalette(hDC, hPal, TRUE);
	}
	
	/* Make sure to use the stretching mode best for color pictures */
	::SetStretchBltMode(hDC, COLORONCOLOR);	
	BOOL bSuccess = FALSE;
	
	UINT start(0), end, step_size(1);//, offset_y(0);

	end = step_size;
	
	if((UINT)bm.bmHeight < step_size)
		end = (int)bm.bmHeight;
	
	while(start < (UINT)bm.bmHeight){
		
		GetDIBits( hPDC, (HBITMAP)bitmap.GetSafeHandle(),
								start,				// Start scan line
								end - start,				// # of scan lines
								(LPBYTE) m_pBits,	//lpbi 			// address for bitmap bits
								(LPBITMAPINFO)lpbi,		// address of bitmapinfo
								(DWORD)DIB_RGB_COLORS);		// Use RGB for color table
		
		bSuccess = ::SetDIBitsToDevice(hDC,        // hDC		
			rect->left,             // DestX
			rect->top,              // DestY
			RECTWIDTH(rect),        // nDestWidth
			RECTHEIGHT(rect),		// nDestHeight
			rect->left,             // SrcX
			(int)Height() -
			rect->top -
			RECTHEIGHT(rect),		// SrcY
			start,                  // nStartScan
			end - start,			// nNumScans
			m_pBits,                // lpBits
			m_pBMI,                 // lpBitsInfo
			DIB_RGB_COLORS);        // wUsage
		
	    

		start = end;
		end = start + step_size;
		if((UINT)bm.bmHeight < end)
			end = (UINT)bm.bmHeight;
	}
	
	/* Reselect old palette */
	if (hOldPal != NULL)
	{
		::SelectPalette(hDC, hOldPal, TRUE);
	}
	
	return bSuccess;

}
Ejemplo n.º 3
0
void Picker_HandleDrawItem(HWND hWnd, LPDRAWITEMSTRUCT lpDrawItemStruct)
{
	struct PickerInfo *pPickerInfo;
	HDC         hDC = lpDrawItemStruct->hDC;
	RECT        rcItem = lpDrawItemStruct->rcItem;
	UINT        uiFlags = ILD_TRANSPARENT;
	HIMAGELIST  hImageList;
	int         nItem = lpDrawItemStruct->itemID;
	COLORREF    clrTextSave = 0;
	COLORREF    clrBkSave = 0;
	COLORREF    clrImage = GetSysColor(COLOR_WINDOW);
	static TCHAR szBuff[MAX_PATH];
	BOOL        bFocus = (GetFocus() == hWnd);
	LPCTSTR     pszText;
	UINT        nStateImageMask = 0;
	BOOL        bSelected = 0;
	LV_COLUMN   lvc;
	LV_ITEM     lvi;
	RECT        rcAllLabels;
	RECT        rcLabel;
	RECT        rcIcon;
	int         offset = 0;
	SIZE        size;
	int         i = 0, j = 0;
	int         nColumn = 0;
	int         nColumnMax = 0;
	int         *order;
	BOOL        bDrawAsChild = 0;
	int indent_space = 0;
	BOOL		bColorChild = FALSE;
	BOOL		bParentFound = FALSE;
	int		nParent = 0;
	HBITMAP		hBackground = GetBackgroundBitmap();
	MYBITMAPINFO *pbmDesc = GetBackgroundInfo();
	BOOL res = 0;

	pPickerInfo = GetPickerInfo(hWnd);

	order = (int*)malloc(pPickerInfo->nColumnCount * sizeof(*order));
	if (!order)
		return;
	nColumnMax = Picker_GetNumColumns(hWnd);

	if (GetUseOldControl())
	{
		pPickerInfo->pCallbacks->pfnGetColumnOrder(order);
	}
	else
	{
		/* Get the Column Order and save it */
		res = ListView_GetColumnOrderArray(hWnd, nColumnMax, order);

		/* Disallow moving column 0 */
		if (order[0] != 0)
		{
			for (i = 0; i < nColumnMax; i++)
			{
				if (order[i] == 0)
				{
					order[i] = order[0];
					order[0] = 0;
				}
			}
			res = ListView_SetColumnOrderArray(hWnd, nColumnMax, order);
		}
	}

	/* Labels are offset by a certain amount */
	/* This offset is related to the width of a space character */
	GetTextExtentPoint32(hDC, TEXT(" "), 1, &size);
	offset = size.cx;

	lvi.mask	   = LVIF_TEXT | LVIF_IMAGE | LVIF_STATE | LVIF_PARAM;
	lvi.iItem	   = nItem;
	lvi.iSubItem   = order[0];
	lvi.pszText	   = szBuff;
	lvi.cchTextMax = sizeof(szBuff) / sizeof(szBuff[0]);
	lvi.stateMask  = 0xFFFF;	   /* get all state flags */
	res = ListView_GetItem(hWnd, &lvi);

	bSelected = ((lvi.state & LVIS_DROPHILITED) || ( (lvi.state & LVIS_SELECTED)
		&& ((bFocus) || (GetWindowLong(hWnd, GWL_STYLE) & LVS_SHOWSELALWAYS))));

	/* figure out if we indent and draw grayed */
	if (pPickerInfo->pCallbacks->pfnFindItemParent)
		nParent = pPickerInfo->pCallbacks->pfnFindItemParent(hWnd, lvi.lParam);
	else
		nParent = -1;
	bDrawAsChild = (pPickerInfo->pCallbacks->pfnGetViewMode() == VIEW_GROUPED && (nParent >= 0));

	/* only indent if parent is also in this view */
	if ((nParent >= 0) && bDrawAsChild)
	{
		for (i = 0; i < ListView_GetItemCount(hWnd); i++)
		{
			lvi.mask = LVIF_PARAM;
			lvi.iItem = i;
			res = ListView_GetItem(hWnd, &lvi);

			if (lvi.lParam == nParent)
			{
				bParentFound = TRUE;
				break;
			}
		}
	}

	if (pPickerInfo->pCallbacks->pfnGetOffsetChildren && pPickerInfo->pCallbacks->pfnGetOffsetChildren())
	{
		if (!bParentFound && bDrawAsChild)
		{
			/*Reset it, as no Parent is there*/
			bDrawAsChild = FALSE;
			bColorChild = TRUE;
		}
		else
		{
			nParent = -1;
			bParentFound = FALSE;
		}
	}

	res = ListView_GetItemRect_Modified(hWnd, nItem, &rcAllLabels, LVIR_BOUNDS);
	res = ListView_GetItemRect_Modified(hWnd, nItem, &rcLabel, LVIR_LABEL);

	rcAllLabels.left = rcLabel.left;

	if (hBackground != NULL)
	{
		RECT		rcClient;
		HRGN		rgnBitmap;
		RECT		rcTmpBmp = rcItem;
		RECT		rcFirstItem;
		HPALETTE	hPAL;
		HDC 		htempDC;
		HBITMAP 	oldBitmap;

		htempDC = CreateCompatibleDC(hDC);

		oldBitmap = (HBITMAP)SelectObject(htempDC, hBackground);

		GetClientRect(hWnd, &rcClient);
		rcTmpBmp.right = rcClient.right;
		/* We also need to check whether it is the last item
           The update region has to be extended to the bottom if it is */
		if (nItem == ListView_GetItemCount(hWnd) - 1)
			rcTmpBmp.bottom = rcClient.bottom;

		rgnBitmap = CreateRectRgnIndirect(&rcTmpBmp);
		SelectClipRgn(hDC, rgnBitmap);
		DeleteBitmap(rgnBitmap);

		hPAL = GetBackgroundPalette();
		if (hPAL == NULL)
			hPAL = CreateHalftonePalette(hDC);

		if (GetDeviceCaps(htempDC, RASTERCAPS) & RC_PALETTE && hPAL != NULL)
		{
			SelectPalette(htempDC, hPAL, FALSE);
			RealizePalette(htempDC);
		}

		res = ListView_GetItemRect_Modified(hWnd, 0, &rcFirstItem, LVIR_BOUNDS);

		for (i = rcFirstItem.left; i < rcClient.right; i += pbmDesc->bmWidth)
			for (j = rcFirstItem.top; j < rcClient.bottom; j +=  pbmDesc->bmHeight)
				BitBlt(hDC, i, j, pbmDesc->bmWidth, pbmDesc->bmHeight, htempDC, 0, 0, SRCCOPY);

		SelectObject(htempDC, oldBitmap);
		DeleteDC(htempDC);

		if (GetBackgroundPalette() == NULL)
		{
			DeletePalette(hPAL);
			hPAL = NULL;
		}
	}

	indent_space = 0;

	if (bDrawAsChild)
	{
		RECT rect;

		res = ListView_GetItemRect_Modified(hWnd, nItem, &rect, LVIR_ICON);

		/* indent width of icon + the space between the icon and text
         * so left of clone icon starts at text of parent
         */
		indent_space = rect.right - rect.left + offset;
	}

	rcAllLabels.left += indent_space;

	if (bSelected)
	{
		HBRUSH hBrush;
		HBRUSH hOldBrush;

		if (bFocus)
		{
			clrTextSave = SetTextColor(hDC, GetSysColor(COLOR_HIGHLIGHTTEXT));
			clrBkSave	= SetBkColor(hDC, GetSysColor(COLOR_HIGHLIGHT));
			hBrush		= CreateSolidBrush(GetSysColor(COLOR_HIGHLIGHT));
		}
		else
		{
			clrTextSave = SetTextColor(hDC, GetSysColor(COLOR_BTNTEXT));
			clrBkSave	= SetBkColor(hDC, GetSysColor(COLOR_BTNFACE));
			hBrush		= CreateSolidBrush(GetSysColor(COLOR_BTNFACE));
		}

		hOldBrush = (HBRUSH)SelectObject(hDC, hBrush);
		FillRect(hDC, &rcAllLabels, hBrush);
		SelectObject(hDC, hOldBrush);
		DeleteBrush(hBrush);
	}
	else
	{
		if (hBackground == NULL)
		{
			HBRUSH hBrush;

			hBrush = CreateSolidBrush(GetSysColor(COLOR_WINDOW));
			FillRect(hDC, &rcAllLabels, hBrush);
			DeleteBrush(hBrush);
		}

		if (pPickerInfo->pCallbacks->pfnGetOffsetChildren && pPickerInfo->pCallbacks->pfnGetOffsetChildren())
		{
			if (bDrawAsChild || bColorChild)
				clrTextSave = SetTextColor(hDC, GetListCloneColor());
			else
				clrTextSave = SetTextColor(hDC, GetListFontColor());
		}
		else
		{
			if (bDrawAsChild)
				clrTextSave = SetTextColor(hDC, GetListCloneColor());
			else
				clrTextSave = SetTextColor(hDC, GetListFontColor());
		}

		clrBkSave = SetBkColor(hDC, GetSysColor(COLOR_WINDOW));
	}


	if (lvi.state & LVIS_CUT)
	{
		clrImage = GetSysColor(COLOR_WINDOW);
		uiFlags |= ILD_BLEND50;
	}
	else if (bSelected)
	{
		if (bFocus)
			clrImage = GetSysColor(COLOR_HIGHLIGHT);
		else
			clrImage = GetSysColor(COLOR_BTNFACE);

		uiFlags |= ILD_BLEND50;
	}

	nStateImageMask = lvi.state & LVIS_STATEIMAGEMASK;

	if (nStateImageMask)
	{
		int nImage = (nStateImageMask >> 12) - 1;
		hImageList = ListView_GetImageList(hWnd, LVSIL_STATE);
		if (hImageList)
			ImageList_Draw(hImageList, nImage, hDC, rcItem.left, rcItem.top, ILD_TRANSPARENT);
	}

	res = ListView_GetItemRect_Modified(hWnd, nItem, &rcIcon, LVIR_ICON);

	rcIcon.left += indent_space;

	res = ListView_GetItemRect_Modified(hWnd, nItem, &rcItem, LVIR_LABEL);

	hImageList = ListView_GetImageList(hWnd, LVSIL_SMALL);
	if (hImageList)
	{
		UINT nOvlImageMask = lvi.state & LVIS_OVERLAYMASK;
		if (rcIcon.left + 16 + indent_space < rcItem.right)
		{
			ImageList_DrawEx(hImageList, lvi.iImage, hDC, rcIcon.left, rcIcon.top, 16, 16,
				GetSysColor(COLOR_WINDOW), clrImage, uiFlags | nOvlImageMask);
		}
	}

	res = ListView_GetItemRect_Modified(hWnd, nItem, &rcItem, LVIR_LABEL);

	pszText = MakeShortString(hDC, szBuff, rcItem.right - rcItem.left, 2*offset + indent_space);

	rcLabel = rcItem;
	rcLabel.left  += offset + indent_space;
	rcLabel.right -= offset;

	DrawText(hDC, pszText, -1, &rcLabel, DT_LEFT | DT_SINGLELINE | DT_NOPREFIX | DT_VCENTER);

	for (nColumn = 1; nColumn < nColumnMax; nColumn++)
	{
		int 	nRetLen;
		UINT	nJustify;
		LV_ITEM lvItem;

		lvc.mask = LVCF_FMT | LVCF_WIDTH;
		res = ListView_GetColumn(hWnd, order[nColumn], &lvc);

		lvItem.mask 	  = LVIF_TEXT;
		lvItem.iItem	  = nItem;
		lvItem.iSubItem   = order[nColumn];
		lvItem.pszText	  = szBuff;
		lvItem.cchTextMax = sizeof(szBuff) / sizeof(szBuff[0]);

		if (ListView_GetItem(hWnd, &lvItem) == FALSE)
			continue;

		rcItem.left   = rcItem.right;
		rcItem.right += lvc.cx;

		nRetLen = _tcslen(szBuff);
		if (nRetLen == 0)
			continue;

		pszText = MakeShortString(hDC, szBuff, rcItem.right - rcItem.left, 2 * offset);

		nJustify = DT_LEFT;

		if (pszText == szBuff)
		{
			switch (lvc.fmt & LVCFMT_JUSTIFYMASK)
			{
			case LVCFMT_RIGHT:
				nJustify = DT_RIGHT;
				break;

			case LVCFMT_CENTER:
				nJustify = DT_CENTER;
				break;

			default:
				break;
			}
		}

		rcLabel = rcItem;
		rcLabel.left  += offset;
		rcLabel.right -= offset;
		DrawText(hDC, pszText, -1, &rcLabel,
				 nJustify | DT_SINGLELINE | DT_NOPREFIX | DT_VCENTER);
	}

	if (lvi.state & LVIS_FOCUSED && bFocus)
		DrawFocusRect(hDC, &rcAllLabels);

	SetTextColor(hDC, clrTextSave);
	SetBkColor(hDC, clrBkSave);
	free(order);
	res++;
}
Ejemplo n.º 4
0
HDIB BitmapToDIB(HBITMAP hBitmap, HPALETTE hPal)
{
   BITMAP bm;                   // bitmap structure
   BITMAPINFOHEADER bi;         // bitmap header
   BITMAPINFOHEADER FAR *lpbi;  // pointer to BITMAPINFOHEADER
   DWORD dwLen;                 // size of memory block
   HANDLE hDIB, h;              // handle to DIB, temp handle
   HDC hDC;                     // handle to DC
   WORD biBits;                 // bits per pixel

   /* check if bitmap handle is valid */

   if (!hBitmap)
      return NULL;

   /* if no palette is specified, use default palette */
   if (hPal == NULL)
      hPal = (HPALETTE) GetStockObject(DEFAULT_PALETTE);

   /* fill in BITMAP structure */
   GetObject(hBitmap, sizeof(bm), (LPSTR)&bm);

   /* calculate bits per pixel */
   biBits = bm.bmPlanes * bm.bmBitsPixel;

   /* initialize BITMAPINFOHEADER */
   bi.biSize = sizeof(BITMAPINFOHEADER);
   bi.biWidth = bm.bmWidth;
   bi.biHeight = bm.bmHeight;
   bi.biPlanes = 1;
   bi.biBitCount = biBits;
   bi.biCompression = DIB_RGB_COLORS;
   bi.biSizeImage = 0;
   bi.biXPelsPerMeter = 0;
   bi.biYPelsPerMeter = 0;
   bi.biClrUsed = 0;
   bi.biClrImportant = 0;

   /* calculate size of memory block required to store BITMAPINFO */
   dwLen = bi.biSize + PaletteSize((LPSTR)&bi);

   /* get a DC */
   hDC = GetDC(NULL);

   /* select and realize our palette */
   hPal = SelectPalette(hDC, hPal, FALSE);
   RealizePalette(hDC);

   /* alloc memory block to store our bitmap */
   hDIB = GlobalAlloc(GHND, dwLen);

   /* if we couldn't get memory block */
   if (!hDIB)
   {
      /* clean up and return NULL */
      SelectPalette(hDC, hPal, TRUE);
      RealizePalette(hDC);
      ReleaseDC(NULL, hDC);
      return NULL;
   }

   /* lock memory and get pointer to it */
   lpbi = (BITMAPINFOHEADER FAR *)GlobalLock(hDIB);

   /* use our bitmap info. to fill BITMAPINFOHEADER */
   *lpbi = bi;

   /*  call GetDIBits with a NULL lpBits param, so it will calculate the
    *  biSizeImage field for us
    */
   GetDIBits(hDC, hBitmap, 0, (WORD)bi.biHeight, NULL, (LPBITMAPINFO)lpbi,
             DIB_RGB_COLORS);

   /* get the info. returned by GetDIBits and unlock memory block */
   bi = *lpbi;
   GlobalUnlock(hDIB);

   /* if the driver did not fill in the biSizeImage field, make one up */
   if (bi.biSizeImage == 0)
      bi.biSizeImage = WIDTHBYTES((DWORD)bm.bmWidth * biBits) * bm.bmHeight;

   /* realloc the buffer big enough to hold all the bits */
   dwLen = bi.biSize + PaletteSize((LPSTR)&bi) + bi.biSizeImage;
   if (h = GlobalReAlloc(hDIB, dwLen, 0))
      hDIB = h;
   else
   {
      /* clean up and return NULL */
      GlobalFree(hDIB);
      hDIB = NULL;
      SelectPalette(hDC, hPal, TRUE);
      RealizePalette(hDC);
      ReleaseDC(NULL, hDC);
      return NULL;
   }

   /* lock memory block and get pointer to it */
   lpbi = (BITMAPINFOHEADER FAR *)GlobalLock(hDIB);

   /*  call GetDIBits with a NON-NULL lpBits param, and actualy get the
    *  bits this time
    */
   if (GetDIBits(hDC, hBitmap, 0, (WORD)bi.biHeight, (LPSTR)lpbi + (WORD)lpbi
                 ->biSize + PaletteSize((LPSTR)lpbi), (LPBITMAPINFO)lpbi,
                 DIB_RGB_COLORS) == 0)
   {
      /* clean up and return NULL */
      GlobalUnlock(hDIB);
      hDIB = NULL;
      SelectPalette(hDC, hPal, TRUE);
      RealizePalette(hDC);
      ReleaseDC(NULL, hDC);
      return NULL;
   }
   bi = *lpbi;

   /* clean up */
   GlobalUnlock(hDIB);
   SelectPalette(hDC, hPal, TRUE);
   RealizePalette(hDC);
   ReleaseDC(NULL, hDC);

   /* return handle to the DIB */
   return hDIB;
}
Ejemplo n.º 5
0
BOOL
saveBmp( const char *filename, HBITMAP hBitmap )
{
    // 出典: http://blog.csdn.net/bobob/archive/2005/02/20/294759.aspx

    if ( !filename || !(*filename) || !hBitmap )
        return FALSE;

    HDC                 hDC;
    int                 iBits;
    WORD                wBitCount;
    DWORD               dwPaletteSize = 0;
    DWORD               dwBmBitsSize  = 0;
    DWORD               dwDIBSize     = 0;
    BITMAP              Bitmap;
    BITMAPFILEHEADER    bmfHdr;
    BITMAPINFOHEADER    bi;
    LPBITMAPINFOHEADER  lpbi;
    HANDLE              hDib, hPal, hOldPal = NULL;
    FILE                *fp;

    hDC   = CreateDC( "DISPLAY", NULL, NULL, NULL );
    iBits = GetDeviceCaps( hDC, BITSPIXEL ) * GetDeviceCaps( hDC, PLANES );
    DeleteDC( hDC );
    if ( iBits <= 1 )
        wBitCount = 1;
    else if ( iBits <= 4 )
        wBitCount = 4;
    else if ( iBits <= 8 )
        wBitCount = 8;
    else
        wBitCount = 24;

    GetObject( hBitmap, sizeof ( Bitmap ), (LPSTR)&Bitmap );
    bi.biSize          = sizeof ( BITMAPINFOHEADER );
    bi.biWidth         = Bitmap.bmWidth;
    bi.biHeight        = Bitmap.bmHeight;
    bi.biPlanes        = 1;
    bi.biBitCount      = wBitCount;
    bi.biCompression   = BI_RGB;
    bi.biSizeImage     = 0;
    bi.biXPelsPerMeter = 0;
    bi.biYPelsPerMeter = 0;
    bi.biClrImportant  = 0;
    bi.biClrUsed       = 0;

    dwBmBitsSize =
            ((Bitmap.bmWidth * wBitCount + 31) / 32) * 4 *Bitmap.bmHeight;

    hDib  = GlobalAlloc(
                GHND,
                dwBmBitsSize + dwPaletteSize + sizeof ( BITMAPINFOHEADER ) );
    lpbi  = (LPBITMAPINFOHEADER)GlobalLock( hDib );
    *lpbi = bi;

    hPal = GetStockObject( DEFAULT_PALETTE );
    if ( hPal ) { 
        hDC     = ::GetDC( NULL ); 
        hOldPal = ::SelectPalette( hDC, (HPALETTE)hPal, FALSE );
        RealizePalette( hDC );
    }

    GetDIBits( hDC, hBitmap, 0, (UINT) Bitmap.bmHeight,
               (LPSTR)lpbi + sizeof ( BITMAPINFOHEADER ) + dwPaletteSize,
               (BITMAPINFO *)lpbi, DIB_RGB_COLORS );

    if ( hOldPal ) {
        ::SelectPalette( hDC, (HPALETTE)hOldPal, TRUE );
        RealizePalette( hDC );
        ::ReleaseDC( NULL, hDC );
    }

    fp = fopen( filename, "wb" );
    if ( !fp ) {
        GlobalUnlock( hDib );
        GlobalFree( hDib );
        return ( FALSE );
    }

    bmfHdr.bfType = 0x4D42; // "BM"
    dwDIBSize     = sizeof ( BITMAPFILEHEADER ) +
                    sizeof ( BITMAPINFOHEADER ) +
                    dwPaletteSize +
                    dwBmBitsSize;
    bmfHdr.bfSize = dwDIBSize;
    bmfHdr.bfReserved1 = 0;
    bmfHdr.bfReserved2 = 0;
    bmfHdr.bfOffBits = sizeof ( BITMAPFILEHEADER ) +
                       sizeof ( BITMAPINFOHEADER ) +
                       dwPaletteSize;

    fwrite( &bmfHdr, sizeof ( BITMAPFILEHEADER ), 1, fp );
    fwrite( lpbi, sizeof ( BYTE ), dwDIBSize, fp );

    GlobalUnlock( hDib );
    GlobalFree( hDib );
    fclose( fp );

    return TRUE;
}
Ejemplo n.º 6
0
void PLWEMFDecoder::GetImage (PLBmpBase & Bmp)
{
	HPALETTE hpal = NULL;
  LPLOGPALETTE plogpal (0);

  if (GetBitsPerPixel() == 8) {
		plogpal = (LPLOGPALETTE)new PLBYTE[sizeof(LOGPALETTE) + (sizeof(PALETTEENTRY) * 256)];
		memset(plogpal,0x0,sizeof(LOGPALETTE) + sizeof(PALETTEENTRY)*256);
		plogpal->palVersion = 0x300;
		plogpal->palNumEntries = 256;
		if (plogpal == NULL) {
			PLASSERT(false);
			raiseError (PL_ERRNO_MEMORY,"Cannot allocate palette.");
		}
    UINT pe = GetEnhMetaFilePaletteEntries(m_hemf, 0, NULL);
		GetEnhMetaFilePaletteEntries(m_hemf, pe, plogpal->palPalEntry);
	}

	// Setup a logical palette for our memory dc and also a
	// paintlib compatible palette for the paintlib bitmap
  PLPixel32 pPal[256];
	if (plogpal) {
		for (UINT i = 0; i < 256; i++) {
			pPal[i] = *(PLPixel32*)&plogpal->palPalEntry[i];
		}

		if ( 0 != (hpal = CreatePalette((LPLOGPALETTE)plogpal)) ) {
			m_holdpal = SelectPalette(m_memdc, hpal, false);
			RealizePalette(m_memdc);
		}
		Bmp.SetPalette(pPal);
		delete [] plogpal;
	}

	// Play the metafile into the device context
	// First, setup a bounding rectangle and fill
	// the memory dc with white (some metafiles only
	// use a black pen to draw and have no actual fill
	// color set, This would cause a black on black
	// painting which is rather useless
	RECT rc;
	rc.left = rc.top = 0;
	rc.bottom = GetHeight();
	rc.right = GetWidth();

	FillRect(m_memdc,&rc,(HBRUSH)GetStockObject(WHITE_BRUSH));

	// Heeere we go....
	/*BOOL bres =*/ PlayEnhMetaFile(m_memdc,m_hemf,&rc);

	// Finally, convert the Windows bitmap into a paintlib bitmap
	PLWinBmp& winbmp = dynamic_cast<PLWinBmp&>(Bmp);
	BITMAPINFO* pBMI = (BITMAPINFO*)winbmp.GetBMI();
	//PLBYTE* pBits = (PLBYTE*)winbmp.GetBits();
	if (GetBitsPerPixel() == 8) {
		GetDIBits(m_dc, m_bm, 0, GetHeight(), winbmp.GetBits(), pBMI, DIB_RGB_COLORS);
	}
	else {
		GetDIBits(m_dc, m_bm, 0, GetHeight(), winbmp.GetBits(), pBMI, DIB_PAL_COLORS);
	}
}
Ejemplo n.º 7
0
HDIB FAR ChangeDIBFormat(HDIB hDIB, WORD wBitCount, DWORD dwCompression)
{
   HDC                hDC;             // Handle to DC
   HBITMAP            hBitmap;         // Handle to bitmap
   BITMAP             Bitmap;          // BITMAP data structure
   BITMAPINFOHEADER   bi;              // Bitmap info header
   LPBITMAPINFOHEADER lpbi;            // Pointer to bitmap info
   HDIB               hNewDIB = NULL;  // Handle to new DIB
   HPALETTE           hPal, hOldPal;   // Handle to palette, prev pal
   WORD               DIBBPP, NewBPP;  // DIB bits per pixel, new bpp
   DWORD              DIBComp, NewComp;// DIB compression, new compression

   /* Check for a valid DIB handle */
   if (!hDIB)
      return NULL;

   /* Get the old DIB's bits per pixel and compression format */
   lpbi = (LPBITMAPINFOHEADER)GlobalLock(hDIB);
   DIBBPP = ((LPBITMAPINFOHEADER)lpbi)->biBitCount;
   DIBComp = ((LPBITMAPINFOHEADER)lpbi)->biCompression;
   GlobalUnlock(hDIB);

   /* Validate wBitCount and dwCompression
    * They must match correctly (i.e., BI_RLE4 and 4 BPP or
    * BI_RLE8 and 8BPP, etc.) or we return failure */
   if (wBitCount == 0)
      {
      NewBPP = DIBBPP;
      if ((dwCompression == BI_RLE4 && NewBPP == 4) ||
      (dwCompression == BI_RLE8 && NewBPP == 8) ||
      (dwCompression == BI_RGB))
     NewComp = dwCompression;
      else
     return NULL;
      }
   else if (wBitCount == 1 && dwCompression == BI_RGB)
      {
      NewBPP = wBitCount;
      NewComp = BI_RGB;
      }
   else if (wBitCount == 4)
      {
      NewBPP = wBitCount;
      if (dwCompression == BI_RGB || dwCompression == BI_RLE4)
     NewComp = dwCompression;
      else
     return NULL;
      }
   else if (wBitCount == 8)
      {
      NewBPP = wBitCount;
      if (dwCompression == BI_RGB || dwCompression == BI_RLE8)
     NewComp = dwCompression;
      else
     return NULL;
      }
   else if (wBitCount == 24 && dwCompression == BI_RGB)
      {
      NewBPP = wBitCount;
      NewComp = BI_RGB;
      }
   else
      return NULL;

   /* Save the old DIB's palette */
   hPal = CreateDIBPalette(hDIB);
   if (!hPal)
      return NULL;

   /* Convert old DIB to a bitmap */
   hBitmap = DIBToBitmap(hDIB, hPal);
   if (!hBitmap)
      {
      DeleteObject(hPal);
      return NULL;
      }

   /* Get info about the bitmap */
   GetObject(hBitmap, sizeof(BITMAP), (LPSTR)&Bitmap);

   /* Fill in the BITMAPINFOHEADER appropriately */
   bi.biSize               = sizeof(BITMAPINFOHEADER);
   bi.biWidth              = Bitmap.bmWidth;
   bi.biHeight             = Bitmap.bmHeight;
   bi.biPlanes             = 1;
   bi.biBitCount           = NewBPP;
   bi.biCompression        = NewComp;
   bi.biSizeImage          = 0;
   bi.biXPelsPerMeter      = 0;
   bi.biYPelsPerMeter      = 0;
   bi.biClrUsed            = 0;
   bi.biClrImportant       = 0;

   /* Go allocate room for the new DIB */
   hNewDIB = AllocRoomForDIB(bi, hBitmap);
   if (!hNewDIB)
      return NULL;

   /* Get a pointer to the new DIB */
   lpbi = (VOID FAR *)GlobalLock(hNewDIB);

   /* Get a DC and select/realize our palette in it */
   hDC  = GetDC(NULL);
   hOldPal = SelectPalette(hDC, hPal, FALSE);
   RealizePalette(hDC);

   /* Call GetDIBits and get the new DIB bits */
   if (!GetDIBits(hDC, hBitmap, 0, (WORD) lpbi->biHeight,
       (LPSTR)lpbi + (WORD)lpbi->biSize + PaletteSize((LPSTR)lpbi),
       (LPBITMAPINFO)lpbi, DIB_RGB_COLORS))
      {
      GlobalUnlock(hNewDIB);
      GlobalFree(hNewDIB);
      hNewDIB = NULL;
      }

   /* Clean up and return */
   SelectPalette(hDC, hOldPal, TRUE);
   RealizePalette(hDC);
   ReleaseDC(NULL, hDC);

   if (hNewDIB)
      /* Unlock the new DIB's memory block */
      GlobalUnlock(hNewDIB);

   DeleteObject(hBitmap);
   DeleteObject(hPal);

   return hNewDIB;
}
Ejemplo n.º 8
0
// Window procedure, handles all messages for this program
LRESULT CALLBACK WndProc(	HWND 	hWnd,
							UINT	message,
							WPARAM	wParam,
							LPARAM	lParam)
	{
	static HGLRC hRC;		// Permenant Rendering context
	static HDC hDC;			// Private GDI Device context

	switch (message)
	   	{
		// Window creation, setup for OpenGL
		case WM_CREATE:
			// Store the device context
			hDC = GetDC(hWnd);		

			// Select the pixel format
			SetDCPixelFormat(hDC);		

			// Create the rendering context and make it current
			hRC = wglCreateContext(hDC);
			wglMakeCurrent(hDC, hRC);

			// Create the palette
			hPalette = GetOpenGLPalette(hDC);

			SetupRC(hDC);

			break;

		// Window is being destroyed, cleanup
		case WM_DESTROY:
			// Kill the timer that we created
			KillTimer(hWnd,101);

			glDeleteLists(nFontList, 128);

			// Deselect the current rendering context and delete it
			wglMakeCurrent(hDC,NULL);
			wglDeleteContext(hRC);

			// Delete the palette
			if(hPalette != NULL)
				DeleteObject(hPalette);

			// Tell the application to terminate after the window
			// is gone.
			PostQuitMessage(0);
			break;

		// Window is resized.
		case WM_SIZE:
			// Call our function which modifies the clipping
			// volume and viewport
			ChangeSize(LOWORD(lParam), HIWORD(lParam));
			break;

		// The painting function.  This message sent by Windows 
		// whenever the screen needs updating.
		case WM_PAINT:
			{
			// Call OpenGL drawing code
			RenderScene();

			// Call function to swap the buffers
			SwapBuffers(hDC);

            ValidateRect(hWnd,NULL);
			}
			break;


		// Windows is telling the application that it may modify
		// the system palette.  This message in essance asks the 
		// application for a new palette.
		case WM_QUERYNEWPALETTE:
			// If the palette was created.
			if(hPalette)
				{
				int nRet;

				// Selects the palette into the current device context
				SelectPalette(hDC, hPalette, FALSE);

				// Map entries from the currently selected palette to
				// the system palette.  The return value is the number 
				// of palette entries modified.
				nRet = RealizePalette(hDC);

				// Repaint, forces remap of palette in current window
				InvalidateRect(hWnd,NULL,FALSE);

				return nRet;
				}
			break;

	
		// This window may set the palette, even though it is not the 
		// currently active window.
		case WM_PALETTECHANGED:
			// Don't do anything if the palette does not exist, or if
			// this is the window that changed the palette.
			if((hPalette != NULL) && ((HWND)wParam != hWnd))
				{
				// Select the palette into the device context
				SelectPalette(hDC,hPalette,FALSE);

				// Map entries to system palette
				RealizePalette(hDC);
				
				// Remap the current colors to the newly realized palette
				UpdateColors(hDC);
				return 0;
				}
			break;


        default:   // Passes it on if unproccessed
            return (DefWindowProc(hWnd, message, wParam, lParam));

        }

    return (0L);
	}
Ejemplo n.º 9
0
int GPsetwidgetattr (Gwidget_t *widget, int attrn, Gwattr_t *attrp) {
    PIXsize_t ps;
    int color, ai;

    for (ai = 0; ai < attrn; ai++) {
        switch (attrp[ai].id) {
        case G_ATTRORIGIN:
            break;
        case G_ATTRSIZE:
            break;
        case G_ATTRNAME:
            break;
        case G_ATTRMODE:
            break;
        case G_ATTRCOLOR:
            color = attrp[ai].u.c.index;
            if (color < 0 || color > G_MAXCOLORS) {
                Gerr (POS, G_ERRBADCOLORINDEX, color);
                return -1;
            }
            WPU->colors[color].color.peRed = attrp[ai].u.c.r;
            WPU->colors[color].color.peGreen = attrp[ai].u.c.g;
            WPU->colors[color].color.peBlue = attrp[ai].u.c.b;
            WPU->colors[color].color.peFlags = 0;
            if (color >= WPU->ncolor)
                ResizePalette (WPU->cmap, color + 1), WPU->ncolor = color + 1;
            SetPaletteEntries (
                WPU->cmap, (int) color, 1, &WPU->colors[color].color
            );
            RealizePalette (GC);
            WPU->colors[color].inuse = TRUE;
            if (color == WPU->gattr.color)
                WPU->gattr.color = -1;
            break;
        case G_ATTRVIEWPORT:
            if (attrp[ai].u.s.x == 0)
                attrp[ai].u.s.x = 1;
            if (attrp[ai].u.s.y == 0)
                attrp[ai].u.s.y = 1;
            WPU->vsize.x = attrp[ai].u.s.x + 0.5;
            WPU->vsize.y = attrp[ai].u.s.y + 0.5;
            ps.x = WPU->vsize.x, ps.y = WPU->vsize.y;
            break;
        case G_ATTRWINDOW:
            if (attrp[ai].u.r.o.x == attrp[ai].u.r.c.x)
                attrp[ai].u.r.c.x = attrp[ai].u.r.o.x + 1;
            if (attrp[ai].u.r.o.y == attrp[ai].u.r.c.y)
                attrp[ai].u.r.c.y = attrp[ai].u.r.o.y + 1;
            WPU->wrect = attrp[ai].u.r;
            break;
        case G_ATTRWINDOWID:
            Gerr (POS, G_ERRCANNOTSETATTR2, "windowid");
            return -1;
        case G_ATTRUSERDATA:
            widget->udata = attrp[ai].u.u;
            break;
        default:
            Gerr (POS, G_ERRBADATTRID, attrp[ai].id);
            return -1;
        }
    }
    return 0;
}
Ejemplo n.º 10
0
/////////////////////////////////////////////////////////////////////////////
// AppWndProc( hwnd, uiMessage, wParam, lParam )
//
// The window proc for the app's main (tiled) window.  This processes all
// of the parent window's messages.
//
LONG FAR PASCAL _export AppWndProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam)
{
    PAINTSTRUCT ps;
    HDC hdc;
    BOOL f;

		//is it the registered message?  (this proc is called after the creation
		//of the msgApp).

	 if (msg == msgApp) {				
 		 if (bShowRendering) {
		 	HDC hdc = GetDC(hwndApp);
		 	AppPaint(hwndApp, hdc);
		 	ReleaseDC(hwndApp, hdc);
		 	bShowRendering = (int)wParam;	//sent a 0 to turn off bShowRendering.
		 }
	    return 0L;
	 }
		
		//well, how about standard Windows messages?

    switch (msg)
    {
    case WM_CREATE:
			//let WM_SIZE do all the work.
	      break;

    case WM_ACTIVATEAPP:
		    bAppActive = (BOOL)wParam;
			wt_reset_input();
			// *** Remap the system colors and deal with the palette
			AppActivate(bAppActive);

			if (hpalApp)
			{
				HDC hdc = GetDC(hwnd);

				UnrealizeObject(hpalApp);
				SelectPalette(hdc, hpalApp, FALSE);
				RealizePalette(hdc);

				ReleaseDC(hwnd, hdc);
			}
			break;

    case WM_SIZE:			
			wt_reset_input();
		   nBitmapW = LOWORD(lParam);			//new size.
		   nBitmapH = HIWORD(lParam);

			nBitmapW /= StretchFactor;
			nBitmapH /= StretchFactor;

			//Windows DIBs, including WinG bitmaps, are always a multiple of 
			//32-bits wide.  For us, using the typical 8-bit per pixel bitmap,
			//that means we need to ensure the width is a multiple of 4.  This
			//is important because the WT engine treats a bitmap's width and 
			//pitch as one - there is no way for WT to draw into a bitmap
			//using a width different than the pitch.  So we force the bitmap's
			//width to be a multiple of 4, to be both Windows and WT compatible.
			//Note we could have patched WT to deal with the concept of a 
			//bitmap pitch, but that's too much change.

			nBitmapW = ((nBitmapW+3)/4)*4;

			if(Buffer)
			{						//resizing, minimizing, maximizing.
			 	HBITMAP hbm;
			   int Counter;

				//Create a new 8-bit WinGBitmap with the new size
				BufferHeader.Header.biWidth = nBitmapW;
				BufferHeader.Header.biHeight = nBitmapH * Orientation;

				//probably don't need to do this, but do it anyway.
			   for(Counter = 0;Counter < 256;Counter++) {
				    	BufferHeader.aColors[Counter].rgbRed   = ColorTable[Counter].rgbRed;
				    	BufferHeader.aColors[Counter].rgbGreen = ColorTable[Counter].rgbGreen;
				    	BufferHeader.aColors[Counter].rgbBlue  = ColorTable[Counter].rgbBlue;
				    	BufferHeader.aColors[Counter].rgbReserved = 0;
				}

				hbm = WinG.pCreateBitmap(Buffer,
					(BITMAPINFO *)&BufferHeader, &pBuffer);

				//  Select it in and delete the old one
				hbm = (HBITMAP)SelectObject(Buffer, hbm);
				DeleteObject(hbm);

   			PatBlt(Buffer, 0,0,nBitmapW,nBitmapH, BLACKNESS);

	         wt_set_fb_mem(pBuffer);		//tell WT about new bitmap address.
			   wt_reinit(nBitmapW,nBitmapH);  //and about new bitmap size.
				wt_render();					//and have WT render a frame.

			}
			else						//first time.
			{
				//  Create a new WinGDC and 8-bit WinGBitmap

				HBITMAP hbm;
			   int Counter;

				//  Get WinG to recommend the fastest DIB format

				if(WinG.pRecommendDIBFormat((BITMAPINFO *)&BufferHeader))
				{
					//  make sure it's 8bpp and remember the orientation

					BufferHeader.Header.biBitCount = 8;
					BufferHeader.Header.biCompression = BI_RGB;
					Orientation = BufferHeader.Header.biHeight;
					if (Orientation > 0) {
						DebugMsg("WT requires a top-down bitmap!\nYou are about to hit a brick wall at 90 MPH!");
						PostQuitMessage(1);		//works but slams palette.  bummer.
					}
				}
				else
				{
					//  set it up ourselves
	
					BufferHeader.Header.biSize = sizeof(BITMAPINFOHEADER);
					BufferHeader.Header.biPlanes = 1;
					BufferHeader.Header.biBitCount = 8;
					BufferHeader.Header.biCompression = BI_RGB;
					BufferHeader.Header.biSizeImage = 0;
					BufferHeader.Header.biClrUsed = 0;
					BufferHeader.Header.biClrImportant = 0;
				}

				BufferHeader.Header.biWidth = nBitmapW;
				BufferHeader.Header.biHeight = nBitmapH * Orientation;

//#define BAD_PALETTE_CODE
#ifdef BAD_PALETTE_CODE
//This code sets an incorrect palette, but at least you can still use
//regular windows tools.  Good for debugging.
			   HDC Screen;
			   RGBQUAD *pColorTable;

				//  create an identity palette from the DIB's color table

				//  get the 20 system colors as PALETTEENTRIES
    
			    Screen = GetDC(0);

			    GetSystemPaletteEntries(Screen,0,10,LogicalPalette.aEntries);
			    GetSystemPaletteEntries(Screen,246,10,
								LogicalPalette.aEntries + 246);

				ReleaseDC(0,Screen);

				// initialize the logical palette and DIB color table

			    for(Counter = 0;Counter < 10;Counter++)
			    {
			    	// copy the system colors into the DIB header
			    	// WinG will do this in WinGRecommendDIBFormat,
			    	// but it may have failed above so do it here anyway
			    	
			    	BufferHeader.aColors[Counter].rgbRed =
			    					LogicalPalette.aEntries[Counter].peRed;
			    	BufferHeader.aColors[Counter].rgbGreen =
			    					LogicalPalette.aEntries[Counter].peGreen;
			    	BufferHeader.aColors[Counter].rgbBlue =
			    					LogicalPalette.aEntries[Counter].peBlue;
			    	BufferHeader.aColors[Counter].rgbReserved = 0;

   					LogicalPalette.aEntries[Counter].peFlags = 0;

			    	BufferHeader.aColors[Counter + 246].rgbRed =
		    					LogicalPalette.aEntries[Counter + 246].peRed;
			    	BufferHeader.aColors[Counter + 246].rgbGreen =
		    					LogicalPalette.aEntries[Counter + 246].peGreen;
			    	BufferHeader.aColors[Counter + 246].rgbBlue =
		    					LogicalPalette.aEntries[Counter + 246].peBlue;
			    	BufferHeader.aColors[Counter + 246].rgbReserved = 0;

   					LogicalPalette.aEntries[Counter + 246].peFlags = 0;
   				}

            for (i=0; i<256; i++) {
               ColorTable[i].rgbRed = 0;
               ColorTable[i].rgbGreen = 0;
               ColorTable[i].rgbBlue = 0;
            }

            nColors = wt_load_palette();
            for (i=0; i<nColors; i++) {
               int r,g,b;
               wt_get_palette_entry(i,&r,&g,&b);
               ColorTable[i].rgbRed = r;
               ColorTable[i].rgbGreen = g;
               ColorTable[i].rgbBlue = b;
            }
            pColorTable = &ColorTable[0];

			    for(Counter = 10;Counter < 246;Counter++)
			    {
			    	// copy from the original color table to the WinGBitmap's
			    	// color table and the logical palette

			    	BufferHeader.aColors[Counter].rgbRed =
    					LogicalPalette.aEntries[Counter].peRed =
    						pColorTable[Counter].rgbRed;
			    	BufferHeader.aColors[Counter].rgbGreen =
    					LogicalPalette.aEntries[Counter].peGreen =
    						pColorTable[Counter].rgbGreen;
			    	BufferHeader.aColors[Counter].rgbBlue =
    					LogicalPalette.aEntries[Counter].peBlue =
    						pColorTable[Counter].rgbBlue;
			    	BufferHeader.aColors[Counter].rgbReserved = 0;
  					LogicalPalette.aEntries[Counter].peFlags = PC_NOCOLLAPSE;
			    }

			    hpalApp = CreatePalette((LOGPALETTE *)&LogicalPalette);
#else
//GOOD_PALETTE_CODE
//Working palette code.  Has correct colors. And identity.  Same frame
//rate as bad palette code.  This really hoses Windows colors, so
//a GUI debugger's windows are really hard to read.  I couldn't read the
//Symantec IDDE's windows - so I #ifdef'd the bad palette code in for
//debugging.
//Anyway, this code works.  Need 3 things for identity, as far as I can tell:
//1. you have to be writing to your bitmap using a specific palette, 
//2. this palette has to be made into a Windows palette, and selected.
//3. this palette has to be copied into the BitmapInfo header of the WinG
//   bitmap, before creating it (actually as a parameter to creating it).
//
				ClearSystemPalette();
				CreateWTPalette();

			    for(Counter = 0;Counter < 256;Counter++) {
				    	BufferHeader.aColors[Counter].rgbRed   = ColorTable[Counter].rgbRed;
				    	BufferHeader.aColors[Counter].rgbGreen = ColorTable[Counter].rgbGreen;
				    	BufferHeader.aColors[Counter].rgbBlue  = ColorTable[Counter].rgbBlue;
				    	BufferHeader.aColors[Counter].rgbReserved = 0;
				}
#endif
			    
				//  Create a WinGDC and Bitmap, then select away
				Buffer = WinG.pCreateDC();
				hbm = WinG.pCreateBitmap(Buffer,
					(BITMAPINFO *)&BufferHeader, &pBuffer);

				//  Store the old hbitmap to select back in before deleting
				gbmOldMonoBitmap = (HBITMAP)SelectObject(Buffer, hbm);

   			PatBlt(Buffer, 0,0,nBitmapW,nBitmapH, BLACKNESS);

            wt_set_fb_mem(pBuffer);		//hack to get around WT's code.
            strcpy(szDefaultWorldFileName, szModulePath);
            strcat(szDefaultWorldFileName, DEFAULT_WORLD_FILEPATH);
            wt_init(szDefaultWorldFileName, nBitmapW,nBitmapH); 
				AppSetCaption(DEFAULT_WORLD_FILETITLE);

            wt_render();
			}
			bWTinitialized = TRUE;		
            break;

		case WM_KEYDOWN:
						//set WT's keyboard array, then do a WT cycle.
				switch (wParam) {
					case VK_UP:
						kbPressed[kbUpArrow] = 1; break;
					case VK_DOWN:
						kbPressed[kbDownArrow] = 1; break;
					case VK_LEFT:
						kbPressed[kbLeftArrow] = 1; break;
					case VK_RIGHT:
						kbPressed[kbRightArrow] = 1; break;
					case VK_CONTROL:
						kbPressed[kbCtrl] = 1; break;
					case VK_ESCAPE:
						kbPressed[kbEsc] = 1; 
						//DestroyWindow() here?  let's check to ensure that func
						//  will send the proper msgs to close stuff.
						break;
					case VK_SPACE:
						kbPressed[kbSpace] = 1; break;
					case VK_SHIFT:
						kbPressed[kbLeftShift] = 1; break;
					case VK_TAB:
						kbPressed[kbAlt] = 1; break;
				}

					//tried using wt_input/wt_render/InvalidateRect sequence
					//here, but was sometimes jerky (missed frames, actually), 
					//if there was too much keyboard activity.  
					//I think windows was collapsing queued/pending
					//WM_PAINT messages, so that the app got one instead of a 
					//sudden stream.  Anyhow now I draw immediately, and it works
					//great.  Note that AppIdle() processing is required to
					//have acceleration/deceleration/monsters/events occur without
					//keyboard input.  I guess a timer could also be used.
					//So I ended up using this helper routine to repaint.

				AppDoCycle();
				break;

		case WM_KEYUP:
						//set WT's keyboard array, then do a WT cycle.
				switch (wParam) {
					case VK_UP:
						kbPressed[kbUpArrow] = 0; break;
					case VK_DOWN:
						kbPressed[kbDownArrow] = 0; break;
					case VK_LEFT:
						kbPressed[kbLeftArrow] = 0; break;
					case VK_RIGHT:
						kbPressed[kbRightArrow] = 0; break;
					case VK_CONTROL:
						kbPressed[kbCtrl] = 0; break;
					case VK_ESCAPE:
						kbPressed[kbEsc] = 0; break;
					case VK_SPACE:
						kbPressed[kbSpace] = 0; break;
					case VK_SHIFT:
						kbPressed[kbLeftShift] = 0; break;
					case VK_TAB:
						kbPressed[kbAlt] = 0; break;
				}

				AppDoCycle();
				break;

		case WM_LBUTTONDOWN:
				break;

		case WM_RBUTTONDOWN:
				break;

      case WM_MOUSEMOVE:
        	break;

      case WM_COMMAND:
            return AppCommand(hwnd,msg,wParam,lParam);

		case WM_DESTROY:
            PostQuitMessage(0);
            break;

      case WM_CLOSE:
		 	   break;

      case WM_PALETTECHANGED:
		    	if ((HWND)wParam == hwnd)
					break;

	    // fall through to WM_QUERYNEWPALETTE

		case WM_QUERYNEWPALETTE:
		    hdc = GetDC(hwnd);

		    if (hpalApp)
				SelectPalette(hdc, hpalApp, FALSE);
	
		    f = RealizePalette(hdc);
		    ReleaseDC(hwnd,hdc);
	
		    if (f)
				InvalidateRect(hwnd,NULL,TRUE);
	
		    return f;
	
	     case WM_PAINT:
		    hdc = BeginPaint(hwnd,&ps);
			 SelectPalette(hdc, hpalApp, FALSE);
			 RealizePalette(hdc);
		    AppPaint (hwnd,hdc);
	       EndPaint(hwnd,&ps);
	       return 0L;
	    }
	return DefWindowProc(hwnd,msg,wParam,lParam);
}
Ejemplo n.º 11
0
// If necessary, creates a 3-3-2 palette for the device context listed.
HPALETTE GetOpenGLPalette(HDC hDC)
	{
	HPALETTE hRetPal = NULL;	// Handle to palette to be created
	PIXELFORMATDESCRIPTOR pfd;	// Pixel Format Descriptor
	LOGPALETTE *pPal;			// Pointer to memory for logical palette
	int nPixelFormat;			// Pixel format index
	int nColors;				// Number of entries in palette
	int i;						// Counting variable
	BYTE RedRange,GreenRange,BlueRange;
								// Range for each color entry (7,7,and 3)


	// Get the pixel format index and retrieve the pixel format description
	nPixelFormat = GetPixelFormat(hDC);
	DescribePixelFormat(hDC, nPixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &pfd);

	// Does this pixel format require a palette?  If not, do not create a
	// palette and just return NULL
	if(!(pfd.dwFlags & PFD_NEED_PALETTE))
		return NULL;

	// Number of entries in palette.  8 bits yeilds 256 entries
	nColors = 1 << pfd.cColorBits;	

	// Allocate space for a logical palette structure plus all the palette entries
	pPal = (LOGPALETTE*)malloc(sizeof(LOGPALETTE) +nColors*sizeof(PALETTEENTRY));

	// Fill in palette header 
	pPal->palVersion = 0x300;		// Windows 3.0
	pPal->palNumEntries = nColors; // table size

	// Build mask of all 1's.  This creates a number represented by having
	// the low order x bits set, where x = pfd.cRedBits, pfd.cGreenBits, and
	// pfd.cBlueBits.  
	RedRange = (1 << pfd.cRedBits) -1;
	GreenRange = (1 << pfd.cGreenBits) - 1;
	BlueRange = (1 << pfd.cBlueBits) -1;

	// Loop through all the palette entries
	for(i = 0; i < nColors; i++)
		{
		// Fill in the 8-bit equivalents for each component
		pPal->palPalEntry[i].peRed = (i >> pfd.cRedShift) & RedRange;
		pPal->palPalEntry[i].peRed = (unsigned char)(
			(double) pPal->palPalEntry[i].peRed * 255.0 / RedRange);

		pPal->palPalEntry[i].peGreen = (i >> pfd.cGreenShift) & GreenRange;
		pPal->palPalEntry[i].peGreen = (unsigned char)(
			(double)pPal->palPalEntry[i].peGreen * 255.0 / GreenRange);

		pPal->palPalEntry[i].peBlue = (i >> pfd.cBlueShift) & BlueRange;
		pPal->palPalEntry[i].peBlue = (unsigned char)(
			(double)pPal->palPalEntry[i].peBlue * 255.0 / BlueRange);

		pPal->palPalEntry[i].peFlags = (unsigned char) NULL;
		}
		

	// Create the palette
	hRetPal = CreatePalette(pPal);

	// Go ahead and select and realize the palette for this device context
	SelectPalette(hDC,hRetPal,FALSE);
	RealizePalette(hDC);

	// Free the memory used for the logical palette structure
	free(pPal);

	// Return the handle to the new palette
	return hRetPal;
	}
Ejemplo n.º 12
0
BOOL CDIB::SetBitmap(HBITMAP hBitmap, HPALETTE hPal /*= NULL*/)
{
//    DeleteObject();

    if (!hBitmap)
        return FALSE;

    // Get dimensions of bitmap
    BITMAP bm;
    if (!::GetObject(hBitmap, sizeof(bm),(LPVOID)&bm))
        return FALSE;
    bm.bmHeight = abs(bm.bmHeight);

	HDC hDC = GetWindowDC(NULL);
    HPALETTE hOldPal = NULL;

    m_iColorTableSize = NumColorEntries(bm.bmBitsPixel, BI_RGB);

    // Initialize the BITMAPINFOHEADER in m_DIBinfo
    BITMAPINFOHEADER& bih = m_DIBinfo.bmiHeader;
    bih.biSize          = sizeof(BITMAPINFOHEADER);
    bih.biWidth         = bm.bmWidth;
    bih.biHeight        = bm.bmHeight;
    bih.biPlanes        = 1;                // Must always be 1 according to docs
    bih.biBitCount      = bm.bmBitsPixel;
    bih.biCompression   = BI_RGB;
    bih.biSizeImage     = BytesPerLine(bm.bmWidth, bm.bmBitsPixel) * bm.bmHeight;
    bih.biXPelsPerMeter = 0;
    bih.biYPelsPerMeter = 0;
    bih.biClrUsed       = 0;
    bih.biClrImportant  = 0;

    GetColorTableEntries(hDC, hBitmap);

    // If we have a palette supplied, then set the palette (and hance DIB color
    // table) using this palette
    if (hPal)
        SetPalette(hPal);

    if (hPal)
    {
        hOldPal = SelectPalette(hDC, m_hPal, FALSE);
        RealizePalette(hDC);
    }

    // Create it!
    m_hBitmap = CreateDIBSection(hDC, (const BITMAPINFO*) m_DIBinfo, m_iColorDataType, &m_ppvBits, NULL, 0);
    if (hOldPal)
        SelectPalette(hDC, hOldPal, FALSE);
    hOldPal = NULL; 

    if (! m_hBitmap)
    {
        TRACE0("Unable to CreateDIBSection\n");
        return FALSE;
    }

    // If palette was supplied then create a palette using the entries in the DIB
    // color table.
    if (! hPal)
        CreatePalette();

    // Need to copy the supplied bitmap onto the newly created DIBsection
    HDC hMemDC = CreateCompatibleDC(hDC);
	HDC hCopyDC = CreateCompatibleDC(hDC);
	
    if (! hMemDC || ! hCopyDC) 
    {
        TRACE0("Unable to create compatible DC's\n");
        //AfxThrowResourceException();
    }

    if (m_hPal)
    {
        SelectPalette(hMemDC, m_hPal, FALSE);   RealizePalette(hMemDC);
        SelectPalette(hCopyDC, m_hPal, FALSE);  RealizePalette(hCopyDC);
    }

    HBITMAP hOldMemBitmap  = (HBITMAP) SelectObject(hMemDC,  hBitmap);
    HBITMAP hOldCopyBitmap = (HBITMAP) SelectObject(hCopyDC, m_hBitmap);

    BitBlt(hCopyDC, 0, 0, bm.bmWidth, bm.bmHeight, hMemDC, 0, 0, SRCCOPY);

    SelectObject(hMemDC,  hOldMemBitmap);
    SelectObject(hCopyDC, hOldCopyBitmap);

    if (m_hPal)
    {
		HGDIOBJ hObj = ::GetStockObject(DEFAULT_PALETTE);
        SelectObject(hMemDC, hObj);
        SelectObject(hCopyDC, hObj);
    }

	ReleaseDC(NULL, hDC);
    return TRUE;
}
Ejemplo n.º 13
0
INT
Test_NtUserSelectPalette(PTESTINFO pti)
{
	HPALETTE hPal, hOldPal;
	HWND hWnd;
	HDC hDC, hCompDC;
	struct
	{
		LOGPALETTE logpal;
		PALETTEENTRY entry[20];
	} pal;

	ZeroMemory(&pal, sizeof(pal));

	pal.logpal.palVersion = 0x300;
	pal.logpal.palNumEntries = 6;
	pal.entry[0] = PALENTRY(0,0,0);
	pal.entry[1] = PALENTRY(255,255,255);
	pal.entry[2] = PALENTRY(128,128,128);
	pal.entry[3] = PALENTRY(128,0,0);
	pal.entry[4] = PALENTRY(0,128,0);
	pal.entry[5] = PALENTRY(0,0,128);

	hPal = CreatePalette(&pal.logpal);
	ASSERT(hPal);
	TEST(DeletePalette(hPal) == 1);
	hPal = CreatePalette(&pal.logpal);
	ASSERT(hPal);

	/* Create a window */
	hWnd = CreateWindowW(L"BUTTON", L"TestWindow", WS_OVERLAPPEDWINDOW | WS_VISIBLE,
	                    CW_USEDEFAULT, CW_USEDEFAULT, 100, 100,
	                    NULL, NULL, g_hInstance, 0);
	hDC = GetDC(hWnd);
	ASSERT(hDC);
	hCompDC = CreateCompatibleDC(hDC);
	ASSERT(hCompDC);

	/* Test NULL DC */
	SetLastError(ERROR_SUCCESS);
	hOldPal = NtUserSelectPalette(NULL, hPal, 0);
	TEST(hOldPal == 0);
	TEST(GetLastError() == ERROR_SUCCESS);

	/* Test invalid DC */
	SetLastError(ERROR_SUCCESS);
	hOldPal = NtUserSelectPalette((HDC)-1, hPal, 0);
	TEST(hOldPal == 0);
	TEST(GetLastError() == ERROR_SUCCESS);

	/* Test NULL palette */
	SetLastError(ERROR_SUCCESS);
	hOldPal = NtUserSelectPalette(hDC, NULL, 0);
	TEST(hOldPal == 0);
	TEST(GetLastError() == ERROR_SUCCESS);

	/* Test invalid palette */
	SetLastError(ERROR_SUCCESS);
	hOldPal = NtUserSelectPalette(hDC, (HPALETTE)-1, 0);
	TEST(hOldPal == 0);
	TEST(GetLastError() == ERROR_SUCCESS);

	/* Test valid palette */
	hOldPal = NtUserSelectPalette(hDC, hPal, 0);
	TEST(hOldPal != 0);
	TEST(hOldPal == GetStockObject(DEFAULT_PALETTE));

	/* We cannot Delete the palette */
	TEST(DeletePalette(hPal) == 0);

	/* We can still select the Palette into a compatible DC */
	hOldPal = NtUserSelectPalette(hCompDC, hPal, 0);
	TEST(hOldPal != 0);



#if 0
	RealizePalette(hDC);

	GetClientRect(hWnd, &rect);
	FillRect(hDC, &rect, GetSysColorBrush(COLOR_BTNSHADOW));

	TEST(GetNearestColor(hDC, RGB(0,0,0)) == RGB(0,0,0));
	TEST(GetNearestColor(hDC, RGB(0,0,1)) == RGB(0,0,1));

	ReleaseDC(hWnd, hDC);
	DestroyWindow(hWnd);
	RECT rect;
	HBITMAP hBmp;


	BITMAPINFOHEADER bmih = {sizeof(BITMAPINFOHEADER), // biSize
	                         3, // biWidth
	                         3, // biHeight
	                         1, // biPlanes
	                         8, // biBitCount
	                         BI_RGB, // biCompression
	                         0, // biSizeImage
	                         92, // biXPelsPerMeter
	                         92, // biYPelsPerMeter
	                         6,  // biClrUsed
	                         6}; // biClrImportant
	BYTE bits[3][3] = {{0,1,2},{3,4,5},{6,1,2}};

	struct
	{
		BITMAPINFOHEADER bmih;
		RGBQUAD colors[6];
	} bmi = {{sizeof(BITMAPINFOHEADER),3,3,1,8,BI_RGB,0,92,92,6,6},
	                  {{0,0,0,0},{255,255,255,0},{255,0,0,0},
	                   {0,255,0,0},{0,0,255,0},{128,128,128,0}}};

	hBmp = CreateDIBitmap(hCompDC, &bmih, CBM_INIT, &bits, (BITMAPINFO*)&bmi, DIB_RGB_COLORS);
	ASSERT(hBmp);

	SetLastError(0);
	TEST(NtGdiSelectBitmap(hCompDC, hBmp));
	hOldPal = NtUserSelectPalette(hCompDC, hPal, 0);
	TEST(hOldPal != NULL);
	RealizePalette(hCompDC);

	TEST(GetNearestColor(hCompDC, RGB(0,0,0)) == RGB(0,0,0));
	TEST(GetNearestColor(hCompDC, RGB(0,0,1)) == RGB(0,0,0));
	TEST(GetNearestColor(hCompDC, RGB(100,0,0)) == RGB(0,0,0));
	TEST(GetNearestColor(hCompDC, RGB(250,250,250)) == RGB(255,255,255));
	TEST(GetNearestColor(hCompDC, RGB(120,100,110)) == RGB(128,128,128));

printf("nearest = 0x%x\n", GetNearestColor(hCompDC, RGB(120,100,110)));
#endif


	return APISTATUS_NORMAL;
}
Ejemplo n.º 14
0
static BOOL CALLBACK 
sSplashDlgProc (
		HWND	hDlg, 
		UINT	uMsg, 
		WPARAM	wParam, 
		LPARAM	lParam) 
{
	PSPLASHSTRUCT	pss;

	switch (uMsg) {

	case WM_INITDIALOG:
		{
			HWND hWndControl;

			SetWindowLong (hDlg, GWL_USERDATA, lParam);
			pss = (PSPLASHSTRUCT)lParam;

			g_hWndSplash = hDlg;
			SetWindowPos (hDlg, HWND_TOP, pss->uXpos, pss->uYpos, 
											pss->uXsize, pss->uYsize, 0);

			hWndControl = GetDlgItem (hDlg, IDOK);
			EnableWindow (hWndControl, FALSE);
			ShowWindow (hWndControl, SW_HIDE);
			hWndControl = GetDlgItem (hDlg, IDC_BUYNOW);
			EnableWindow (hWndControl, FALSE);
			ShowWindow (hWndControl, SW_HIDE);
			pss->uTimerTime = 0;
			SetTimer (hDlg, TIMER_ID, TIMER_PERIOD, NULL);
		}
		return TRUE;

	case WM_PAINT:
		{
			HDC			hDC, hMemDC;
			PAINTSTRUCT ps;
			HBITMAP		hBitmapOld;

			pss = (PSPLASHSTRUCT)GetWindowLong (hDlg, GWL_USERDATA);

			hDC = BeginPaint (hDlg, &ps);
			hMemDC = CreateCompatibleDC (hDC);
			if (pss->hPaletteSplash) {
				SelectPalette (hDC, pss->hPaletteSplash, FALSE);
				RealizePalette (hDC);
			}
			hBitmapOld = SelectObject (hMemDC, pss->hBitmapSplash);
			CLPaintUserInfo (MemMgr, hDlg, hMemDC, NULL);
			BitBlt (hDC, 0, 0, pss->uXsize, pss->uYsize, 
											hMemDC, 0, 0, SRCCOPY);
			SelectObject (hMemDC, hBitmapOld);
			DeleteDC (hMemDC);
			EndPaint (hDlg, &ps);
		}
		return FALSE;

	case WM_LBUTTONDOWN:
		if (hWndSplashParent) EndDialog (hDlg, 0);
		return TRUE;

	case WM_DESTROY:
		KillTimer (hDlg, TIMER_ID);
		return FALSE;

	case WM_TIMER:
		pss = (PSPLASHSTRUCT)GetWindowLong (hDlg, GWL_USERDATA);
		if (pss->uTimerTime < pss->uTimeOut) 
			pss->uTimerTime += TIMER_PERIOD;
		else 
			if (hWndSplashParent) EndDialog (hDlg, 0);
		return TRUE;

	case WM_CLOSE :
		EndDialog (hDlg, 0);
		break;

	case WM_COMMAND :
		switch(LOWORD (wParam)) {

		case IDOK: 
			if (hWndSplashParent) EndDialog (hDlg, 0);
			break;
		}
		return TRUE;

	default:
		return FALSE;

	}

	return FALSE;
}
Ejemplo n.º 15
0
void
SetupContext(void)
    {
    PIXELFORMATDESCRIPTOR pfd;     /* Pixel format information */
    LOGPALETTE            *pPal;   /* Pointer to logical palette */
    int                   nColors; /* Number of entries in palette */
    int                   ind,     /* Color index */
                          rmax,    /* Maximum red value */
                          gmax,    /* Maximum green value */
                          bmax;    /* Maximum blue value */


    /* Choose a pixel format... */
    memset(&pfd, 0, sizeof(pfd));
    pfd.nSize        = sizeof(pfd);
    pfd.nVersion     = 1;
    pfd.dwFlags      = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL;
    pfd.iPixelType   = PFD_TYPE_RGBA;	/* RGB color buffer */
    pfd.cDepthBits   = 16;		/* Need a depth buffer */

    Format = ChoosePixelFormat(DC, &pfd);
    if (!Format)
      exit(1);

    DescribePixelFormat(DC, Format, sizeof(PIXELFORMATDESCRIPTOR), &pfd);
    SetPixelFormat(DC, Format, &pfd);

    /* Create the OpenGL rendering context... */
    RC = wglCreateContext(DC);
    wglMakeCurrent(DC, RC);

    /* Find out if we need to define a color palette... */
    if (!(pfd.dwFlags & PFD_NEED_PALETTE))
        {
        Palette = NULL;
        return;
        }

    /* Allocate memory for a color palette... */
    nColors = 1 << pfd.cColorBits;	

    pPal = (LOGPALETTE *)malloc(sizeof(LOGPALETTE) +
                                nColors * sizeof(PALETTEENTRY));

    pPal->palVersion    = 0x300;
    pPal->palNumEntries = nColors;

    /*
     * Get the maximum values for red, green, and blue.  Then build 'nColors'
     * colors...
     */

    rmax = (1 << pfd.cRedBits) - 1;
    gmax = (1 << pfd.cGreenBits) - 1;
    bmax = (1 << pfd.cBlueBits) - 1;

    for (ind = 0; ind < nColors; ind ++)
        {
        pPal->palPalEntry[ind].peRed   = 255 * ((ind >> pfd.cRedShift) & rmax) / rmax;
        pPal->palPalEntry[ind].peGreen = 255 * ((ind >> pfd.cGreenShift) & gmax) / gmax;
        pPal->palPalEntry[ind].peBlue  = 255 * ((ind >> pfd.cBlueShift) & bmax) / bmax;
        pPal->palPalEntry[ind].peFlags = 0;
        }

    /* Create, select, and realize the palette... */
    Palette = CreatePalette(pPal);
    SelectPalette(DC, Palette, FALSE);
    RealizePalette(DC);

    free(pPal);
}
Ejemplo n.º 16
0
int GPcreatewidget (
    Gwidget_t *parent, Gwidget_t *widget, int attrn, Gwattr_t *attrp
) {
    PIXpoint_t po;
    PIXsize_t ps;
    PRINTDLG pd;
    DOCINFO di;
    DEVMODE *dmp;
    /* the 2 here is to provide enough space for palPalEntry[0] and [1] */
    LOGPALETTE pal[2];

    HBRUSH brush;
    HPEN pen;
    HBITMAP bmap;
    char *s, *s1;
    int color, lflag, ai, dpix, dpiy, i;

    s = Gpscanvasname;
    lflag = FALSE;
    po.x = po.y = 0;
    ps.x = ps.y = MINPWSIZE;
    for (ai = 0; ai < attrn; ai++) {
        switch (attrp[ai].id) {
        case G_ATTRORIGIN:
            GETORIGIN (attrp[ai].u.p, po);
            break;
        case G_ATTRSIZE:
            GETSIZE (attrp[ai].u.s, ps, MINPWSIZE);
            break;
        case G_ATTRNAME:
            if (attrp[ai].u.t && attrp[ai].u.t[0])
                s = attrp[ai].u.t;
            break;
        case G_ATTRMODE:
            if (strcmp ("landscape", attrp[ai].u.t) == 0)
                lflag = TRUE;
            else if (strcmp ("portrait", attrp[ai].u.t) == 0)
                lflag = FALSE;
            else {
                Gerr (POS, G_ERRBADATTRVALUE, attrp[ai].u.t);
                return -1;
            }
            break;
        case G_ATTRCOLOR:
            /* will do it after the widget is created */
            break;
        case G_ATTRVIEWPORT:
            /* will do it after the widget is created */
            break;
        case G_ATTRWINDOW:
            /* will do it after the widget is created */
            break;
        case G_ATTRWINDOWID:
            Gerr (POS, G_ERRCANNOTSETATTR1, "windowid");
            return -1;
        case G_ATTRUSERDATA:
            widget->udata = attrp[ai].u.u;
            break;
        default:
            Gerr (POS, G_ERRBADATTRID, attrp[ai].id);
            return -1;
        }
    }
    s1 = s + strlen (s) - 3;
    if (s1 > s && strncmp (s1, "emf", 3) == 0) {
        WPU->mode = 1;
        ps.x *= 8.235, ps.y *= 8.235;
        if (!(GC = CreateEnhMetaFile (NULL, s, NULL, "LEFTY\\0GRAPH\\0\\0"))) {
            Gerr (POS, G_ERRCANNOTCREATEWIDGET);
            return -1;
        }
    } else { /* open the printer device */
        WPU->mode = 2;
        di.cbSize = sizeof (DOCINFO);
        di.lpszDocName = NULL;
        di.lpszOutput = NULL;
        di.lpszDatatype = "LEFTY";
        di.fwType = 0;
        pd.lStructSize = sizeof (pd);
        pd.hwndOwner = NULL;
        pd.hDevMode = NULL;
        pd.hDevNames = NULL;
        pd.hDC = NULL;
        pd.Flags = PD_RETURNDC | PD_RETURNDEFAULT;
        pd.nFromPage = 0;
        pd.nToPage = 0;
        pd.nMinPage = 0;
        pd.nMaxPage = 0;
        pd.nCopies = 1;
        pd.hInstance = NULL;
        pd.lCustData = NULL;
        pd.lpfnPrintHook = NULL;
        pd.lpfnSetupHook = NULL;
        pd.lpPrintTemplateName = NULL;
        pd.lpSetupTemplateName = NULL;
        pd.hPrintTemplate = NULL;
        pd.hSetupTemplate = NULL;
        if (!PrintDlg (&pd)) {
            Gerr (POS, G_ERRCANNOTCREATEWIDGET);
            return -1;
        }
        if (lflag && pd.hDevMode) {
            dmp = (DEVMODE *) GlobalLock (pd.hDevMode);
            dmp->dmOrientation = DMORIENT_LANDSCAPE;
            GlobalUnlock (pd.hDevMode);
            pd.Flags = PD_RETURNDC;
            if (!PrintDlg (&pd)) {
                Gerr (POS, G_ERRCANNOTCREATEWIDGET);
                return -1;
            }
        }
        GC = pd.hDC;
        dpix = GetDeviceCaps (GC, LOGPIXELSX);
        if (dpix != 300)
            ps.x = ps.x * (double) dpix / 300.0;
        dpiy = GetDeviceCaps (GC, LOGPIXELSY);
        if (dpiy != 300)
            ps.y = ps.y * (double) dpiy / 300.0;
        if (StartDoc (GC, &di) <= 0 || StartPage (GC) <= 0) {
            Gerr (POS, G_ERRCANNOTCREATEWIDGET);
            return -1;
        }
    }
    WPU->wrect.o.x = 0.0, WPU->wrect.o.y = 0.0;
    WPU->wrect.c.x = 1.0, WPU->wrect.c.y = 1.0;
    WPU->vsize.x = ps.x, WPU->vsize.y = ps.y;
    WPU->ncolor = 2;
    pal[0].palVersion = 0x300; /* HA HA HA */
    pal[0].palNumEntries = 2;
    pal[0].palPalEntry[0].peRed = 255;
    pal[0].palPalEntry[0].peGreen = 255;
    pal[0].palPalEntry[0].peBlue = 255;
    pal[0].palPalEntry[0].peFlags = 0;
    pal[0].palPalEntry[1].peRed = 0;
    pal[0].palPalEntry[1].peGreen = 0;
    pal[0].palPalEntry[1].peBlue = 0;
    pal[0].palPalEntry[1].peFlags = 0;
    WPU->cmap = CreatePalette (&pal[0]);
    WPU->colors[0].color = pal[0].palPalEntry[0];
    for (i = 1; i < G_MAXCOLORS; i++)
        WPU->colors[i].color = pal[0].palPalEntry[1];
    SelectPalette (GC, WPU->cmap, FALSE);
    RealizePalette (GC);
    WPU->colors[0].inuse = TRUE;
    WPU->colors[1].inuse = TRUE;
    for (i = 2; i < G_MAXCOLORS; i++)
        WPU->colors[i].inuse = FALSE;
    WPU->gattr.color = 1;
    brush = CreateSolidBrush (PALETTEINDEX (1));
    SelectObject (GC, brush);
    pen = CreatePen (PS_SOLID, 1, PALETTEINDEX (1));
    SelectObject (GC, pen);
    SetTextColor (GC, PALETTEINDEX (1));
    SetBkMode (GC, TRANSPARENT);
    WPU->gattr.width = 0;
    WPU->gattr.mode = G_SRC;
    WPU->gattr.fill = 0;
    WPU->gattr.style = 0;
    WPU->defgattr = WPU->gattr;
    WPU->font = NULL;
    if (Gdepth == 1) {
        for (i = 0; i < 17; i++) {
            if (!(bmap = CreateBitmap (4, 4, 1, 1, &grays[i][0])))
                continue;
            WPU->grays[i] = CreatePatternBrush (bmap);
        }
    }
    for (ai = 0; ai < attrn; ai++) {
        switch (attrp[ai].id) {
        case G_ATTRCOLOR:
            color = attrp[ai].u.c.index;
            if (color < 0 || color > G_MAXCOLORS) {
                Gerr (POS, G_ERRBADCOLORINDEX, color);
                return -1;
            }
            WPU->colors[color].color.peRed = attrp[ai].u.c.r;
            WPU->colors[color].color.peGreen = attrp[ai].u.c.g;
            WPU->colors[color].color.peBlue = attrp[ai].u.c.b;
            WPU->colors[color].color.peFlags = 0;
            if (color >= WPU->ncolor)
                ResizePalette (WPU->cmap, color + 1), WPU->ncolor = color + 1;
            SetPaletteEntries (
                WPU->cmap, (int) color, 1, &WPU->colors[color].color
            );
            RealizePalette (GC);
            WPU->colors[color].inuse = TRUE;
            if (color == WPU->gattr.color)
                WPU->gattr.color = -1;
            break;
        case G_ATTRVIEWPORT:
            if (attrp[ai].u.s.x == 0)
                attrp[ai].u.s.x = 1;
            if (attrp[ai].u.s.y == 0)
                attrp[ai].u.s.y = 1;
            WPU->vsize.x = attrp[ai].u.s.x + 0.5;
            WPU->vsize.y = attrp[ai].u.s.y + 0.5;
            SetWindowPos (
                widget->w, (HWND) NULL, 0, 0, WPU->vsize.x,
                WPU->vsize.y, SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOMOVE
            );
            break;
        case G_ATTRWINDOW:
            if (attrp[ai].u.r.o.x == attrp[ai].u.r.c.x)
                attrp[ai].u.r.c.x = attrp[ai].u.r.o.x + 1;
            if (attrp[ai].u.r.o.y == attrp[ai].u.r.c.y)
                attrp[ai].u.r.c.y = attrp[ai].u.r.o.y + 1;
            WPU->wrect = attrp[ai].u.r;
            break;
        }
    }
    return 0;
}
Ejemplo n.º 17
0
LRESULT CALLBACK CanvasWndProc (
    HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam
) {
    Gwidget_t *widget;
    WINDOWPOS *wpos;
    PIXpoint_t pp;
    Gevent_t gev;
    POINT p;
    int wi, bn;

    static int cntlflag;

    if (Gnocallbacks || !(widget = findwidget (hwnd, G_CANVASWIDGET)))
        return (DefWindowProc(hwnd, message, wparam, lparam));
    Gpopdownflag = FALSE;
    switch (message) {
    case WM_PAINT:
        if (palettechanged != hwnd)
            RealizePalette (widget->u.c->gc);
        Gneedredraw = widget->u.c->needredraw = TRUE;
        Gadjustclip (widget);
        return (DefWindowProc(hwnd, message, wparam, lparam));
    case WM_WINDOWPOSCHANGED:
        wpos = (WINDOWPOS *) lparam;
        if (!(wpos->flags & SWP_NOSIZE))
            handleresize (widget);
        return 0;
    case WM_MOUSEACTIVATE:
        SetFocus (widget->w);
        return (DefWindowProc(hwnd, message, wparam, lparam));
    case WM_COMMAND:
        processcommand (widget, wparam, lparam);
        return 0;
    case WM_CHAR:
        gev.type = G_KEYBD;
        gev.code = G_DOWN;   /* I don't know how to get up events so I make */
        Gpopdownflag = TRUE; /* the code after this switch send the up event */
        gev.data = wparam;
        GetCursorPos (&p);
        ScreenToClient (widget->w, &p);
        pp.x = p.x, pp.y = p.y;
        gev.p = ppixtodraw (widget, pp);
        /* continues after the end of this switch */
        break;
    case WM_LBUTTONDOWN:
    case WM_LBUTTONUP:
    case WM_MBUTTONDOWN:
    case WM_MBUTTONUP:
    case WM_RBUTTONDOWN:
    case WM_RBUTTONUP:
        gev.type = G_MOUSE;
        if (twobmouse) {
            if (message == WM_LBUTTONDOWN && (wparam & MK_CONTROL))
                message = WM_MBUTTONDOWN, cntlflag = TRUE;
            if (message == WM_LBUTTONUP && cntlflag)
                message = WM_MBUTTONUP, cntlflag = FALSE;
        }
        switch (message) {
        case WM_LBUTTONDOWN: gev.code = G_DOWN, gev.data = G_LEFT;   break;
        case WM_LBUTTONUP:   gev.code = G_UP,   gev.data = G_LEFT;   break;
        case WM_MBUTTONDOWN: gev.code = G_DOWN, gev.data = G_MIDDLE; break;
        case WM_MBUTTONUP:   gev.code = G_UP,   gev.data = G_MIDDLE; break;
        case WM_RBUTTONDOWN: gev.code = G_DOWN, gev.data = G_RIGHT;  break;
        case WM_RBUTTONUP:   gev.code = G_UP,   gev.data = G_RIGHT;  break;
        }
        pp.x = LOWORD (lparam), pp.y = HIWORD (lparam);
        gev.p = ppixtodraw (widget, pp);
        bn = WCU->bstate[gev.data];
        WCU->bstate[gev.data] = (gev.code == G_DOWN) ? 1 : 0;
        bn = WCU->bstate[gev.data] - bn;
        widget->u.c->buttonsdown += bn;
        Gbuttonsdown += bn;
        /* continues after the end of this switch */
        break;
    default:
        return (DefWindowProc(hwnd, message, wparam, lparam));
    }
    wi = gev.wi = widget - &Gwidgets[0];
    if (widget->u.c->func)
        (*widget->u.c->func) (&gev);
    if (Gpopdownflag) {
        Gpopdownflag = FALSE;
        if (gev.code == G_DOWN) {
            gev.code = G_UP;
            widget = &Gwidgets[wi];
            WCU->bstate[gev.data] = 0;
            widget->u.c->buttonsdown--;
            Gbuttonsdown--;
            if (widget->inuse && widget->u.c->func)
                (*widget->u.c->func) (&gev);
        }
    }
    return 0;
}
Ejemplo n.º 18
0
Archivo: qa.c Proyecto: mingpen/OpenNT
/*----------------------------------------------------------------------------*\
|   AppWndProc( hwnd, uiMessage, wParam, lParam )                              |
|                                                                              |
|   Description:                                                               |
|       The window proc for the app's main (tiled) window.  This processes all |
|       of the parent window's messages.                                       |
|                                                                              |
\*----------------------------------------------------------------------------*/
LONG FAR PASCAL _export AppWndProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam)
{
    PAINTSTRUCT ps;
    HDC hdc;
    BOOL f;
  
    switch (msg)
    {
        case WM_CREATE:
            hwndA = CreateWindowEx(WS_EX_CLIENTEDGE,ANIMATE_CLASS, NULL,
//              ACS_CENTER |
                ACS_TRANSPARENT |
                WS_VISIBLE | WS_CHILD | WS_BORDER,
                10, 10, 500, 200, hwnd, (HMENU)42, hInstApp, NULL);
	    break;

	case WM_SIZE:
            //if (hwndC = GetWindow(hwnd, GW_CHILD))
            //    MoveWindow(hwndC, 0, 0, LOWORD(lParam), HIWORD(lParam), TRUE);
	    break;

        case WM_ACTIVATEAPP:
	    fAppActive = (BOOL)wParam;
            break;

        case WM_TIMER:
            break;

        case WM_ERASEBKGND:
            break;

        case WM_INITMENU:
	    EnableMenuSz((HMENU)wParam, TEXT("Edit.Paste"), IsClipboardFormatAvailable(CF_TEXT));
            break;

        case WM_COMMAND:
            //
            //  the animate control will notify us when play start or stops.
            //
            if (LOWORD(wParam) == 42)
            {
                if (GET_WM_COMMAND_CMD(wParam, lParam) == ACN_STOP)
                    AppSetText(TEXT("(stopped)"));
                else if (GET_WM_COMMAND_CMD(wParam, lParam) == ACN_START)
                    AppSetText(TEXT("(playing)"));
                else
                    AppSetText(NULL);
            }
            return HandleCommand(hwnd,msg,wParam,lParam);

	case WM_DESTROY:
	    hAccelApp = NULL;
            PostQuitMessage(0);
	    break;

        case WM_CLOSE:
	    break;

        case WM_PALETTECHANGED:
	    if ((HWND)wParam == hwnd)
		break;

	    // fall through to WM_QUERYNEWPALETTE

	case WM_QUERYNEWPALETTE:
	    hdc = GetDC(hwnd);

	    if (hpalApp)
		SelectPalette(hdc, hpalApp, FALSE);

	    f = RealizePalette(hdc);
	    ReleaseDC(hwnd,hdc);

	    if (f)
		InvalidateRect(hwnd,NULL,TRUE);

	    return f;

        case WM_PAINT:
	    hdc = BeginPaint(hwnd,&ps);
	    AppPaint (hwnd,hdc);
            EndPaint(hwnd,&ps);
            return 0L;
    }
    return DefWindowProc(hwnd,msg,wParam,lParam);
}
Ejemplo n.º 19
0
BOOL CDDB::ConstructDDB(					// construct a DDB from the DIB data
	LPBITMAPINFOHEADER lpHeader,			// pointer to BITMAPINFOHEADER structure
	HDC hDC,										// device context to use for call to CreateDIBitmap()
	BOOL fUseDIBPalette,						// flag indicating if DIB bitmap should be used for conversion
	HPALETTE hPalette /*=NULL*/)			// Palette to use
{
	/*
	// Build a palette containing the DIB color table. For 24 bit dibs, a default
	// 256 entry palette is built (RGB)=(8*8*4).
	*/

	if ((m_hPalette = hPalette) == NULL)
	{
		UINT wNumberOfPaletteEntries;

		if ((wNumberOfPaletteEntries = PaletteEntryCount(lpHeader)) == 0)
		{
			if (lpHeader->biBitCount == 24)
			{
				wNumberOfPaletteEntries = 256;
			}
		}
									
		if (wNumberOfPaletteEntries > 0)
		{
			LOGPALETTE FAR *lpPalette;
								
			if ((lpPalette = (LOGPALETTE FAR *)new far char[sizeof(LOGPALETTE)+wNumberOfPaletteEntries*sizeof(PALETTEENTRY)]) != NULL)
			{
				lpPalette->palNumEntries = (WORD)wNumberOfPaletteEntries;
				lpPalette->palVersion    = 0x0300;
					
				if (lpHeader->biBitCount != 24)
				{
					RGBQUAD FAR *lpRGB;
									
					lpRGB = (RGBQUAD FAR *)(((LPBYTE)lpHeader)+(WORD)(lpHeader->biSize));
											
					UINT i;
												
					for (i = 0; i < wNumberOfPaletteEntries; i++)
					{
						lpPalette->palPalEntry[i].peRed   = lpRGB[i].rgbRed;
						lpPalette->palPalEntry[i].peGreen = lpRGB[i].rgbGreen;
						lpPalette->palPalEntry[i].peBlue  = lpRGB[i].rgbBlue;
						lpPalette->palPalEntry[i].peFlags = (BYTE)0;
					}
				}
											
				else
				{
					BYTE Red = 0;
					BYTE Green = 0;
					BYTE Blue = 0;
												
					UINT i;
												
					for (i = 0; i < wNumberOfPaletteEntries; i++)
					{
						lpPalette->palPalEntry[i].peRed   = Red;
						lpPalette->palPalEntry[i].peGreen = Green;
						lpPalette->palPalEntry[i].peBlue  = Blue;
						lpPalette->palPalEntry[i].peFlags = (BYTE)0;
													
						if ((Red += 32) == 0)
						{
							if ((Green += 32) == 0)
							{
								Blue += 64;
							}
						}
					}
				}
					
				m_hPalette = CreatePalette(lpPalette);
											
				delete [] lpPalette;
				lpPalette = NULL;
			}
		}
	}

	/*
	// If the palette was successfully created, then go ahead and create the DDB.
	*/

	if (m_hPalette != NULL)
	{
		/*
		// If the user wants to use the DIB palette to convert the DIB to a DDB, then select it now.
		*/

		HPALETTE hOldPalette = NULL;
									
		if (fUseDIBPalette)
		{
			/*
			// Note: The DIB palette is selected as a background palette. This should
			// make the DIB->DDB conversion work without affecting the system colors.
			*/
			
			if ((hOldPalette = SelectPalette(hDC, m_hPalette, TRUE)) != NULL)
			{
				RealizePalette(hDC);
			}
		}
		
		if ((!fUseDIBPalette) || (hOldPalette != NULL))
		{
			/*
			// Create the DDB.
			*/
			
			m_hBitmap = CreateDIBitmap(
								hDC,
								lpHeader,
								CBM_INIT,
								((LPBYTE)lpHeader)+((UINT)lpHeader->biSize)+(PaletteEntryCount(lpHeader)*sizeof(RGBQUAD)),
								(LPBITMAPINFO)lpHeader,
								DIB_RGB_COLORS);
																	
		}
		
		if (hOldPalette != NULL)
		{
			SelectPalette(hDC, hOldPalette, FALSE);
		}
	}

	return IsValid();
}
Ejemplo n.º 20
0
//VC下把HBITMAP保存为bmp图片   
BOOL  SaveBmp(HBITMAP     hBitmap, CString     FileName)
{
	HDC     hDC;
	//当前分辨率下每象素所占字节数         
	int     iBits;
	//位图中每象素所占字节数         
	WORD     wBitCount;
	//定义调色板大小,     位图中像素字节大小     ,位图文件大小     ,     写入文件字节数             
	DWORD     dwPaletteSize = 0, dwBmBitsSize = 0, dwDIBSize = 0, dwWritten = 0;
	//位图属性结构             
	BITMAP     Bitmap;
	//位图文件头结构         
	BITMAPFILEHEADER     bmfHdr;
	//位图信息头结构             
	BITMAPINFOHEADER     bi;
	//指向位图信息头结构                 
	LPBITMAPINFOHEADER     lpbi;
	//定义文件,分配内存句柄,调色板句柄             
	HANDLE     fh, hDib, hPal, hOldPal = NULL;

	//计算位图文件每个像素所占字节数             
	hDC = CreateDC(L"DISPLAY", NULL, NULL, NULL);
	iBits = GetDeviceCaps(hDC, BITSPIXEL)     *     GetDeviceCaps(hDC, PLANES);
	DeleteDC(hDC);
	if (iBits <= 1)
		wBitCount = 1;
	else  if (iBits <= 4)
		wBitCount = 4;
	else if (iBits <= 8)
		wBitCount = 8;
	else
		wBitCount = 24;

	GetObject(hBitmap, sizeof(Bitmap), (LPSTR)&Bitmap);
	bi.biSize = sizeof(BITMAPINFOHEADER);
	bi.biWidth = Bitmap.bmWidth;
	bi.biHeight = Bitmap.bmHeight;
	bi.biPlanes = 1;
	bi.biBitCount = wBitCount;
	bi.biCompression = BI_RGB;
	bi.biSizeImage = 0;
	bi.biXPelsPerMeter = 0;
	bi.biYPelsPerMeter = 0;
	bi.biClrImportant = 0;
	bi.biClrUsed = 0;

	dwBmBitsSize = ((Bitmap.bmWidth *wBitCount + 31) / 32) * 4 * Bitmap.bmHeight;

	//为位图内容分配内存             
	hDib = GlobalAlloc(GHND, dwBmBitsSize + dwPaletteSize + sizeof(BITMAPINFOHEADER));
	lpbi = (LPBITMAPINFOHEADER)GlobalLock(hDib);
	*lpbi = bi;

	//     处理调色板                 
	hPal = GetStockObject(DEFAULT_PALETTE);
	if (hPal)
	{
		hDC = ::GetDC(NULL);
		hOldPal = ::SelectPalette(hDC, (HPALETTE)hPal, FALSE);
		RealizePalette(hDC);
	}

	//     获取该调色板下新的像素值             
	GetDIBits(hDC, hBitmap, 0, (UINT)Bitmap.bmHeight,
		(LPSTR)lpbi + sizeof(BITMAPINFOHEADER) + dwPaletteSize,
		(BITMAPINFO *)lpbi, DIB_RGB_COLORS);

	//恢复调色板                 
	if (hOldPal)
	{
		::SelectPalette(hDC, (HPALETTE)hOldPal, TRUE);
		RealizePalette(hDC);
		::ReleaseDC(NULL, hDC);
	}


	//创建位图文件                 
	fh = CreateFile(FileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
		FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL);

	if (fh == INVALID_HANDLE_VALUE)         return     FALSE;

	//     设置位图文件头             
	bmfHdr.bfType = 0x4D42;     //     "BM"             
	dwDIBSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + dwPaletteSize + dwBmBitsSize;
	bmfHdr.bfSize = dwDIBSize;
	bmfHdr.bfReserved1 = 0;
	bmfHdr.bfReserved2 = 0;
	bmfHdr.bfOffBits = (DWORD)sizeof(BITMAPFILEHEADER) + (DWORD)sizeof(BITMAPINFOHEADER) + dwPaletteSize;
	//     写入位图文件头             
	WriteFile(fh, (LPSTR)&bmfHdr, sizeof(BITMAPFILEHEADER), &dwWritten, NULL);
	//     写入位图文件其余内容             
	WriteFile(fh, (LPSTR)lpbi, dwDIBSize, &dwWritten, NULL);
	//清除                 
	GlobalUnlock(hDib);
	GlobalFree(hDib);
	CloseHandle(fh);

	return     TRUE;
}
Ejemplo n.º 21
0
HDIB FAR ChangeBitmapFormat(HBITMAP  hBitmap,
            WORD     wBitCount,
            DWORD    dwCompression,
            HPALETTE hPal)
{
   HDC                hDC;          // Screen DC
   HDIB               hNewDIB=NULL; // Handle to new DIB
   BITMAP             Bitmap;       // BITMAP data structure
   BITMAPINFOHEADER   bi;           // Bitmap info. header
   LPBITMAPINFOHEADER lpbi;         // Pointer to bitmap header
   HPALETTE           hOldPal=NULL; // Handle to palette
   WORD               NewBPP;       // New bits per pixel
   DWORD              NewComp;      // New compression format

   /* Check for a valid bitmap handle */
   if (!hBitmap)
      return NULL;

   /* Validate wBitCount and dwCompression
    * They must match correctly (i.e., BI_RLE4 and 4 BPP or
    * BI_RLE8 and 8BPP, etc.) or we return failure
    */
   if (wBitCount == 0)
      {
      NewComp = dwCompression;
      if (NewComp == BI_RLE4)
     NewBPP = 4;
      else if (NewComp == BI_RLE8)
     NewBPP = 8;
      else /* Not enough info */
     return NULL;
      }
   else if (wBitCount == 1 && dwCompression == BI_RGB)
      {
      NewBPP = wBitCount;
      NewComp = BI_RGB;
      }
   else if (wBitCount == 4)
      {
      NewBPP = wBitCount;
      if (dwCompression == BI_RGB || dwCompression == BI_RLE4)
         NewComp = dwCompression;
      else
         return NULL;
      }
   else if (wBitCount == 8)
      {
      NewBPP = wBitCount;
      if (dwCompression == BI_RGB || dwCompression == BI_RLE8)
         NewComp = dwCompression;
      else
         return NULL;
      }
   else if (wBitCount == 24 && dwCompression == BI_RGB)
      {
      NewBPP = wBitCount;
      NewComp = BI_RGB;
      }
   else
      return NULL;

   /* Get info about the bitmap */
   GetObject(hBitmap, sizeof(BITMAP), (LPSTR)&Bitmap);

   /* Fill in the BITMAPINFOHEADER appropriately */
   bi.biSize               = sizeof(BITMAPINFOHEADER);
   bi.biWidth              = Bitmap.bmWidth;
   bi.biHeight             = Bitmap.bmHeight;
   bi.biPlanes             = 1;
   bi.biBitCount           = NewBPP;
   bi.biCompression        = NewComp;
   bi.biSizeImage          = 0;
   bi.biXPelsPerMeter      = 0;
   bi.biYPelsPerMeter      = 0;
   bi.biClrUsed            = 0;
   bi.biClrImportant       = 0;

   /* Go allocate room for the new DIB */
   hNewDIB = AllocRoomForDIB(bi, hBitmap);
   if (!hNewDIB)
      return NULL;

   /* Get a pointer to the new DIB */
   lpbi = (VOID FAR *)GlobalLock(hNewDIB);

   /* If we have a palette, get a DC and select/realize it */
   if (hPal)
   {
      hDC  = GetDC(NULL);
      hOldPal = SelectPalette(hDC, hPal, FALSE);
      RealizePalette(hDC);
   }

   /* Call GetDIBits and get the new DIB bits */
   if (!GetDIBits(hDC, hBitmap, 0, (WORD) lpbi->biHeight,
       (LPSTR)lpbi + (WORD)lpbi->biSize + PaletteSize((LPSTR)lpbi),
       (LPBITMAPINFO)lpbi, DIB_RGB_COLORS))
      {
      GlobalUnlock(hNewDIB);
      GlobalFree(hNewDIB);
      hNewDIB = NULL;
      }

   /* Clean up and return */
   if (hOldPal)
   {
      SelectPalette(hDC, hOldPal, TRUE);
      RealizePalette(hDC);
      ReleaseDC(NULL, hDC);
   }

   if (hNewDIB)
      {
      /* Unlock the new DIB's memory block */
      GlobalUnlock(hNewDIB);
      }

   return hNewDIB;
}
Ejemplo n.º 22
0
static int	MyPaintSplash (HWND pmSplashWindow, BOOL pmDraw)
{
    SplashWindowInfoPtr	myInfo;
    HDC			myDisplayContext, myMemDC;
    PAINTSTRUCT		myPaintStruct;
    BITMAP		myBitmap;
    HBITMAP		myOldBitmap;
    HPALETTE		myPalette, myOldPalette;
    POINT		myPoint, myOrigin;
    int			myY;

    myInfo = MyGetSplashWindowInfo (pmSplashWindow);
        		
    myDisplayContext = BeginPaint (pmSplashWindow, &myPaintStruct);

    if (pmDraw && myInfo -> usePicture)
    {
    	myMemDC = CreateCompatibleDC (NULL);
    	myOldBitmap = SelectBitmap (myMemDC, myInfo -> picture);

    	GetObject (myInfo -> picture, sizeof(BITMAP), (LPSTR) &myBitmap);

    	myPoint.x = myBitmap.bmWidth;
    	myPoint.y = myBitmap.bmHeight;
    	DPtoLP (myDisplayContext, &myPoint, 1);

    	myOrigin.x = 0;
    	myOrigin.y = 0;
    	DPtoLP (myMemDC, &myOrigin, 1);
    	
    	//
    	// We need to perform all sorts of stuff to get the palette right...
    	//
   	// If the DIBSection is 256 color or less, it has a color table
   	if ((myBitmap.bmBitsPixel * myBitmap.bmPlanes) <= 8)
   	{
	   RGBQUAD      myClrTbl [256];
	   LPLOGPALETTE myLogPal;
	   WORD         cnt;

   	    // Get the DIBSection's color table
   	    GetDIBColorTable (myMemDC, 0, 256, myClrTbl);
   	    
	    // Create a palette from the color tabl
	    myLogPal = (LOGPALETTE *) malloc (sizeof(LOGPALETTE) + 
	    					(256 * sizeof(PALETTEENTRY)));
	    myLogPal -> palVersion = 0x300;
	    myLogPal -> palNumEntries = 256;
	    for (cnt = 0 ; cnt < 256 ; cnt++)
	    {
	 	myLogPal -> palPalEntry [cnt].peRed = myClrTbl [cnt].rgbRed;
		myLogPal -> palPalEntry [cnt].peGreen = myClrTbl [cnt].rgbGreen;
		myLogPal -> palPalEntry [cnt].peBlue = myClrTbl [cnt].rgbBlue;
		myLogPal -> palPalEntry [cnt].peFlags = 0;
	    }
   	    myPalette = CreatePalette (myLogPal);
	    free (myLogPal);
   	    
	    // Select Palette
	    myOldPalette = SelectPalette (myDisplayContext, myPalette, FALSE);
	    RealizePalette (myDisplayContext);
	}

	if (gProgram.isTuring)
	{
    	    BitBlt (myDisplayContext, 0, 0, myPoint.x, myPoint.y,
            	myMemDC, myOrigin.x, myOrigin.y, SRCCOPY);
	}
	else
	{
    	    BitBlt (myDisplayContext, MARGIN, 0, myPoint.x, myPoint.y,
            	myMemDC, myOrigin.x, myOrigin.y, SRCCOPY);
        }

	SelectObject (myMemDC, myOldBitmap);
   	if ((myBitmap.bmBitsPixel * myBitmap.bmPlanes) <= 8)
   	{
   	    SelectPalette (myDisplayContext, myOldPalette, FALSE);
   	    DeleteObject (myPalette);
   	}
    	DeleteDC (myMemDC);
    }

    // Place Ministry message over top of the Sun
    if (gProgram.assistedByIBM && gProgram.isTuring)
    {
    	//
    	// Output "Ministry of Education License Message"
    	//
    	myY = LARGE_GAP;
        MyDrawString (myInfo, myDisplayContext, myInfo -> versionFont,
    		      myInfo -> miniEdMsg [0], &myY, pmDraw, FALSE);
	myY += SMALL_GAP;
        MyDrawStrings (myInfo, myDisplayContext, myInfo -> chiefProgrammerFont,
    		  &myInfo -> miniEdMsg [1], 9, &myY, pmDraw, FALSE);
    } // if (gProgram.assistedByIBM)
       
    if (myInfo -> usePicture)
    {
    	// The starting Y position
    	myY = myInfo -> bitmapHeight + MARGIN;
    }
    else
    {
    	myY = SMALL_GAP;
        MyDrawStrings (myInfo, myDisplayContext, myInfo -> productNameFont,
    		  myInfo -> productNameMsg, myInfo -> productNameLines, 
    		  &myY, pmDraw, TRUE);
    	myY += LARGE_GAP;
    }

    //
    // Output "Created By Holt Software Associates Inc."
    //
    MyDrawString (myInfo, myDisplayContext, myInfo -> createdByFont,
    		  myInfo -> createdByMsg, &myY, pmDraw, TRUE);
    
    if (gProgram.assistedByIBM && gProgram.isJava)
    {
    	//
    	// Output "Development Assisted by IBM Corp."
    	//
        MyDrawString (myInfo, myDisplayContext, myInfo -> createdByFont,
    		      myInfo -> assistedByMsg, &myY, pmDraw, TRUE);
    } // if (gProgram.assistedByIBM)

    //
    //        	    
    // Output "Lead Programmer: Tom West"
    //
    if (gProgram.isJava)
    {
        MyDrawString (myInfo, myDisplayContext, myInfo -> chiefProgrammerFont,
    		      myInfo -> leadProgrammerMsg, &myY, pmDraw, TRUE);
    } // if (gProgram.isJava)
	    	
    //    	    
    // Output version number	    	
    //
    myY += SMALL_GAP;
    MyDrawString (myInfo, myDisplayContext, myInfo -> versionFont,
    		  myInfo -> versionString, &myY, pmDraw, TRUE);

    //
    // Output install kind specific info
    if (gProgram.miniVersion)
    {
    	//
	// Output: Licensed to xxx.
	//	   This version cannot compile programs of greater than 100 lines in length
	//
        myY += SMALL_GAP;
        MyDrawStrings (myInfo, myDisplayContext, myInfo -> chiefProgrammerFont,
    		       myInfo -> miniMsg, 3, &myY, pmDraw, TRUE);
    }
    else if (gProgram.installKind == INSTALL_KIND_EVAL)
    {
    	//
	// Output: This version is for personal evaluation purposes only.
	//	   It may not be redistributed or used for teaching purposes.
	//	   See the "Help" menu for information on obtaining Ready.
	//	   This version is time limited and will not execute Java programs after xxx
	// or
	//
	// Output: This version is for personal evaluation purposes only.
	//	   It may not be redistributed or used for teaching purposes.
	//	   See the "Help" menu for information on obtaining Ready.
	//	   This demonstration version of the software is restricted and
	//		(1) Cannot save programs,
	//    	        (2) Cannot compile programs of greater than 100 lines in length, and
	//		(3) Will not execute programs after xxx
	//
        myY += SMALL_GAP;
	if (gProgram.restrictedVersion)
	{
            MyDrawStrings (myInfo, myDisplayContext, 
            		   myInfo -> chiefProgrammerFont,
    		           myInfo -> evalMsg, 3, &myY, pmDraw, TRUE);
	    myY += SMALL_GAP;    		           
            MyDrawStrings (myInfo, myDisplayContext, 
            		   myInfo -> chiefProgrammerFont,
    		           myInfo -> restrictMsg, 4, &myY, pmDraw, TRUE);
	}
	else
	{
            MyDrawStrings (myInfo, myDisplayContext, 
            		   myInfo -> chiefProgrammerFont,
    		           myInfo -> evalMsg, 4, &myY, pmDraw, TRUE);
	}
    }
    else if (gProgram.installKind == INSTALL_KIND_BETA)
    {
    	//
	// Output: This version is for personal beta test purposes only.
	//	   It may not be redistributed or used for teaching purposes.
	//	   Please report all bugs found in this software to [email protected]
	//	   This version of the software will not execute programs after xxx
	//
        myY += SMALL_GAP;
        MyDrawStrings (myInfo, myDisplayContext, 
            	       myInfo -> chiefProgrammerFont,
    		       myInfo -> betaMsg, 4, &myY, pmDraw, TRUE);
    }
    else if (gProgram.installKind == INSTALL_KIND_PERSONAL)
    {
        myY += SMALL_GAP;
        MyDrawString (myInfo, myDisplayContext, myInfo -> chiefProgrammerFont,
    		      myInfo -> personalMsg, &myY, pmDraw, TRUE);
    }
    else if (gProgram.installKind == INSTALL_KIND_SITE)
    {
        myY += SMALL_GAP;
        MyDrawString (myInfo, myDisplayContext, myInfo -> chiefProgrammerFont,
    		      myInfo -> siteMsg, &myY, pmDraw, TRUE);
    }
    else if (gProgram.installKind == INSTALL_KIND_REDISTRIB)
    {
        myY += SMALL_GAP;
        MyDrawString (myInfo, myDisplayContext, myInfo -> chiefProgrammerFont,
    		      myInfo -> redistribMsg, &myY, pmDraw, TRUE);
    }
    
    if (gProgram.isJava)
    {
    	//
    	// Output "Using IBM's Jikes Java Compiler"
    	//
        myY += SMALL_GAP;
        MyDrawString (myInfo, myDisplayContext, myInfo -> usingJikesFont,
    		      myInfo -> usingJikesMsg, &myY, pmDraw, TRUE);

        myY += SMALL_GAP;
	if (gProgram.operatingSystem == WIN_95)
	{
            MyDrawString (myInfo, myDisplayContext, myInfo -> trademarkFont,
	    		  myInfo -> win95Msg, &myY, pmDraw, TRUE);
	}
	else
	{
            MyDrawString (myInfo, myDisplayContext, myInfo -> trademarkFont,
	    		  myInfo -> jreLevelMsg, &myY, pmDraw, TRUE);
	}

    	//    	        
    	// Output trademark information
    	//
        myY += SMALL_GAP;
        MyDrawString (myInfo, myDisplayContext, myInfo -> trademarkFont,
    		      myInfo -> trademarkMsg, &myY, pmDraw, TRUE);
    } // if (gProgram.isJava)
    
    EndPaint (pmSplashWindow, &myPaintStruct);
    
    return myY;
} // MyPaintSplash
Ejemplo n.º 23
0
static void InstallColours(void)
{
   int pixVal=0;
   int c;
   int step;
   LOGPALETTE *pal;
   HPALETTE hpal,OldPal;
   HDC dc;
   /* WHITE */
   colours[0][0] = 255; colours[0][1] = 255; colours[0][2] = 255;
   /* YELLOW */
   colours[1][0] = 255; colours[1][1] = 255; colours[1][2] = 0;
   /* ORANGE */
   colours[2][0] = 255; colours[2][1] = 128; colours[2][2] = 0;
   /* RED */
   colours[3][0] = 255; colours[3][1] = 0;   colours[3][2] = 0;
   /* MAUVE */
   colours[4][0] = 196; colours[4][1] = 100; colours[4][2] = 255;
   /* PURPLE */
   colours[5][0] = 128; colours[5][1] = 0;   colours[5][2] = 128;
   /* DARK_BLUE */
   colours[6][0] = 0;   colours[6][1] = 0;   colours[6][2] = 196;
   /* LIGHT_BLUE (CYAN) */
   colours[7][0] = 0;   colours[7][1] = 255; colours[7][2] = 255;
   /* DARK_GREEN */
   colours[8][0] = 0;   colours[8][1] = 128; colours[8][2] = 0;
   /* LIGHT_GREEN */
   colours[9][0] = 0;   colours[9][1] = 255; colours[9][2] = 0;
   /* DARK_BROWN */
   colours[10][0] = 128;colours[10][1] = 64; colours[10][2] = 64;
   /* LIGHT_BROWN */
   colours[11][0] = 196;colours[11][1] = 140;colours[11][2] = 140;
   /* LIGHT_GREY */
   colours[12][0] = 196;colours[12][1] = 196;colours[12][2] = 196;
   /* GREY */
   colours[13][0] = 128;colours[13][1] = 128;colours[13][2] = 128;
   /* DARK_GREY */
   colours[14][0] = 64; colours[14][1] = 64; colours[14][2] = 64;
   /* BLACK */
   colours[15][0] = 0;  colours[15][1] = 0;  colours[15][2] = 0;
     
   step = 256/MAX_GREYS;
   for (c = 0; c < MAX_GREYS; c++, pixVal+= step){
      greys[c] = pixVal;
   } 
     
   /* if display is 8 bits or less, create a palette containing 
      the best match to our desired colors. If it is 16 bits or
      greater, matching will be no problem. */
   if (dispDEEP <= 8){
      pal = (LOGPALETTE *) 
         New(&gcheap,2*sizeof(WORD) + (MAX_GREYS + MAX_COLOURS)*sizeof(PALETTEENTRY));
      pal->palVersion = 0x300;
      pal->palNumEntries = MAX_GREYS + MAX_COLOURS;
          
      /* most important colors should be first in list. Black, White, 
         the rest of the colors, then the greys. */

      pal->palPalEntry[0].peRed = pal->palPalEntry[0].peGreen = 
         pal->palPalEntry[0].peBlue = 0;
      pal->palPalEntry[0].peFlags = 0;
      pal->palPalEntry[1].peRed = pal->palPalEntry[1].peGreen = 
         pal->palPalEntry[1].peBlue = 255;
      pal->palPalEntry[1].peFlags = 0;
      for (c=2;c<MAX_COLOURS;c++) {
         pal->palPalEntry[c].peRed = colours[c-1][0];
         pal->palPalEntry[c].peGreen = colours[c-1][1];
         pal->palPalEntry[c].peBlue = colours[c-1][2];
         pal->palPalEntry[c].peFlags = 0;
      } 
          
      for (c=0;c<MAX_GREYS;c++) {
         pal->palPalEntry[MAX_COLOURS+c].peRed = greys[c];
         pal->palPalEntry[MAX_COLOURS+c].peGreen = greys[c];
         pal->palPalEntry[MAX_COLOURS+c].peBlue = greys[c];
         pal->palPalEntry[MAX_COLOURS+c].peFlags = 0;
      }
      hpal = CreatePalette(pal);
          
      OldPal = SelectPalette(memDC,hpal,FALSE);
      RealizePalette(memDC);
      SelectPalette(memDC,OldPal,FALSE);
          
      dc = GetDC(theWindow);
      OldPal = SelectPalette(dc,hpal,FALSE);
      RealizePalette(dc);
      SelectPalette(dc,OldPal,FALSE);
      ReleaseDC(theWindow,dc);
      DeleteObject(hpal);
   } /* if (dispDEEP <= 8) */
}
Ejemplo n.º 24
0
/*****************************************************************************
 * x11_copy_to_screen
 *
 * Helper function that blts the front buffer contents to the target window
 *
 * Params:
 *  This: Surface to copy from
 *  rc: Rectangle to copy
 *
 *****************************************************************************/
void x11_copy_to_screen(IWineD3DSwapChainImpl *This, const RECT *rc)
{
    IWineD3DSurfaceImpl *front = This->front_buffer;

    if(front->resource.usage & WINED3DUSAGE_RENDERTARGET) {
        POINT offset = {0,0};
        HWND hDisplayWnd;
        HDC hDisplayDC;
        HDC hSurfaceDC = 0;
        RECT drawrect;
        TRACE("(%p)->(%p): Copying to screen\n", front, rc);

        hSurfaceDC = front->hDC;

        hDisplayWnd = This->win_handle;
        hDisplayDC = GetDCEx(hDisplayWnd, 0, DCX_CLIPSIBLINGS|DCX_CACHE);
        if(rc) {
            TRACE(" copying rect (%d,%d)->(%d,%d), offset (%d,%d)\n",
                  rc->left, rc->top, rc->right, rc->bottom, offset.x, offset.y);
        }

        /* Front buffer coordinates are screen coordinates. Map them to the destination
         * window if not fullscreened
         */
        if(This->presentParms.Windowed) {
            ClientToScreen(hDisplayWnd, &offset);
        }
#if 0
        /* FIXME: This doesn't work... if users really want to run
        * X in 8bpp, then we need to call directly into display.drv
        * (or Wine's equivalent), and force a private colormap
        * without default entries. */
        if (front->palette) {
        SelectPalette(hDisplayDC, front->palette->hpal, FALSE);
        RealizePalette(hDisplayDC); /* sends messages => deadlocks */
    }
#endif
        drawrect.left   = 0;
        drawrect.right  = front->currentDesc.Width;
        drawrect.top    = 0;
        drawrect.bottom = front->currentDesc.Height;

#if 0
        /* TODO: Support clippers */
        if (front->clipper)
        {
        RECT xrc;
        HWND hwnd = ((IWineD3DClipperImpl *) front->clipper)->hWnd;
        if (hwnd && GetClientRect(hwnd,&xrc))
        {
        OffsetRect(&xrc,offset.x,offset.y);
        IntersectRect(&drawrect,&drawrect,&xrc);
    }
    }
#endif
        if (rc) {
            IntersectRect(&drawrect,&drawrect,rc);
        }
        else {
            /* Only use this if the caller did not pass a rectangle, since
            * due to double locking this could be the wrong one ...
            */
            if (front->lockedRect.left != front->lockedRect.right) {
                IntersectRect(&drawrect,&drawrect,&front->lockedRect);
            }
        }

        BitBlt(hDisplayDC,
               drawrect.left-offset.x, drawrect.top-offset.y,
               drawrect.right-drawrect.left, drawrect.bottom-drawrect.top,
               hSurfaceDC,
               drawrect.left, drawrect.top,
               SRCCOPY);
        ReleaseDC(hDisplayWnd, hDisplayDC);
    }
}
// DDBToDIB		- Creates a DIB from a DDB
// bitmap		- Device dependent bitmap
// dwCompression	- Type of compression - see BITMAPINFOHEADER
// pPal			- Logical palette
HANDLE CClientCapture::DDBToDIB( CBitmap& bitmap, DWORD dwCompression, CPalette* pPal, 	CDC *dc) 
{
	BITMAP			bm;
	BITMAPINFOHEADER	bi;
	//LPBITMAPINFOHEADER 	lpbi;
	DWORD			dwLen;
	//HANDLE			hDIB;
	HANDLE			handle;
	HDC 			hDC;
	HPALETTE		hPal;


	ASSERT( bitmap.GetSafeHandle() );

	// The function has no arg for bitfields
	if( dwCompression == BI_BITFIELDS )
		return NULL;

	// If a palette has not been supplied use defaul palette
	hPal = (HPALETTE) pPal->GetSafeHandle();
	if (hPal==NULL)
		hPal = (HPALETTE) GetStockObject(DEFAULT_PALETTE);

	// Get bitmap information
	bitmap.GetObject(sizeof(bm),(LPSTR)&bm);

	// Initialize the bitmapinfoheader
	bi.biSize		= sizeof(BITMAPINFOHEADER);
	bi.biWidth		= bm.bmWidth;
	bi.biHeight 		= bm.bmHeight;
	bi.biPlanes 		= 1;
	bi.biBitCount		= bm.bmPlanes * bm.bmBitsPixel;
	bi.biCompression	= dwCompression;
	bi.biSizeImage		= 0;
	bi.biXPelsPerMeter	= 0;
	bi.biYPelsPerMeter	= 0;
	bi.biClrUsed		= 0;
	bi.biClrImportant	= 0;

	// Compute the size of the  infoheader and the color table
	int nColors = (1 << bi.biBitCount);
	if( nColors > 256 ) 
		nColors = 0;
	dwLen  = bi.biSize + nColors * sizeof(RGBQUAD);

	// We need a device context to get the DIB from
	hDC = dc->GetSafeHdc();

	//hDC = GetDC(NULL);
	hPal = SelectPalette(hDC,hPal,FALSE);
	RealizePalette(hDC);

	
	// Allocate enough memory to hold bitmapinfoheader and color table
	if(hDIB) GlobalFree( hDIB );

	hDIB = GlobalAlloc(GMEM_FIXED,dwLen);

	if (!hDIB){
		SelectPalette(hDC,hPal,FALSE);
		return NULL;
	}

	lpbi = (LPBITMAPINFOHEADER)hDIB;

	*lpbi = bi;

	// Call GetDIBits with a NULL lpBits param, so the device driver 
	// will calculate the biSizeImage field 
	GetDIBits(hDC, (HBITMAP)bitmap.GetSafeHandle(), 0L, (DWORD)bi.biHeight,
			(LPBYTE)NULL, (LPBITMAPINFO)lpbi, (DWORD)DIB_RGB_COLORS);

	bi = *lpbi;

	// If the driver did not fill in the biSizeImage field, then compute it
	// Each scan line of the image is aligned on a DWORD (32bit) boundary
	if (bi.biSizeImage == 0){
		bi.biSizeImage = ((((bi.biWidth * bi.biBitCount) + 31) & ~31) / 8) 
						* bi.biHeight;

		// If a compression scheme is used the result may infact be larger
		// Increase the size to account for this.
		if (dwCompression != BI_RGB)
			bi.biSizeImage = (bi.biSizeImage * 3) / 2;
	}

	// Realloc the buffer so that it can hold all the bits
	dwLen += bi.biSizeImage;
	if (handle = GlobalReAlloc(hDIB, dwLen, GMEM_MOVEABLE))
		hDIB = handle;
	else{
		GlobalFree(hDIB);
		hDIB = 0;
		// Reselect the original palette
		SelectPalette(hDC,hPal,FALSE);

		return NULL;
	}

	// Get the bitmap bits
	lpbi = (LPBITMAPINFOHEADER)hDIB;
	m_pBMI = (LPBITMAPINFO)hDIB;
	m_pBits = (LPBYTE)hDIB + (bi.biSize + nColors * sizeof(RGBQUAD));

	// FINALLY get the DIB
	BOOL bGotBits = GetDIBits( hDC, (HBITMAP)bitmap.GetSafeHandle(),
				0L,				// Start scan line
				(DWORD)bi.biHeight,		// # of scan lines
				(LPBYTE) m_pBits,//lpbi 			// address for bitmap bits
				(LPBITMAPINFO)lpbi,		// address of bitmapinfo
				(DWORD)DIB_RGB_COLORS);		// Use RGB for color table

	if( !bGotBits )
	{
		GlobalFree(hDIB);
		hDIB = 0;
		SelectPalette(hDC,hPal,FALSE);

		return NULL;
	}

	SelectPalette(hDC,hPal,FALSE);

	return hDIB;
}
Ejemplo n.º 26
0
LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
     static HPALETTE hPalette ;
     static int      cxClient, cyClient ;
     HDC             hdc ;
     PAINTSTRUCT     ps ;

     switch (message)
     {
     case WM_CREATE:
          if (!CheckDisplay (hwnd))
               return -1 ;

          hPalette = CreateRoutine (hwnd) ;
          return 0 ;
     
     case WM_DISPLAYCHANGE:
          if (!CheckDisplay (hwnd))
               DestroyWindow (hwnd) ;

          return 0 ;

     case WM_SIZE:
          cxClient = LOWORD (lParam) ;
          cyClient = HIWORD (lParam) ;
          return 0 ;

     case WM_PAINT:
          hdc = BeginPaint (hwnd, &ps) ;

          SelectPalette (hdc, hPalette, FALSE) ;
          RealizePalette (hdc) ;

          PaintRoutine (hdc, cxClient, cyClient) ;

          EndPaint (hwnd, &ps) ;
          return 0 ;

     case WM_TIMER:
          hdc = GetDC (hwnd) ;

          SelectPalette (hdc, hPalette, FALSE) ;

          TimerRoutine (hdc, hPalette) ;

          ReleaseDC (hwnd, hdc) ;
          return 0 ;

     case WM_QUERYNEWPALETTE:
          if (!hPalette)
               return FALSE ;

          hdc = GetDC (hwnd) ;
          SelectPalette (hdc, hPalette, FALSE) ;
          RealizePalette (hdc) ;
          InvalidateRect (hwnd, NULL, TRUE) ;

          ReleaseDC (hwnd, hdc) ;
          return TRUE ;

     case WM_PALETTECHANGED:
          if (!hPalette || (HWND) wParam == hwnd)
               break ;

          hdc = GetDC (hwnd) ;
          SelectPalette (hdc, hPalette, FALSE) ;
          RealizePalette (hdc) ;
          UpdateColors (hdc) ;

          ReleaseDC (hwnd, hdc) ;
          break ;

     case WM_DESTROY:
          DestroyRoutine (hwnd, hPalette) ;
          PostQuitMessage (0) ;
          return 0 ;
     }
     return DefWindowProc (hwnd, message, wParam, lParam) ;
}
Ejemplo n.º 27
0
LRESULT CALLBACK EXPORT AWLayoutWndProc
  (
  HWND    hwnd,
  UINT    uMsg,
  WPARAM  wParam,
  LPARAM  lParam
  )

  {
  BOOL    fHandled = FALSE;
  LRESULT lRet;
  Layout* pLayout = (Layout*)GetWindowLong(hwnd, I_GWL_LAYOUT);

  switch(uMsg)
    {
    case WM_CREATE:
      pLayout = (Layout*)(((CREATESTRUCT*)lParam)->lpCreateParams);
      SetWindowLong(hwnd, I_GWL_LAYOUT, (long)pLayout);
      pLayout->m_hwndLayout = hwnd;
      fHandled = TRUE;
      lRet = 0L;
      break;

    case WM_SYSCOMMAND:
      if((wParam & 0xFFF0)==SC_CLOSE)
        {
        FORWARD_WM_COMMAND(hwnd, IDM_EXIT, 0, 0, PostMessage);
        fHandled = TRUE;
        lRet = 0L;
        break;
        }
      break;

    case WM_QUERYENDSESSION:
      MessageBeep(MB_ICONEXCLAMATION);
      MessageBox(hwnd, "Window layout is still active.\r\n\r\nQuit the window layout before quitting Windows.", "Window Layout", MB_TASKMODAL | MB_OK | MB_ICONEXCLAMATION);
      lRet = 0;
      fHandled = TRUE;
      break;

    case WM_KEYDOWN:
      (pLayout->m_shapes).KeyDown(pLayout->m_pWndActive, hwnd, (int)wParam, lParam);
      fHandled = TRUE;
      lRet = 0L;
      break;

    case WM_KEYUP:
      (pLayout->m_shapes).KeyUp(pLayout->m_pWndActive, hwnd, (int)wParam, lParam);
      fHandled = TRUE;
      lRet = 0L;
      break;

    case WM_INITMENUPOPUP:
      HANDLE_WM_INITMENUPOPUP(hwnd, wParam, lParam, pLayout->InitMenuPopup);
      fHandled = TRUE;
      lRet = 0L;
      break;

    case WM_PALETTECHANGED:
      if ((pLayout->ActiveWindow()) && ((HWND)wParam==pLayout->ActiveWindow()->ClientWnd()))
        break;
      // else fall through
    case WM_QUERYNEWPALETTE:
      if(!IsIconic(hwnd) && pLayout->ActiveWindow() && WndData::GetPaletteHandle())
        {
        HDC       hdc     = GetDC(pLayout->ActiveWindow()->ClientWnd());
        HPALETTE  hpalOld = SelectPalette(hdc, WndData::GetPaletteHandle(), FALSE);
        lRet = RealizePalette(hdc);         
        SelectPalette(hdc, hpalOld, TRUE);
        RealizePalette(hdc);
        ReleaseDC(pLayout->ActiveWindow()->ClientWnd(), hdc);

        if(lRet)                            
          InvalidateRect(pLayout->ActiveWindow()->ClientWnd(), NULL, TRUE);
        fHandled = TRUE;
        }
      break;

    case WM_HSCROLL:
      HANDLE_WM_HSCROLL(hwnd, wParam, lParam, pLayout->HScroll);
      fHandled = TRUE;
      lRet = 0;
      break;

    case WM_VSCROLL:
      HANDLE_WM_VSCROLL(hwnd, wParam, lParam, pLayout->VScroll);
      fHandled = TRUE;
      lRet = 0L;
      break;

    case WM_SIZE:
      pLayout->UpdateScrollRegion();
      fHandled = TRUE;
      lRet = 0L;
      break;

    case WM_COMMAND:
      HANDLE_WM_COMMAND(hwnd, wParam, lParam, pLayout->Command);
      fHandled = TRUE;
      lRet = 0L;
      break;

    case WM_NCACTIVATE:
      if(!IsIconic(hwnd) && pLayout->m_pWndActive && pLayout->m_pWndActive->WndHandle())
        SendMessage(pLayout->m_pWndActive->WndHandle(), uMsg, wParam, lParam);
      break;

    default:
      break;
    }

  if(!fHandled)
    lRet = DefWindowProc(hwnd, uMsg, wParam, lParam);

  return lRet;
  }
Ejemplo n.º 28
0
LRESULT CALLBACK
WinProc(HWND   hWnd,   /* I - Window triggering this event */
        UINT   uMsg,   /* I - Message type */
        WPARAM wParam, /* I - 'word' parameter value */
        LPARAM lParam) /* I - 'long' parameter value */
    {
    PAINTSTRUCT ps;    /* WM_PAINT message info */
    RECT        rect;  /* Current client area rectangle */


    switch (uMsg)
        {
        case WM_CREATE :
            /*
             * 'Create' message.  Get device and rendering contexts, and 
	     * setup the client area for OpenGL drawing...
	     */

            DC = GetDC(hWnd);
	    SetupContext();
	    break;

        case WM_SIZE :
            /*
	     * Handle resizes...
	     */

            GetClientRect(hWnd, &rect);
	    Resize(rect.right, rect.bottom);

        case WM_PAINT :
            /*
             * Repaint the client area...
	     */

            BeginPaint(hWnd, &ps);
	    Redraw();
	    EndPaint(hWnd, &ps);
	    break;

        case WM_QUIT :
        case WM_CLOSE :
            /*
             * Destroy the window and exit...
             */

            DestroyWindow(Window);
            exit(0);
            break;

        case WM_DESTROY :
            /*
             * Release and free the device context, rendering
             * context, and color palette...
	     */

            if (RC)
    	        wglDeleteContext(RC);

            if (DC)
    	        ReleaseDC(Window, DC);

	    if (Palette)
	        DeleteObject(Palette);

            PostQuitMessage(0);
            break;

        case WM_QUERYNEWPALETTE :
            /*
             * Realize the color palette if necessary...
	     */

            if (Palette)
	        {
                SelectPalette(DC, Palette, FALSE);
                RealizePalette(DC);

                InvalidateRect(hWnd, NULL, FALSE);
	        return (TRUE);
	        }
            break;

        case WM_PALETTECHANGED:
            /*
             * Reselect our color palette if necessary...
	     */

            if (Palette && (HWND)wParam != hWnd)
	        {
                SelectPalette(DC, Palette, FALSE);
                RealizePalette(DC);

                UpdateColors(DC);
	        }
	    break;

        case WM_CHAR :
	    /*
	     * Handle key presses...
	     */

	    Keyboard((unsigned char)wParam, 0, 0);
	    break;

        default :
            /*
             * Pass all other messages through the default window
             * procedure...
             */

            return (DefWindowProc(hWnd, uMsg, wParam, lParam));
        }

    return (FALSE);
    }
Ejemplo n.º 29
0
LONG CALLBACK AppWndProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam)
{
  RECT Rect;
  int key;
  switch (msg)
  {
    case WM_COMMAND:
      switch(LOWORD(wParam))
      {
         case CM_FILEEXIT:
            DestroyWindow(hwndApp);
            break;
         case CM_FILEOPEN:
            OpenBitmap();
            break;
         case CM_PALETTE:
            if(!paletteWindow)
               paletteWindow = CreateDialog(hInstApp, "PaletteControl", hwnd, (DLGPROC) PaletteDialog);
            break;
      }
      break;
    case WM_KEYDOWN:
    case WM_KEYUP:
    case WM_CREATE:
      break;

    case WM_PALETTECHANGED:
      break;
    case WM_QUERYNEWPALETTE:
    {
      BOOL changed;
      HDC hDC = GetDC(hwnd);
      if(sfc) sfc->setPalette(NULL);
      changed = RealizePalette(hDC);
      if(changed)
      {
         InvalidateRect(hwnd, NULL, TRUE);
         //((GFXCDSSurface *)sfc)->setHWND(hwnd);
      }
      return changed;
    }
    case WM_SETCURSOR:
      break;

    case WM_ENTERMENULOOP:
      break;

    case WM_EXITMENULOOP:
      break;

    case WM_INITMENUPOPUP:
        break;

    case WM_DESTROY:
      hwndApp = NULL;
      PostQuitMessage(0);
      break;

    case WM_PAINT:
      LPPAINTSTRUCT lpPaint;
      //BeginPaint(hwnd, lpPaint);
      if(sfc) sfc->update();
      //EndPaint(hwnd, lpPaint);
      return 1;
      break;

    case WM_MOVE:
    case WM_SIZE:
      break;

    case WM_MOUSEMOVE:
    case WM_LBUTTONDOWN:
      if(GetKeyState(VK_LBUTTON) < 0)
      {
         imgPoint.x = LOWORD(lParam);
         imgPoint.y = HIWORD(lParam);
         Redraw();
      }
      break;
  }

  return DefWindowProc(hwnd,msg,wParam,lParam);
}
Ejemplo n.º 30
0
int gr_palette_fade_in(ubyte *pal, int nsteps, int allow_keys)	
{
	HRESULT ddresult;
	int i,j;
	ubyte c;
	fix fade_palette[768];
	fix fade_palette_delta[768];

	allow_keys  = allow_keys;

	Assert(_lpDDPalActive!=0);

	if (!gr_palette_faded_out) return 0;

	#ifndef NDEBUG
	if (grd_fades_disabled) {
		gr_palette_load(pal);
		return 0;
	}
	#endif

	for (i=0; i<768; i++ )	{
		gr_current_pal[i] = pal[i];
		fade_palette[i] = 0;
		fade_palette_delta[i] = i2f(pal[i]+gr_palette_gamma) / nsteps;
	}

	for (j=0; j<nsteps; j++ )	{
		for (i=0; i<256; i++ )	{
			fade_palette[i*3] += fade_palette_delta[i*3];
			fade_palette[i*3+1] += fade_palette_delta[i*3+1];
			fade_palette[i*3+2] += fade_palette_delta[i*3+2];
			if (fade_palette[i*3] > i2f(pal[i*3]+gr_palette_gamma) )
				fade_palette[i*3] = i2f(pal[i*3]+gr_palette_gamma);
			if (fade_palette[i*3+1] > i2f(pal[i*3+1]+gr_palette_gamma) )
				fade_palette[i*3+1] = i2f(pal[i*3+1]+gr_palette_gamma);
			if (fade_palette[i*3+2] > i2f(pal[i*3+2]+gr_palette_gamma) )
				fade_palette[i*3+2] = i2f(pal[i*3+2]+gr_palette_gamma);

			c = f2i(fade_palette[i*3]);
			if ( c > 63 ) c = 63;
			PalGDIData.ScratchPal[i].peRed = c << 2;
			c = f2i(fade_palette[i*3+1]);
			if ( c > 63 ) c = 63;
			PalGDIData.ScratchPal[i].peGreen = c << 2;
			c = f2i(fade_palette[i*3+2]);
			if ( c > 63 ) c = 63;
			PalGDIData.ScratchPal[i].peBlue = c << 2;
			PalGDIData.ScratchPal[i].peFlags = 0;
		}
			
		if (!hPalGDI) {
			IDirectDraw_WaitForVerticalBlank(lpDD, DDWAITVB_BLOCKBEGIN, NULL);
			ddresult = IDirectDrawPalette_SetEntries(_lpDDPalActive, 0,
											0, 256,
											PalGDIData.ScratchPal);
			Assert (ddresult == DD_OK);
		}
		else {
			HDC hdc;
		
			hdc = GetDC(GetLibraryWindow());		
			SetPaletteEntries(hPalGDI, 0, PalGDIData.num, PalGDIData.ScratchPal);
			RealizePalette(hdc);
			ReleaseDC(GetLibraryWindow(), hdc);
		}
	}

	gr_palette_faded_out = 0;
	return 0;
}