Example #1
0
HANDLE	CreateDialogBoxHandle (	  DIALOGBOX &		DialogBoxTemplate )
   {
	register char *			memp,
		      *			memory_dialog ;
	register char far *		globalp ;
	DLGTEMPLATE			DlgTemplate = DialogBoxTemplate. DialogTemplate ;
	DLGITEMTEMPLATE *		ItemTemplates = DialogBoxTemplate. DialogItemTemplates ,
			*		pItem ;
	FONTINFO			FontInfo = DialogBoxTemplate. FontInfo ;
	HANDLE				handle ;
	register int			i, size, memsize ;

// On ne se préoccupe pas pour le moment des infos à la fin de la
// définition
// et on calcule la taille du bazar.
// Remarque : on utilise sizeof ( DLGTEMPLATE ), etc... la taille calculée
// sera légèrement supérieure à la taille réelle du dialogue car, par ce
// procédé, on inclut aussi les pointeurs sur les chaînes de caractères.
	size  = sizeof ( DLGTEMPLATE ) +
			( sizeof ( DLGITEMTEMPLATE ) * DlgTemplate. dtItemCount ) ;
	size += strlen ( DlgTemplate. dtMenuName ) 	+ 1 +
		strlen ( DlgTemplate. dtClassName )     + 1 +
		strlen ( DlgTemplate. dtCaptionText )	+ 1 ;

	for  ( i = 0, pItem = ItemTemplates ;
			i < DlgTemplate. dtItemCount ;
				i ++, pItem ++ )
		size += strlen ( pItem -> dtilClass ) 	+ 1 +
			strlen ( pItem -> dtilText )	+ 1 ;

	memp    = memory_dialog = new  char [ size ] ;
	memset ( memp, 0, size ) ;
	memsize = size ;


// La place mémoire est allouée pour la définition du dialogue : on copie
// maintenant les données de la boîte.

// Recopie des champs entiers
	size  = sizeof ( DlgTemplate. dtStyle ) 	+
		sizeof ( DlgTemplate. dtItemCount )	+
		sizeof ( DlgTemplate. dtX )		+
		sizeof ( DlgTemplate. dtY )		+
		sizeof ( DlgTemplate. dtCX )		+
		sizeof ( DlgTemplate. dtCY ) ;
	memmove ( memp, & DlgTemplate. dtStyle, size ) ;
	memp += size ;

 // Recopie du nom de menu, de la classe et du titre
	strcpy ( memp, DlgTemplate. dtMenuName ) ;
	memp += strlen ( DlgTemplate. dtMenuName ) + 1 ;

	strcpy ( memp, DlgTemplate. dtClassName ) ;
	memp += strlen ( DlgTemplate. dtClassName ) + 1 ;

	strcpy ( memp, DlgTemplate. dtCaptionText ) ;
	memp += strlen ( DlgTemplate. dtCaptionText ) + 1 ;

// Taille et nom de la police
	memmove ( memp, & FontInfo. PointSize, sizeof ( FontInfo. PointSize ) ) ;
	memp += sizeof ( FontInfo. PointSize ) ;

	strcpy ( memp, FontInfo. szTypeFace ) ;
	memp += strlen ( FontInfo. szTypeFace ) + 1 ;


// Recopie des contrôles
	for  ( i = 0, pItem = ItemTemplates ; i < DlgTemplate. dtItemCount ; i ++, pItem ++ )
	   {

	// Recopie des premiers champs numériques
		size  = sizeof ( pItem -> dtilX )  +
			sizeof ( pItem -> dtilY )  +
			sizeof ( pItem -> dtilCX ) +
			sizeof ( pItem -> dtilCY ) +
			sizeof ( pItem -> dtilID ) +
			sizeof ( pItem -> dtilStyle ) ;

		memmove ( memp, & pItem -> dtilX, size ) ;
		memp += size ;

	// Recopie de la classe et du texte
		strcpy ( memp, pItem -> dtilClass ) ;
		memp += strlen ( pItem -> dtilClass ) + 1 ;

		strcpy ( memp, pItem -> dtilText ) ;
		memp += strlen ( pItem -> dtilText ) + 1 ;

	// Recopie des éventuelles données propres à ce contrôle
		memmove ( memp, & pItem -> dtilInfo, sizeof ( pItem -> dtilInfo ) ) ;
		memp += sizeof ( pItem -> dtilInfo ) ;

		if  ( pItem -> dtilInfo )
		   {
			memmove ( memp, pItem -> dtilData, pItem -> dtilInfo ) ;
			memp += pItem -> dtilInfo ;
		    }
	}



// Allocation d'un bloc de mémoire globale pour y placer la définition de
// la boîte
	handle = GlobalAlloc ( GMEM_FIXED, memsize ) ;
	globalp      = ( char far * ) GlobalLock  ( handle ) ;
	movedata ( FP_SEG ( memory_dialog ), FP_OFF ( memory_dialog ),
		   FP_SEG ( globalp       ), FP_OFF ( globalp ),
			memsize ) ;
	GlobalUnlock ( handle ) ;


// Effacement de tous les objects alloués
	delete []  memory_dialog ;


	return ( handle ) ;
    }
void CIOSFileList::OnLvnBegindrag(NMHDR *pNMHDR, LRESULT *pResult)
{
	CIOSDirectoryTree::m_askIsTransPng = true;
	CIOSDirectoryTree::m_askIsTransPlist = true;
	LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR);

	UINT uFileCount = 0;
	int iItem = GetNextItem(-1,LVNI_SELECTED);
	std::vector<std::wstring> names;
	std::vector<int> items;
	while (iItem != -1)
	{
		std::wstring name = this->GetItemText(iItem, 0).GetString();
		std::wstring path = m_indexList->GetPathByHTreeItem(m_hTreeItem) + name;
		if (m_indexList->IsFolderItem(path, true))
		{
			iItem = GetNextItem(iItem,LVNI_SELECTED);
			continue;
		}
		++uFileCount;
		names.push_back(name);
		items.push_back(iItem);
		iItem = GetNextItem(iItem,LVNI_SELECTED);
	}

	UINT uBuffSize = sizeof(FILEGROUPDESCRIPTOR) + (uFileCount) * sizeof(FILEDESCRIPTOR);
	HGLOBAL hFileDescriptor = GlobalAlloc (GHND | GMEM_SHARE, uBuffSize);        
	if(hFileDescriptor)
	{
		FILEGROUPDESCRIPTOR* pGroupDescriptor = (FILEGROUPDESCRIPTOR*) GlobalLock ( hFileDescriptor );
		if(pGroupDescriptor)
		{
			FILEDESCRIPTOR* pFileDescriptorArray = (FILEDESCRIPTOR*)((LPBYTE)pGroupDescriptor + sizeof(UINT));
			pGroupDescriptor->cItems = uFileCount;
			for (size_t index = 0; index < names.size(); ++index)
			{          
				ZeroMemory(&pFileDescriptorArray[index], sizeof(FILEDESCRIPTOR));
				pFileDescriptorArray[index].dwFlags = FD_FILESIZE|FD_ATTRIBUTES;

				int size = 0;
				for (size_t i = 0; i < m_itemDatas.size(); ++i)
				{
					if (m_itemDatas[i])
					{
						if (!wcscmp(m_itemDatas[i]->itemData[0]->strValue, names[index].c_str()))
						{
							size = m_itemDatas[i]->itemData[2]->intValue;
							break;
						}
					}
				}
				pFileDescriptorArray[index].nFileSizeLow = size;
				pFileDescriptorArray[index].nFileSizeHigh = 0;
				pFileDescriptorArray[index].dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
				lstrcpy ( pFileDescriptorArray[index].cFileName, names[index].c_str());	
			}
			GlobalUnlock ( hFileDescriptor ); 
		}
	}
	else
	{
		GlobalFree ( hFileDescriptor );
	}


	CHOleDataSource dragDataSource;
	dragDataSource.SetAssociat(items, m_indexList);
	FORMATETC etcDescriptor = { RegisterClipboardFormat(CFSTR_FILEDESCRIPTOR), NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
	dragDataSource.CacheGlobalData( RegisterClipboardFormat(CFSTR_FILEDESCRIPTOR), hFileDescriptor, &etcDescriptor );

	FORMATETC etcContents = {RegisterClipboardFormat(CFSTR_FILECONTENTS), NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
	dragDataSource.DelayRenderFileData(RegisterClipboardFormat(CFSTR_FILECONTENTS), &etcContents);

	DROPEFFECT dwEffect = dragDataSource.DoDragDrop( DROPEFFECT_COPY | DROPEFFECT_MOVE );
	if(dwEffect == DROPEFFECT_NONE )
	{
		GlobalFree( hFileDescriptor );
	} 

	CIOSDirectoryTree::m_askIsTransPng = true;
	CIOSDirectoryTree::m_askIsTransPlist = true;
	*pResult = 0;
}
Example #3
0
/******************************************************************
 *		WDML_ServerHandleAdvise
 *
 *
 */
static	WDML_QUEUE_STATE WDML_ServerHandleAdvise(WDML_CONV* pConv, WDML_XACT* pXAct)
{
    UINT		uType;
    WDML_LINK*		pLink;
    DDEADVISE*		pDdeAdvise;
    HDDEDATA		hDdeData = 0;
    BOOL		fAck = TRUE;

    pDdeAdvise = GlobalLock(pXAct->hMem);
    uType = XTYP_ADVSTART |
	    (pDdeAdvise->fDeferUpd ? XTYPF_NODATA : 0) |
	    (pDdeAdvise->fAckReq ? XTYPF_ACKREQ : 0);

    if (!(pConv->instance->CBFflags & CBF_FAIL_ADVISES))
    {
	hDdeData = WDML_InvokeCallback(pConv->instance, XTYP_ADVSTART, pDdeAdvise->cfFormat,
				       (HCONV)pConv, pConv->hszTopic, pXAct->hszItem, 0, 0, 0);
    }

    switch ((ULONG_PTR)hDdeData)
    {
    case 0:
	TRACE("No data returned from the Callback\n");
	fAck = FALSE;
	break;

    case (ULONG_PTR)CBR_BLOCK:
	return WDML_QS_BLOCK;

    default:
	/* billx: first to see if the link is already created. */
	pLink = WDML_FindLink(pConv->instance, (HCONV)pConv, WDML_SERVER_SIDE,
			      pXAct->hszItem, TRUE, pDdeAdvise->cfFormat);

	if (pLink != NULL)
	{
	    /* we found a link, and only need to modify it in case it changes */
	    pLink->transactionType = uType;
	}
	else
	{
	    TRACE("Adding Link with hConv %p\n", pConv);
	    WDML_AddLink(pConv->instance, (HCONV)pConv, WDML_SERVER_SIDE,
			 uType, pXAct->hszItem, pDdeAdvise->cfFormat);
	}
	break;
    }

    GlobalUnlock(pXAct->hMem);
    if (fAck)
    {
	GlobalFree(pXAct->hMem);
    }
    pXAct->hMem = 0;

    WDML_PostAck(pConv, WDML_SERVER_SIDE, 0, FALSE, fAck, pXAct->atom, pXAct->lParam, WM_DDE_ADVISE);

    WDML_DecHSZ(pConv->instance, pXAct->hszItem);

    return WDML_QS_HANDLED;
}
Example #4
0
// Here you can process the Npp Messages 
// I will make the messages accessible little by little, according to the need of plugin development.
// Please let me know if you need to access to some messages :
// http://sourceforge.net/forum/forum.php?forum_id=482781
//
extern "C" __declspec(dllexport) LRESULT messageProc(UINT Message, WPARAM wParam, LPARAM lParam)
{
	switch (Message){
		case WM_CREATE:
		hInst = GetModuleHandle(NULL);

		//Create PopupMenu Dynamically
		HGLOBAL hgbl;
		LPDLGTEMPLATE lpdt;
		LPWORD lpw;
		hwndEdit = nppData._scintillaMainHandle;
		hgbl = GlobalAlloc(GMEM_ZEROINIT, 1024);

		lpdt = (LPDLGTEMPLATE)GlobalLock(hgbl);

		// Define a dialog box.

		lpdt->style = WS_POPUP | WS_BORDER ;
		lpdt->cdit = 0;         // Number of controls = 0
		lpdt->x  = 10;  lpdt->y  = 10;
		lpdt->cx = 100; lpdt->cy = 100;

		lpw = (LPWORD)(lpdt + 1);
		*lpw++ = 0;             // No menu
		*lpw++ = 0;             // Predefined dialog box class (by default)

		GlobalUnlock(hgbl);
		hwndPopupMenu = CreateDialogIndirect(hInst,
			(LPDLGTEMPLATE)hgbl,
			nppData._nppHandle,
			(DLGPROC)PopupMenuProc);
		GlobalFree(hgbl);
		
		//End PopupMenuDialog

		hfontCurrent = MyCreateFont(nppData._nppHandle, 10,L"Zawgyi-One");
		EditProc =(WNDPROC)GetWindowLongW(nppData._scintillaMainHandle, GWL_WNDPROC);
		SetWindowLong(nppData._scintillaMainHandle, GWL_WNDPROC, (long)SubEditProc);
		hMenu = GetMenu(nppData._nppHandle);
		CheckMenuItem(hMenu,funcItem[1]._cmdID,MF_BYCOMMAND|MF_CHECKED);//Check Disable Menu
		break;
		case WM_MOVE:
			//move menu along with the main window
			if(IsWindowVisible(hwndPopupMenu))
			{
				RECT rctWinMain;
				GetWindowRect(hwndEdit,&rctWinMain);

				int height=(burmese.menuLength>MROW?10:burmese.menuLength)*MHEIGHT+MHEIGHT+10;
				int width=((burmese.menuLength/MROW)+1)*MWIDTH;

				MoveWindow (hwndPopupMenu,
					rctWinMain.left + pointEditCursor.x + 10,
					rctWinMain.top + pointEditCursor.y + 20 ,
					width,
					height,
					TRUE) ;
			}
	        
			break;
		}
	return true;
}
Example #5
0
void CJabberDlgGcJoin::OnInitDialog()
{
	CSuper::OnInitDialog();

	WindowSetIcon(m_hwnd, m_proto, "group");

	JabberGcRecentInfo *pInfo = NULL;
	if (m_jid)
		pInfo = new JabberGcRecentInfo(m_proto, m_jid);
	else if(OpenClipboard(m_hwnd)) {
		HANDLE hData = GetClipboardData(CF_UNICODETEXT);

		if (hData) {
			TCHAR *buf = (TCHAR *)GlobalLock(hData);
			if (buf && _tcschr(buf, _T('@')) && !_tcschr(buf, _T(' ')))
				pInfo = new JabberGcRecentInfo(m_proto, buf);
			GlobalUnlock(hData);
		}
		CloseClipboard();
	}

	if (pInfo) {
		pInfo->fillForm(m_hwnd);
		delete pInfo;
	}

	ptrT tszNick(m_proto->getTStringA("Nick"));
	if (tszNick == NULL)
		tszNick = JabberNickFromJID(m_proto->m_szJabberJID);
	SetDlgItemText(m_hwnd, IDC_NICK, tszNick);

	TEXTMETRIC tm = { 0 };
	HDC hdc = GetDC(m_hwnd);
	GetTextMetrics(hdc, &tm);
	ReleaseDC(m_hwnd, hdc);
	sttTextLineHeight = tm.tmHeight;
	SendDlgItemMessage(m_hwnd, IDC_ROOM, CB_SETITEMHEIGHT, -1, sttTextLineHeight - 1);

	LOGFONT lf = { 0 };
	HFONT hfnt = (HFONT)SendDlgItemMessage(m_hwnd, IDC_TXT_RECENT, WM_GETFONT, 0, 0);
	GetObject(hfnt, sizeof(lf), &lf);
	lf.lfWeight = FW_BOLD;
	SendDlgItemMessage(m_hwnd, IDC_TXT_RECENT, WM_SETFONT, (WPARAM)CreateFontIndirect(&lf), TRUE);

	SendDlgItemMessage(m_hwnd, IDC_BOOKMARKS, BM_SETIMAGE, IMAGE_ICON, (LPARAM)m_proto->LoadIconEx("bookmarks"));
	SendDlgItemMessage(m_hwnd, IDC_BOOKMARKS, BUTTONSETASFLATBTN, TRUE, 0);
	SendDlgItemMessage(m_hwnd, IDC_BOOKMARKS, BUTTONADDTOOLTIP, (WPARAM)"Bookmarks", 0);
	SendDlgItemMessage(m_hwnd, IDC_BOOKMARKS, BUTTONSETASPUSHBTN, TRUE, 0);

	m_proto->ComboLoadRecentStrings(m_hwnd, IDC_SERVER, "joinWnd_rcSvr");

	int i;
	for (i = 0; i < 5; i++) {
		TCHAR jid[JABBER_MAX_JID_LEN];
		JabberGcRecentInfo info(m_proto);
		if (!info.loadRecent(i))
			break;

		mir_sntprintf(jid, _T("%[email protected]%s (%s)"), info.m_room, info.m_server, info.m_nick ? info.m_nick : TranslateT("<no nick>"));
		SetDlgItemText(m_hwnd, IDC_RECENT1 + i, jid);
	}
	sttJoinDlgShowRecentItems(m_hwnd, i);
}
Example #6
0
static void test_PrintDlgExW(void)
{
    PRINTPAGERANGE pagerange[2];
    LPPRINTDLGEXW pDlg;
    DEVNAMES *dn;
    HRESULT res;

    /* PrintDlgEx not present before w2k */
    if (!pPrintDlgExW) {
        skip("PrintDlgExW not available\n");
        return;
    }

    /* Set CommDlgExtendedError != 0 */
    PrintDlg(NULL);
    SetLastError(0xdeadbeef);
    res = pPrintDlgExW(NULL);
    ok( (res == E_INVALIDARG),
        "got 0x%x with %u and %u (expected 'E_INVALIDARG')\n",
        res, GetLastError(), CommDlgExtendedError());


    pDlg = HeapAlloc(GetProcessHeap(), 0, (sizeof(PRINTDLGEXW)) + 8);
    if (!pDlg) return;

    /* lStructSize must be exact */
    ZeroMemory(pDlg, sizeof(PRINTDLGEXW));
    pDlg->lStructSize = sizeof(PRINTDLGEXW) - 1;
    PrintDlg(NULL);
    SetLastError(0xdeadbeef);
    res = pPrintDlgExW(pDlg);
    ok( (res == E_INVALIDARG),
        "got 0x%x with %u and %u (expected 'E_INVALIDARG')\n",
        res, GetLastError(), CommDlgExtendedError());


    ZeroMemory(pDlg, sizeof(PRINTDLGEXW));
    pDlg->lStructSize = sizeof(PRINTDLGEXW) + 1;
    PrintDlg(NULL);
    SetLastError(0xdeadbeef);
    res = pPrintDlgExW(pDlg);
    ok( (res == E_INVALIDARG),
        "got 0x%x with %u and %u (expected 'E_INVALIDARG')\n",
        res, GetLastError(), CommDlgExtendedError());


    ZeroMemory(pDlg, sizeof(PRINTDLGEXW));
    pDlg->lStructSize = sizeof(PRINTDLGEXW);
    SetLastError(0xdeadbeef);
    res = pPrintDlgExW(pDlg);
    ok( (res == E_HANDLE),
        "got 0x%x with %u and %u (expected 'E_HANDLE')\n",
        res, GetLastError(), CommDlgExtendedError());

    /* nStartPage must be START_PAGE_GENERAL for the general page or a valid property sheet index */
    ZeroMemory(pDlg, sizeof(PRINTDLGEXW));
    pDlg->lStructSize = sizeof(PRINTDLGEXW);
    pDlg->hwndOwner = GetDesktopWindow();
    pDlg->Flags = PD_RETURNDEFAULT | PD_NOWARNING | PD_NOPAGENUMS;
    res = pPrintDlgExW(pDlg);
    ok((res == E_INVALIDARG), "got 0x%x (expected 'E_INVALIDARG')\n", res);

    /* Use PD_NOPAGENUMS or set nMaxPageRanges and lpPageRanges */
    ZeroMemory(pDlg, sizeof(PRINTDLGEXW));
    pDlg->lStructSize = sizeof(PRINTDLGEXW);
    pDlg->hwndOwner = GetDesktopWindow();
    pDlg->Flags = PD_RETURNDEFAULT | PD_NOWARNING;
    pDlg->nStartPage = START_PAGE_GENERAL;
    res = pPrintDlgExW(pDlg);
    ok((res == E_INVALIDARG), "got 0x%x (expected 'E_INVALIDARG')\n", res);

    /* this is invalid: a valid lpPageRanges with 0 for nMaxPageRanges */
    ZeroMemory(pDlg, sizeof(PRINTDLGEXW));
    pDlg->lStructSize = sizeof(PRINTDLGEXW);
    pDlg->hwndOwner = GetDesktopWindow();
    pDlg->Flags = PD_RETURNDEFAULT | PD_NOWARNING;
    pDlg->lpPageRanges = pagerange;
    pDlg->nStartPage = START_PAGE_GENERAL;
    res = pPrintDlgExW(pDlg);
    ok((res == E_INVALIDARG), "got 0x%x (expected 'E_INVALIDARG')\n", res);

    /* this is invalid: NULL for lpPageRanges with a valid nMaxPageRanges */
    ZeroMemory(pDlg, sizeof(PRINTDLGEXW));
    pDlg->lStructSize = sizeof(PRINTDLGEXW);
    pDlg->hwndOwner = GetDesktopWindow();
    pDlg->Flags = PD_RETURNDEFAULT | PD_NOWARNING;
    pDlg->nMaxPageRanges = 1;
    pDlg->nStartPage = START_PAGE_GENERAL;
    res = pPrintDlgExW(pDlg);
    ok((res == E_INVALIDARG), "got 0x%x (expected 'E_INVALIDARG')\n", res);

    /* this works: lpPageRanges with a valid nMaxPageRanges */
    ZeroMemory(pDlg, sizeof(PRINTDLGEXW));
    pDlg->lStructSize = sizeof(PRINTDLGEXW);
    pDlg->hwndOwner = GetDesktopWindow();
    pDlg->Flags = PD_RETURNDEFAULT | PD_NOWARNING;
    pDlg->nMaxPageRanges = 1;
    pDlg->lpPageRanges = pagerange;
    pDlg->nStartPage = START_PAGE_GENERAL;
    res = pPrintDlgExW(pDlg);
    if (res == E_FAIL)
    {
        skip("No printer configured.\n");
        HeapFree(GetProcessHeap(), 0, pDlg);
        return;
    }

    ok(res == S_OK, "got 0x%x (expected S_OK)\n", res);

    dn = GlobalLock(pDlg->hDevNames);
    ok(dn != NULL, "expected '!= NULL' for GlobalLock(%p)\n",pDlg->hDevNames);
    if (dn)
    {
        ok(dn->wDriverOffset, "(expected '!= 0' for wDriverOffset)\n");
        ok(dn->wDeviceOffset, "(expected '!= 0' for wDeviceOffset)\n");
        ok(dn->wOutputOffset, "(expected '!= 0' for wOutputOffset)\n");
        ok(dn->wDefault == DN_DEFAULTPRN, "got 0x%x (expected DN_DEFAULTPRN)\n", dn->wDefault);

        GlobalUnlock(pDlg->hDevNames);
    }
    GlobalFree(pDlg->hDevMode);
    GlobalFree(pDlg->hDevNames);

    /* this works also: PD_NOPAGENUMS */
    ZeroMemory(pDlg, sizeof(PRINTDLGEXW));
    pDlg->lStructSize = sizeof(PRINTDLGEXW);
    pDlg->hwndOwner = GetDesktopWindow();
    pDlg->Flags = PD_RETURNDEFAULT | PD_NOWARNING | PD_NOPAGENUMS;
    pDlg->nStartPage = START_PAGE_GENERAL;
    res = pPrintDlgExW(pDlg);
    ok(res == S_OK, "got 0x%x (expected S_OK)\n", res);
    GlobalFree(pDlg->hDevMode);
    GlobalFree(pDlg->hDevNames);

    /* this works: PD_RETURNDC with PD_RETURNDEFAULT */
    ZeroMemory(pDlg, sizeof(PRINTDLGEXW));
    pDlg->lStructSize = sizeof(PRINTDLGEXW);
    pDlg->hwndOwner = GetDesktopWindow();
    pDlg->Flags = PD_RETURNDEFAULT | PD_NOWARNING | PD_NOPAGENUMS | PD_RETURNDC;
    pDlg->nStartPage = START_PAGE_GENERAL;
    res = pPrintDlgExW(pDlg);
    ok(res == S_OK, "got 0x%x (expected S_OK)\n", res);
    ok(pDlg->hDC != NULL, "HDC missing for PD_RETURNDC\n");
    GlobalFree(pDlg->hDevMode);
    GlobalFree(pDlg->hDevNames);
    DeleteDC(pDlg->hDC);

    /* this works: PD_RETURNIC with PD_RETURNDEFAULT */
    ZeroMemory(pDlg, sizeof(PRINTDLGEXW));
    pDlg->lStructSize = sizeof(PRINTDLGEXW);
    pDlg->hwndOwner = GetDesktopWindow();
    pDlg->Flags = PD_RETURNDEFAULT | PD_NOWARNING | PD_NOPAGENUMS | PD_RETURNIC;
    pDlg->nStartPage = START_PAGE_GENERAL;
    res = pPrintDlgExW(pDlg);
    ok(res == S_OK, "got 0x%x (expected S_OK)\n", res);
    ok(pDlg->hDC != NULL, "HDC missing for PD_RETURNIC\n");
    GlobalFree(pDlg->hDevMode);
    GlobalFree(pDlg->hDevNames);
    DeleteDC(pDlg->hDC);

    HeapFree(GetProcessHeap(), 0, pDlg);
    return;

}
Example #7
0
void CAboutDlg::OnCopyToClipboard()
{
    CStringW info = m_appname + _T("\r\n");
    info += CString(_T('-'), m_appname.GetLength()) + _T("\r\n\r\n");
    info += _T("Build information:\r\n");
    info += _T("    Version:            ") + m_strBuildNumber + _T("\r\n");
    info += _T("    Compiler:           ") + m_MPCCompiler + _T("\r\n");
    info += _T("    Build date:         ") + m_buildDate + _T("\r\n\r\n");
#ifndef MPCHC_LITE
    info += _T("LAV Filters:\r\n");
    info += _T("    LAV Splitter:       ") + CFGFilterLAV::GetVersion(CFGFilterLAV::SPLITTER) + _T("\r\n");
    info += _T("    LAV Video:          ") + CFGFilterLAV::GetVersion(CFGFilterLAV::VIDEO_DECODER) + _T("\r\n");
    info += _T("    LAV Audio:          ") + CFGFilterLAV::GetVersion(CFGFilterLAV::AUDIO_DECODER) + _T("\r\n");
    info += _T("    FFmpeg compiler:    ") + VersionInfo::GetGCCVersion() + _T("\r\n\r\n");
#endif
    info += _T("Operating system:\r\n");
    info += _T("    Name:               ") + m_OSName + _T("\r\n");
    info += _T("    Version:            ") + m_OSVersion + _T("\r\n\r\n");

    info += _T("Hardware:\r\n");

    CRegKey key;
    if (key.Open(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0"), KEY_READ) == ERROR_SUCCESS) {
        ULONG nChars = 0;
        if (key.QueryStringValue(_T("ProcessorNameString"), nullptr, &nChars) == ERROR_SUCCESS) {
            CString cpuName;
            if (key.QueryStringValue(_T("ProcessorNameString"), cpuName.GetBuffer(nChars), &nChars) == ERROR_SUCCESS) {
                cpuName.ReleaseBuffer(nChars);
                cpuName.Trim();
                info.AppendFormat(_T("    CPU:                %s\r\n"), cpuName);
            }
        }
    }

    if (CComPtr<IDirect3D9> pD3D9 = Direct3DCreate9(D3D_SDK_VERSION)) {
        for (UINT adapter = 0, adapterCount = pD3D9->GetAdapterCount(); adapter < adapterCount; adapter++) {
            D3DADAPTER_IDENTIFIER9 adapterIdentifier;
            if (pD3D9->GetAdapterIdentifier(adapter, 0, &adapterIdentifier) == D3D_OK) {
                CString deviceName = adapterIdentifier.Description;
                deviceName.Trim();

                if (adapterCount > 1) {
                    info.AppendFormat(_T("    GPU%u:               %s"), adapter + 1, deviceName);
                } else {
                    info.AppendFormat(_T("    GPU:                %s"), deviceName);
                }
                if (adapterIdentifier.DriverVersion.QuadPart) {
                    info.AppendFormat(_T(" (driver version: %s)"),
                                      FileVersionInfo::FormatVersionString(adapterIdentifier.DriverVersion.LowPart, adapterIdentifier.DriverVersion.HighPart));
                }
                info += _T("\r\n");
            }
        }
    }

    // Allocate a global memory object for the text
    int len = info.GetLength() + 1;
    HGLOBAL hGlob = GlobalAlloc(GMEM_MOVEABLE, len * sizeof(WCHAR));
    if (hGlob) {
        // Lock the handle and copy the text to the buffer
        LPVOID pData = GlobalLock(hGlob);
        if (pData) {
            wcscpy_s((WCHAR*)pData, len, (LPCWSTR)info);
            GlobalUnlock(hGlob);

            if (GetParent()->OpenClipboard()) {
                // Place the handle on the clipboard, if the call succeeds
                // the system will take care of the allocated memory
                if (::EmptyClipboard() && ::SetClipboardData(CF_UNICODETEXT, hGlob)) {
                    hGlob = nullptr;
                }

                ::CloseClipboard();
            }
        }

        if (hGlob) {
            GlobalFree(hGlob);
        }
    }
}
Example #8
0
HANDLE ReadDIBFile(int hFile)
{
   BITMAPFILEHEADER bmfHeader;
   DWORD dwBitsSize;
   UINT nNumColors;   // Number of colors in table
   HANDLE hDIB;        
   HANDLE hDIBtmp;    // Used for GlobalRealloc() //MPB
   LPBITMAPINFOHEADER lpbi;
   DWORD offBits;

   /*
    * get length of DIB in bytes for use when reading
    */

   dwBitsSize = filelength(hFile);

   // Allocate memory for header & color table.	We'll enlarge this
   // memory as needed.

   hDIB = GlobalAlloc(GMEM_MOVEABLE,
       (DWORD)(sizeof(BITMAPINFOHEADER) + 256 * sizeof(RGBQUAD)));
   
   if (!hDIB) return NULL;

   lpbi = (LPBITMAPINFOHEADER)GlobalLock(hDIB);
   if (!lpbi) 
   {
     GlobalFree(hDIB);
     return NULL;
   }

   // read the BITMAPFILEHEADER from our file

   if (sizeof (BITMAPFILEHEADER) != _lread (hFile, (LPSTR)&bmfHeader, sizeof (BITMAPFILEHEADER)))
     goto ErrExit;

   if (bmfHeader.bfType != 0x4d42)	/* 'BM' */
     goto ErrExit;

   // read the BITMAPINFOHEADER

   if (sizeof(BITMAPINFOHEADER) != _lread (hFile, (LPSTR)lpbi, sizeof(BITMAPINFOHEADER)))
     goto ErrExit;

   // Check to see that it's a Windows DIB -- an OS/2 DIB would cause
   // strange problems with the rest of the DIB API since the fields
   // in the header are different and the color table entries are
   // smaller.
   //
   // If it's not a Windows DIB (e.g. if biSize is wrong), return NULL.

   if (lpbi->biSize == sizeof(BITMAPCOREHEADER))
     goto ErrExit;

   // Now determine the size of the color table and read it.  Since the
   // bitmap bits are offset in the file by bfOffBits, we need to do some
   // special processing here to make sure the bits directly follow
   // the color table (because that's the format we are susposed to pass
   // back)

   if (!(nNumColors = (UINT)lpbi->biClrUsed))
    {
      // no color table for 24-bit, default size otherwise
      if (lpbi->biBitCount != 24)
        nNumColors = 1 << lpbi->biBitCount; /* standard size table */
    }

   // fill in some default values if they are zero
   if (lpbi->biClrUsed == 0)
     lpbi->biClrUsed = nNumColors;

   if (lpbi->biSizeImage == 0)
   {
     lpbi->biSizeImage = ((((lpbi->biWidth * (DWORD)lpbi->biBitCount) + 31) & ~31) >> 3)
			 * lpbi->biHeight;
   }
Example #9
0
void OnMenuPrint(WindowInfo *win, bool waitForCompletion) {
    // we remember some printer settings per process
    static ScopedMem<DEVMODE> defaultDevMode;
    static PrintScaleAdv defaultScaleAdv = PrintScaleShrink;

    static bool hasDefaults = false;
    if (!hasDefaults) {
        hasDefaults = true;
        if (str::EqI(gGlobalPrefs->printerDefaults.printScale, "fit"))
            defaultScaleAdv = PrintScaleFit;
        else if (str::EqI(gGlobalPrefs->printerDefaults.printScale, "none"))
            defaultScaleAdv = PrintScaleNone;
    }

    bool printSelection = false;
    Vec<PRINTPAGERANGE> ranges;
    PRINTER_INFO_2 printerInfo = { 0 };

    //if (!HasPermission(Perm_PrinterAccess))
    //    return;
    if (!win->IsDocLoaded())
        return;

    if (win->AsChm()) {
        // the Print dialog allows access to the file system, so fall back
        // to printing the entire document without dialog if that isn't desired
        bool showUI = HasPermission(Perm_DiskAccess);
        win->AsChm()->PrintCurrentPage(showUI);
        return;
    }
    if (win->AsEbook()) {
        // TODO: use EbookEngine for printing?
        return;
    }

    CrashIf(!win->AsFixed());
    if (!win->AsFixed())
        return;
    DisplayModel *dm = win->AsFixed();

#ifndef DISABLE_DOCUMENT_RESTRICTIONS
    if (!dm->GetEngine()->AllowsPrinting())
        return;
#endif

    if (win->printThread) {
        int res = MessageBox(
            win->hwndFrame, _TR("Printing is still in progress. Abort and start over?"),
            _TR("Printing in progress."), MB_ICONEXCLAMATION | MB_YESNO | MbRtlReadingMaybe());
        if (res == IDNO)
            return;
    }
    AbortPrinting(win);

    // the Print dialog allows access to the file system, so fall back
    // to printing the entire document without dialog if that isn't desired
    if (!HasPermission(Perm_DiskAccess)) {
        PrintFile(dm->GetEngine());
        return;
    }

    PRINTDLGEX pd;
    ZeroMemory(&pd, sizeof(PRINTDLGEX));
    pd.lStructSize = sizeof(PRINTDLGEX);
    pd.hwndOwner = win->hwndFrame;
    pd.Flags = PD_USEDEVMODECOPIESANDCOLLATE | PD_COLLATE;
    if (!win->currentTab->selectionOnPage)
        pd.Flags |= PD_NOSELECTION;
    pd.nCopies = 1;
    /* by default print all pages */
    pd.nPageRanges = 1;
    pd.nMaxPageRanges = MAXPAGERANGES;
    PRINTPAGERANGE *ppr = AllocArray<PRINTPAGERANGE>(MAXPAGERANGES);
    pd.lpPageRanges = ppr;
    ppr->nFromPage = 1;
    ppr->nToPage = dm->PageCount();
    pd.nMinPage = 1;
    pd.nMaxPage = dm->PageCount();
    pd.nStartPage = START_PAGE_GENERAL;

    Print_Advanced_Data advanced(PrintRangeAll, defaultScaleAdv);
    ScopedMem<DLGTEMPLATE> dlgTemplate; // needed for RTL languages
    HPROPSHEETPAGE hPsp = CreatePrintAdvancedPropSheet(&advanced, dlgTemplate);
    pd.lphPropertyPages = &hPsp;
    pd.nPropertyPages = 1;

    LPDEVNAMES devNames;
    LPDEVMODE devMode;
    bool failedEngineClone;
    PrintData *data = nullptr;

    // restore remembered settings
    if (defaultDevMode) {
        DEVMODE *p = defaultDevMode.Get();
        pd.hDevMode = GlobalMemDup(p, p->dmSize + p->dmDriverExtra);
    }

    if (PrintDlgEx(&pd) != S_OK) {
        if (CommDlgExtendedError() != 0) {
            /* if PrintDlg was cancelled then
               CommDlgExtendedError is zero, otherwise it returns the
               error code, which we could look at here if we wanted.
               for now just warn the user that printing has stopped
               becasue of an error */
            MessageBoxWarning(win->hwndFrame, _TR("Couldn't initialize printer"),
                              _TR("Printing problem."));
        }
        goto Exit;
    }

    if (pd.dwResultAction == PD_RESULT_PRINT || pd.dwResultAction == PD_RESULT_APPLY) {
        // remember settings for this process
        devMode = (LPDEVMODE)GlobalLock(pd.hDevMode);
        if (devMode) {
            defaultDevMode.Set(
                (LPDEVMODE)memdup(devMode, devMode->dmSize + devMode->dmDriverExtra));
            GlobalUnlock(pd.hDevMode);
        }
        defaultScaleAdv = advanced.scale;
    }

    if (pd.dwResultAction != PD_RESULT_PRINT)
        goto Exit;

    if (pd.Flags & PD_CURRENTPAGE) {
        PRINTPAGERANGE pr = { (DWORD)dm->CurrentPageNo(), (DWORD)dm->CurrentPageNo() };
        ranges.Append(pr);
    } else if (win->currentTab->selectionOnPage && (pd.Flags & PD_SELECTION)) {
        printSelection = true;
    } else if (!(pd.Flags & PD_PAGENUMS)) {
        PRINTPAGERANGE pr = { 1, (DWORD)dm->PageCount() };
        ranges.Append(pr);
    } else {
        assert(pd.nPageRanges > 0);
        for (DWORD i = 0; i < pd.nPageRanges; i++)
            ranges.Append(pd.lpPageRanges[i]);
    }

    devNames = (LPDEVNAMES)GlobalLock(pd.hDevNames);
    devMode = (LPDEVMODE)GlobalLock(pd.hDevMode);
    if (devNames) {
        printerInfo.pDriverName = (LPWSTR)devNames + devNames->wDriverOffset;
        printerInfo.pPrinterName = (LPWSTR)devNames + devNames->wDeviceOffset;
        printerInfo.pPortName = (LPWSTR)devNames + devNames->wOutputOffset;
    }
    data =
        new PrintData(dm->GetEngine(), &printerInfo, devMode, ranges, advanced, dm->GetRotation(),
                      printSelection ? win->currentTab->selectionOnPage : nullptr);
    if (devNames)
        GlobalUnlock(pd.hDevNames);
    if (devMode)
        GlobalUnlock(pd.hDevMode);

    // if a file is missing and the engine can't thus be cloned,
    // we print using the original engine on the main thread
    // so that the document can't be closed and the original engine
    // unexpectedly deleted
    // TODO: instead prevent closing the document so that printing
    // can still happen on a separate thread and be interruptible
    failedEngineClone = dm->GetEngine() && !data->engine;
    if (failedEngineClone)
        data->engine = dm->GetEngine();

    if (!waitForCompletion && !failedEngineClone)
        PrintToDeviceOnThread(win, data);
    else {
        PrintToDevice(*data);
        if (failedEngineClone)
            data->engine = nullptr;
        delete data;
    }

Exit:
    free(ppr);
    GlobalFree(pd.hDevNames);
    GlobalFree(pd.hDevMode);
}
Example #10
0
/*************************************
*
*  Unregister all TwinView menus
*  associated with a given window.
*
**************************************/
void __far __pascal DeleteMenuInfoForWnd( HWND hWnd )
{
    FPTVMENUINFO fpMenuInfo, fpLastMenuInfo;
    HTVMENUINFO hMenuInfo, hLastMenuInfo, hTmpMenuInfo;
    HTVMENUINFO __far * hFirstMenuInfo;

    BOOL bFirst = TRUE;


    /* Get top of menu list. */
    hFirstMenuInfo = (HTVMENUINFO __far *) &hTVMenuList;

    /* Existing first node. */
    if( *hFirstMenuInfo == 0 ) return;

    /* Point to first node in list. */
    hMenuInfo = *hFirstMenuInfo;

    /*
    ** Process first node if associated
    ** with the hWnd.
    */

    while( bFirst && hMenuInfo != 0 )
    {
        /* Lock current node. */
        fpMenuInfo = (FPTVMENUINFO) GlobalLock( hMenuInfo ) ;

        /* If found the correct window handle. */
        if( fpMenuInfo->hWnd == hWnd )
        {
            /* Remove the menu item from menu. */
            DeleteMenu( GetTVMenuHandle(), fpMenuInfo->wParamAlias, MF_BYCOMMAND );
            DrawMenuBar( GetTVWindowHandle());

            /* Next node is to be new top node. */
            hTmpMenuInfo = fpMenuInfo->Next;

            /* Unlock top handle. */
            GlobalUnlock( hMenuInfo );

            /* Free top. */
            FreeMenuInfo( hMenuInfo );

            /* Assign new top. */
            *hFirstMenuInfo = hMenuInfo = hTmpMenuInfo;

        }

        /* Thru processing top node. */
        else bFirst = FALSE;
    }

    /* Empty list now? */
    if( hMenuInfo == 0 ) return;


    /*
    ** Go thru rest of nodes and
    ** delete any associated with the hWnd.
    */

    /* Last node is top node. */
    hLastMenuInfo = hMenuInfo;

    /* Lock top node. */
    fpMenuInfo = (FPTVMENUINFO) GlobalLock( hMenuInfo ) ;

    /* Assign Next node to temp. */
    hTmpMenuInfo = fpMenuInfo->Next;

    /* Unlock top handle. */
    GlobalUnlock( hMenuInfo );

    /* New current node. */
    hMenuInfo = hTmpMenuInfo;


    while( hMenuInfo != 0 )
    {
        /* Lock current node. */
        fpMenuInfo = (FPTVMENUINFO) GlobalLock( hMenuInfo ) ;

        /* If found the correct window handle. */
        if( fpMenuInfo->hWnd == hWnd )
        {
            /* Remove the menu item from menu. */
            DeleteMenu( GetTVMenuHandle(), fpMenuInfo->wParamAlias, MF_BYCOMMAND );
            DrawMenuBar( GetTVWindowHandle());

            /* Lock previous node. */
            fpLastMenuInfo = (FPTVMENUINFO) GlobalLock( hLastMenuInfo ) ;

            /* Previous node's "next node" is deleted node's "next node". */
            fpLastMenuInfo->Next = fpMenuInfo->Next;

            /* Unlock current node. */
            GlobalUnlock( hMenuInfo );

            /* Free node. */
            FreeMenuInfo( hMenuInfo );

            /* Next node now current node. */
            hMenuInfo = fpLastMenuInfo->Next;

            /* Unlock previous node. */
            GlobalUnlock( hLastMenuInfo );

        }

        /* Not the correct window. */
        else
        {
            /* Unlock it. */
            GlobalUnlock( hMenuInfo ) ;

            /* Get next node. */
            hLastMenuInfo = hMenuInfo;
            hMenuInfo = GetNextMenuInfo( hMenuInfo );
        }
    }
}
Example #11
0
WORD FAR SaveDIB(HDIB hDib, LPSTR lpFileName)
{
   BITMAPFILEHEADER bmfHdr; // Header for Bitmap file
   LPBITMAPINFOHEADER lpBI;   // Pointer to DIB info structure
   int fh;     // file handle for opened file
   OFSTRUCT of;     // OpenFile structure
   DWORD dwDIBSize;
   DWORD dwError;   // Error return from MyWrite

   if (!hDib)
      return ERR_INVALIDHANDLE;
   fh = OpenFile(lpFileName, &of, OF_CREATE | OF_READWRITE);
   if (fh == -1)
      return ERR_OPEN;

   /*
    * Get a pointer to the DIB memory, the first of which contains
    * a BITMAPINFO structure
    */
   lpBI = (LPBITMAPINFOHEADER)GlobalLock(hDib);
   if (!lpBI)
      return ERR_LOCK;

   // Check to see if we're dealing with an OS/2 DIB.  If so, don't
   // save it because our functions aren't written to deal with these
   // DIBs.

   if (lpBI->biSize != sizeof(BITMAPINFOHEADER))
   {
     GlobalUnlock(hDib);
     return ERR_NOT_DIB;
   }

   /*
    * Fill in the fields of the file header
    */

   /* Fill in file type (first 2 bytes must be "BM" for a bitmap) */
   bmfHdr.bfType = DIB_HEADER_MARKER;  // "BM"

   // Calculating the size of the DIB is a bit tricky (if we want to
   // do it right).  The easiest way to do this is to call GlobalSize()
   // on our global handle, but since the size of our global memory may have
   // been padded a few bytes, we may end up writing out a few too
   // many bytes to the file (which may cause problems with some apps,
   // like HC 3.0).
   //
   // So, instead let's calculate the size manually.
   //
   // To do this, find size of header plus size of color table.  Since the
   // first DWORD in both BITMAPINFOHEADER and BITMAPCOREHEADER conains
   // the size of the structure, let's use this.

   dwDIBSize = *(LPDWORD)lpBI + PaletteSize((LPSTR)lpBI);  // Partial Calculation

   // Now calculate the size of the image

   if ((lpBI->biCompression == BI_RLE8) || (lpBI->biCompression == BI_RLE4)) {

      // It's an RLE bitmap, we can't calculate size, so trust the
      // biSizeImage field

      dwDIBSize += lpBI->biSizeImage;
      }
   else {
      DWORD dwBmBitsSize;  // Size of Bitmap Bits only

      // It's not RLE, so size is Width (DWORD aligned) * Height

      dwBmBitsSize = WIDTHBYTES((lpBI->biWidth)*((DWORD)lpBI->biBitCount)) * lpBI->biHeight;

      dwDIBSize += dwBmBitsSize;
      
      // Now, since we have calculated the correct size, why don't we
      // fill in the biSizeImage field (this will fix any .BMP files which 
      // have this field incorrect).

      lpBI->biSizeImage = dwBmBitsSize;
      }


   // Calculate the file size by adding the DIB size to sizeof(BITMAPFILEHEADER)
                   
   bmfHdr.bfSize = dwDIBSize + sizeof(BITMAPFILEHEADER);
   bmfHdr.bfReserved1 = 0;
   bmfHdr.bfReserved2 = 0;

   /*
    * Now, calculate the offset the actual bitmap bits will be in
    * the file -- It's the Bitmap file header plus the DIB header,
    * plus the size of the color table.
    */
   bmfHdr.bfOffBits = (DWORD)sizeof(BITMAPFILEHEADER) + lpBI->biSize +
                      PaletteSize((LPSTR)lpBI);

   /* Write the file header */
   _lwrite(fh, (LPSTR)&bmfHdr, sizeof(BITMAPFILEHEADER));

   /*
    * Write the DIB header and the bits -- use local version of
    * MyWrite, so we can write more than 32767 bytes of data
    */
   dwError = MyWrite(fh, (LPSTR)lpBI, dwDIBSize);
   GlobalUnlock(hDib);
   _lclose(fh);

   if (dwError == 0)
     return ERR_OPEN; // oops, something happened in the write
   else
     return 0; // Success code
}
Example #12
0
/*************************************
*
*  Remove and free a menu info. structure
*  from a menu info. list.
*
**************************************/
BOOL __far __pascal DeleteMenuInfoForAlias( HTVMENUINFO __far * hFirstMenuInfo, WORD wParamAlias  )
{
    FPTVMENUINFO fpMenuInfo, fpTmpMenuInfo;
    HTVMENUINFO hMenuInfo, hTmpMenuInfo;


    /* Existing first node. */
    if( *hFirstMenuInfo == 0 ) return FALSE;

    /* Lock top handle. */
    fpMenuInfo = (FPTVMENUINFO) GlobalLock( *hFirstMenuInfo ) ;

    /* If deleting top node. */
    if( fpMenuInfo->wParamAlias == wParamAlias )
    {
        /* Remove the menu item from menu. */
        DeleteMenu( GetTVMenuHandle(), fpMenuInfo->wParamAlias, MF_BYCOMMAND );
        DrawMenuBar( GetTVWindowHandle());

        /* Next node is to be new top node. */
        hTmpMenuInfo = fpMenuInfo->Next;

        /* Unlock top handle. */
        GlobalUnlock( *hFirstMenuInfo );

        /* Free top. */
        FreeMenuInfo( *hFirstMenuInfo );

        /* Assign new top. */
        *hFirstMenuInfo = hTmpMenuInfo;

        /* Success. */
        return TRUE;
    }

    /* Unlock top handle. */
    GlobalUnlock( *hFirstMenuInfo );

    /* Find correct node and remove. */
    hTmpMenuInfo = *hFirstMenuInfo;
    hMenuInfo = GetNextMenuInfo( *hFirstMenuInfo );

    while( hMenuInfo != 0 )
    {
        /* Lock current node. */
        fpMenuInfo = (FPTVMENUINFO) GlobalLock( hMenuInfo ) ;

        /* If deleting current node. */
        if( fpMenuInfo->wParamAlias == wParamAlias )
        {
            /* Remove the menu item from menu. */
            DeleteMenu( GetTVMenuHandle(), fpMenuInfo->wParamAlias, MF_BYCOMMAND );
            DrawMenuBar( GetTVWindowHandle());

            /* Lock previous node. */
            fpTmpMenuInfo = (FPTVMENUINFO) GlobalLock( hTmpMenuInfo ) ;

            /* Previous node's "next node" is deleted node's "next node". */
            fpTmpMenuInfo->Next = fpMenuInfo->Next;

            /* Unlock previous node. */
            GlobalUnlock( hTmpMenuInfo );

            /* Unlock current node. */
            GlobalUnlock( hMenuInfo );

            /* Free top. */
            FreeMenuInfo( hMenuInfo );

            /* Success. */
            return TRUE;
        }

        /* Unlock it. */
        GlobalUnlock( hMenuInfo ) ;

        /* Get next node. */
        hTmpMenuInfo = hMenuInfo;
        hMenuInfo = GetNextMenuInfo( hMenuInfo );
    }

    /* Did not find menu. */
    return FALSE;
}
Example #13
0
static WAVEHDR* outPrePrep(int n, DWORD bufLen)
{
#ifdef RTL_ENABLED
   RTL_EVENT("SpeakerThreadWnt.outPrePrep", 1);
#endif

   WAVEHDR* pWH;
   int doAlloc = (hOutHdr[n] == NULL);
   MpBufferMsg* msg;
   MpBufferMsg* pFlush;
   MpAudioBufPtr ob;

   static int oPP = 0;

   static int flushes = 0;
   static int skip = 0;

   assert((n > -1) && (n < N_OUT_BUFFERS));

#ifdef DEBUG_WINDOZE /* [ */
   if (1) {
      static int spkQLen[1024];
      int in = oPP % 1024;
      int i, j;

      spkQLen[in] = MpMisc.pSpkQ->numMsgs();
      if (in == 1023) {
         osPrintf("\n\n Speaker Queue lengths [%d,%d]:\n  ", oPP, frameCount);
         for (i=0; i<1024; i+=32) {
            for (j=i; j<(i+32); j++) {
               osPrintf("%3d", spkQLen[j]);
            }
            osPrintf("\n  ");
         }
         osPrintf("\n\n");
      }
   }
#endif /* DEBUG_WINDOZE ] */

   oPP++;

#ifdef DEBUG_WINDOZE /* [ */
   if (0 && (0 == (oPP % 1000))) {
      osPrintf("outPrePrep(): %d playbacks, %d flushes\n", oPP, flushes);
   }
#endif /* DEBUG_WINDOZE ] */
   while (MpMisc.pSpkQ && MpMisc.pSpkQ->numMsgs() > MprToSpkr::MAX_SPKR_BUFFERS) {
      OsStatus  res;
      flushes++;
      res = MpMisc.pSpkQ->receive((OsMsg*&) pFlush, OsTime::NO_WAIT_TIME);
      if (OS_SUCCESS == res) {
         pFlush->releaseMsg();
      } else {
         osPrintf("DmaTask: queue was full, now empty (4)!"
            " (res=%d)\n", res);
      }
      if (flushes > 100) {
         osPrintf("outPrePrep(): %d playbacks, %d flushes\n", oPP, flushes);
         flushes = 0;
      }
   }

   if (MpMisc.pSpkQ) {
      if (  (skip == 0)
         && (MpMisc.pSpkQ->numMsgs() < MprToSpkr::MIN_SPKR_BUFFERS))
      {
         skip = MprToSpkr::SKIP_SPKR_BUFFERS;
         assert(MprToSpkr::MAX_SPKR_BUFFERS >= skip);
#ifdef DEBUG_WINDOZE /* [ */
         osPrintf("Skip(%d,%d)\n", skip, oPP);
#endif /* DEBUG_WINDOZE ] */
      }

      if (MpMisc.pSpkQ->numMsgs() >= skip)
      {
         skip = 0;
         if (MpMisc.pSpkQ->receive((OsMsg*&)msg, OsTime::NO_WAIT_TIME) == OS_SUCCESS)
         {
            ob = (MpAudioBufPtr)(msg->getBuffer());
            msg->releaseMsg();
         }
//         osPrintf("pSpkQ message received\n");
      } else {
//         osPrintf("pSpkQ message skipped\n");
      }
   }

   if (!ob.isValid()) {
      ob = MpMisc.mpFgSilence;
   }

   if (doAlloc) {
      hOutHdr[n] = GlobalAlloc(GPTR, sizeof(WAVEHDR));
      assert(NULL != hOutHdr[n]);
      hOutBuf[n] = GlobalAlloc(GPTR, bufLen);
      assert(NULL != hOutBuf[n]);
   }

   pOutHdr[n] = pWH = (WAVEHDR*) GlobalLock(hOutHdr[n]);
   assert(NULL != pOutHdr[n]);
   pWH->lpData = (char*) GlobalLock(hOutBuf[n]);
   pWH->dwBufferLength = bufLen;
   pWH->dwUser = n;
   pWH->dwBytesRecorded = 0;
   pWH->dwFlags = 0;
   pWH->dwLoops = 0;
   pWH->lpNext = 0;
   pWH->reserved = 0;
   memcpy(pWH->lpData, ob->getSamplesPtr(), bufLen);

#ifdef RTL_ENABLED
   RTL_EVENT("SpeakerThreadWnt.outPrePrep", 0);
#endif
   return pWH;
}
Example #14
0
/******************************************************************************
 *      BIGBLOCKFILE_SetSize
 *
 * Sets the size of the file.
 *
 */
void BIGBLOCKFILE_SetSize(LPBIGBLOCKFILE This, ULARGE_INTEGER newSize)
{
  if (This->filesize.u.LowPart == newSize.u.LowPart)
    return;

  TRACE("from %u to %u\n", This->filesize.u.LowPart, newSize.u.LowPart);
  /*
   * unmap all views, must be done before call to SetEndFile
   *
   * Just ditch the victim list because there is no guarantee we will need them
   * and it is not worth the performance hit to unmap and remap them all.
   */
  BIGBLOCKFILE_DeleteList(This, This->victimhead);
  This->victimhead = NULL;
  This->victimtail = NULL;
  This->num_victim_pages = 0;

  BIGBLOCKFILE_UnmapAllMappedPages(This);

  if (This->fileBased)
  {
    LARGE_INTEGER newpos;

    newpos.QuadPart = newSize.QuadPart;
    if (SetFilePointerEx(This->hfile, newpos, NULL, FILE_BEGIN))
    {
        if( This->hfilemap ) CloseHandle(This->hfilemap);

        SetEndOfFile(This->hfile);

        /*
         * re-create the file mapping object
         */
        This->hfilemap = CreateFileMappingA(This->hfile,
                                            NULL,
                                            This->flProtect,
                                            0, 0,
                                            NULL);
    }
  }
  else
  {
    GlobalUnlock(This->hbytearray);

    /*
     * Resize the byte array object.
     */
    ILockBytes_SetSize(This->pLkbyt, newSize);

    /*
     * Re-acquire the handle, it may have changed.
     */
    GetHGlobalFromILockBytes(This->pLkbyt, &This->hbytearray);
    This->pbytearray = GlobalLock(This->hbytearray);
  }

  This->filesize.u.LowPart = newSize.u.LowPart;
  This->filesize.u.HighPart = newSize.u.HighPart;

  BIGBLOCKFILE_RemapAllMappedPages(This);
}
int
winClipboardFlushXEvents (HWND hwnd,
			  int iWindow,
			  Display *pDisplay,
			  Bool fUseUnicode)
{
  Atom			atomLocalProperty = XInternAtom (pDisplay,
							 WIN_LOCAL_PROPERTY,
							 False);
  Atom			atomUTF8String = XInternAtom (pDisplay,
						      "UTF8_STRING",
						      False);
  Atom			atomCompoundText = XInternAtom (pDisplay,
							"COMPOUND_TEXT",
							False);
  Atom			atomTargets = XInternAtom (pDisplay,
						   "TARGETS",
						   False);

  /* Process all pending events */
  while (XPending (pDisplay))
    {
      XTextProperty		xtpText = {0};
      XEvent			event;
      XSelectionEvent		eventSelection;
      unsigned long		ulReturnBytesLeft;
      unsigned char		*pszReturnData = NULL;
      char			*pszGlobalData = NULL;
      int			iReturn;
      HGLOBAL			hGlobal = NULL;
      XICCEncodingStyle		xiccesStyle;
      int			iConvertDataLen = 0;
      char			*pszConvertData = NULL;
      char			*pszTextList[2] = {NULL};
      int			iCount;
      char			**ppszTextList = NULL;
      wchar_t			*pwszUnicodeStr = NULL;
      int			iUnicodeLen = 0;
      int			iReturnDataLen = 0;
      int			i;
      Bool			fAbort = FALSE;
      Bool			fCloseClipboard = FALSE;
      Bool			fSetClipboardData = TRUE;

      /* Get the next event - will not block because one is ready */
      XNextEvent (pDisplay, &event);

      /* Branch on the event type */
      switch (event.type)
	{
	  /*
	   * SelectionRequest
	   */

	case SelectionRequest:
#if 0
	  {
	    char			*pszAtomName = NULL;
	    
	    ErrorF ("SelectionRequest - target %d\n",
		    event.xselectionrequest.target);
	    
	    pszAtomName = XGetAtomName (pDisplay,
					event.xselectionrequest.target);
	    ErrorF ("SelectionRequest - Target atom name %s\n", pszAtomName);
	    XFree (pszAtomName);
	    pszAtomName = NULL;
	  }
#endif

	  /* Abort if invalid target type */
	  if (event.xselectionrequest.target != XA_STRING
	      && event.xselectionrequest.target != atomUTF8String
	      && event.xselectionrequest.target != atomCompoundText
	      && event.xselectionrequest.target != atomTargets)
	    {
	      /* Abort */
	      fAbort = TRUE;
	      goto winClipboardFlushXEvents_SelectionRequest_Done;
	    }

	  /* Handle targets type of request */
	  if (event.xselectionrequest.target == atomTargets)
	    {
	      Atom atomTargetArr[] = {atomTargets,
				      atomCompoundText,
				      atomUTF8String,
				      XA_STRING};

	      /* Try to change the property */
	      iReturn = XChangeProperty (pDisplay,
					 event.xselectionrequest.requestor,
					 event.xselectionrequest.property,
					 XA_ATOM,
					 32,
					 PropModeReplace,
					 (unsigned char *) atomTargetArr,
					 (sizeof (atomTargetArr)
					  / sizeof (atomTargetArr[0])));
	      if (iReturn == BadAlloc
		  || iReturn == BadAtom
		  || iReturn == BadMatch
		  || iReturn == BadValue
		  || iReturn == BadWindow)
		{
		  ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
			  "XChangeProperty failed: %d\n",
			  iReturn);
		}

	      /* Setup selection notify xevent */
	      eventSelection.type	= SelectionNotify;
	      eventSelection.send_event	= True;
	      eventSelection.display	= pDisplay;
	      eventSelection.requestor	= event.xselectionrequest.requestor;
	      eventSelection.selection	= event.xselectionrequest.selection;
	      eventSelection.target	= event.xselectionrequest.target;
	      eventSelection.property	= event.xselectionrequest.property;
	      eventSelection.time	= event.xselectionrequest.time;

	      /*
	       * Notify the requesting window that
	       * the operation has completed
	       */
	      iReturn = XSendEvent (pDisplay,
				    eventSelection.requestor,
				    False,
				    0L,
				    (XEvent *) &eventSelection);
	      if (iReturn == BadValue || iReturn == BadWindow)
		{
		  ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
			  "XSendEvent () failed\n");
		}
	      break;
	    }

	  /* Check that clipboard format is available */
	  if (fUseUnicode
	      && !IsClipboardFormatAvailable (CF_UNICODETEXT))
	    {
	      ErrorF ("winClipboardFlushXEvents - CF_UNICODETEXT is not "
		      "available from Win32 clipboard.  Aborting.\n");

	      /* Abort */
	      fAbort = TRUE;
	      goto winClipboardFlushXEvents_SelectionRequest_Done;
	    }
	  else if (!fUseUnicode
		   && !IsClipboardFormatAvailable (CF_TEXT))
	    {
	      ErrorF ("winClipboardFlushXEvents - CF_TEXT is not "
		      "available from Win32 clipboard.  Aborting.\n");

	      /* Abort */
	      fAbort = TRUE;
	      goto winClipboardFlushXEvents_SelectionRequest_Done;
	    }

	  /* Close clipboard if we have it open already */
	  if (GetOpenClipboardWindow () == hwnd)
	    {
	      CloseClipboard ();
	    }

	  /* Access the clipboard */
	  if (!OpenClipboard (hwnd))
	    {
	      ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
		      "OpenClipboard () failed: %08x\n",
		      GetLastError ());

	      /* Abort */
	      fAbort = TRUE;
	      goto winClipboardFlushXEvents_SelectionRequest_Done;
	    }
	  
	  /* Indicate that clipboard was opened */
	  fCloseClipboard = TRUE;

	  /* Setup the string style */
	  if (event.xselectionrequest.target == XA_STRING)
	    xiccesStyle = XStringStyle;
#ifdef X_HAVE_UTF8_STRING
	  else if (event.xselectionrequest.target == atomUTF8String)
	    xiccesStyle = XUTF8StringStyle;
#endif
	  else if (event.xselectionrequest.target == atomCompoundText)
	    xiccesStyle = XCompoundTextStyle;
	  else
	    xiccesStyle = XStringStyle;

	  /*
	   * FIXME: Can't pass CF_UNICODETEXT on Windows 95/98/Me
	   */
	  
	  /* Get a pointer to the clipboard text, in desired format */
	  if (fUseUnicode)
	    {
	      /* Retrieve clipboard data */
	      hGlobal = GetClipboardData (CF_UNICODETEXT);
	    }
	  else
	    {
	      /* Retrieve clipboard data */
	      hGlobal = GetClipboardData (CF_TEXT);
	    }
	  if (!hGlobal)
	    {
	      ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
		      "GetClipboardData () failed: %08x\n",
		      GetLastError ());

	      /* Abort */
	      fAbort = TRUE;
	      goto winClipboardFlushXEvents_SelectionRequest_Done;
	    }
	  pszGlobalData = (char *) GlobalLock (hGlobal);

	  /* Convert the Unicode string to UTF8 (MBCS) */
	  if (fUseUnicode)
	    {
	      iConvertDataLen = WideCharToMultiByte (CP_UTF8,
						     0,
						     (LPCWSTR)pszGlobalData,
						     -1,
						     NULL,
						     0,
						     NULL,
						     NULL);
	      /* NOTE: iConvertDataLen includes space for null terminator */
	      pszConvertData = (char *) malloc (iConvertDataLen);
	      WideCharToMultiByte (CP_UTF8,
				   0,
				   (LPCWSTR)pszGlobalData,
				   -1,
				   pszConvertData,
				   iConvertDataLen,
				   NULL,
				   NULL);
	    }
	  else
	    {
	      pszConvertData = strdup (pszGlobalData);
	      iConvertDataLen = strlen (pszConvertData) + 1;
	    }

	  /* Convert DOS string to UNIX string */
	  winClipboardDOStoUNIX (pszConvertData, strlen (pszConvertData));

	  /* Setup our text list */
	  pszTextList[0] = pszConvertData;
	  pszTextList[1] = NULL;

	  /* Initialize the text property */
	  xtpText.value = NULL;

	  /* Create the text property from the text list */
	  if (fUseUnicode)
	    {
#ifdef X_HAVE_UTF8_STRING
	      iReturn = Xutf8TextListToTextProperty (pDisplay,
						     pszTextList,
						     1,
						     xiccesStyle,
						     &xtpText);
#endif
	    }
	  else
	    {
	      iReturn = XmbTextListToTextProperty (pDisplay,
						   pszTextList,
						   1,
						   xiccesStyle,
						   &xtpText);
	    }
	  if (iReturn == XNoMemory || iReturn == XLocaleNotSupported)
	    {
	      ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
		      "X*TextListToTextProperty failed: %d\n",
		      iReturn);

	      /* Abort */
	      fAbort = TRUE;
	      goto winClipboardFlushXEvents_SelectionRequest_Done;
	    }
	  
	  /* Free the converted string */
	  free (pszConvertData);
	  pszConvertData = NULL;

	  /* Copy the clipboard text to the requesting window */
	  iReturn = XChangeProperty (pDisplay,
				     event.xselectionrequest.requestor,
				     event.xselectionrequest.property,
				     event.xselectionrequest.target,
				     8,
				     PropModeReplace,
				     xtpText.value,
				     xtpText.nitems);
	  if (iReturn == BadAlloc || iReturn == BadAtom
	      || iReturn == BadMatch || iReturn == BadValue
	      || iReturn == BadWindow)
	    {
	      ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
		      "XChangeProperty failed: %d\n",
		      iReturn);

	      /* Abort */
	      fAbort = TRUE;
	      goto winClipboardFlushXEvents_SelectionRequest_Done;
	    }

	  /* Release the clipboard data */
	  GlobalUnlock (hGlobal);
	  pszGlobalData = NULL;

	  /* Clean up */
	  XFree (xtpText.value);
	  xtpText.value = NULL;

	  /* Setup selection notify event */
	  eventSelection.type = SelectionNotify;
	  eventSelection.send_event = True;
	  eventSelection.display = pDisplay;
	  eventSelection.requestor = event.xselectionrequest.requestor;
	  eventSelection.selection = event.xselectionrequest.selection;
	  eventSelection.target = event.xselectionrequest.target;
	  eventSelection.property = event.xselectionrequest.property;
	  eventSelection.time = event.xselectionrequest.time;

	  /* Notify the requesting window that the operation has completed */
	  iReturn = XSendEvent (pDisplay,
				eventSelection.requestor,
				False,
				0L,
				(XEvent *) &eventSelection);
	  if (iReturn == BadValue || iReturn == BadWindow)
	    {
	      ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
		      "XSendEvent () failed\n");

	      /* Abort */
	      fAbort = TRUE;
	      goto winClipboardFlushXEvents_SelectionRequest_Done;
	    }

	winClipboardFlushXEvents_SelectionRequest_Done:
	  /* Free allocated resources */
	  if (xtpText.value)
	    XFree (xtpText.value);
	  if (pszConvertData)
	    free (pszConvertData);
	  if (hGlobal && pszGlobalData)
	    GlobalUnlock (hGlobal);
	  
	  /*
	   * Send a SelectionNotify event to the requesting
	   * client when we abort.
	   */
	  if (fAbort)
	    {
	      /* Setup selection notify event */
	      eventSelection.type = SelectionNotify;
	      eventSelection.send_event = True;
	      eventSelection.display = pDisplay;
	      eventSelection.requestor = event.xselectionrequest.requestor;
	      eventSelection.selection = event.xselectionrequest.selection;
	      eventSelection.target = event.xselectionrequest.target;
	      eventSelection.property = None;
	      eventSelection.time = event.xselectionrequest.time;

	      /* Notify the requesting window that the operation is complete */
	      iReturn = XSendEvent (pDisplay,
				    eventSelection.requestor,
				    False,
				    0L,
				    (XEvent *) &eventSelection);
	      if (iReturn == BadValue || iReturn == BadWindow)
		{
		  /*
		   * Should not be a problem if XSendEvent fails because
		   * the client may simply have exited.
		   */
		  ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
			  "XSendEvent () failed for abort event.\n");
		}
	    }

	  /* Close clipboard if it was opened */
	  if (fCloseClipboard)
	    CloseClipboard ();
	  break;


	  /*
	   * SelectionNotify
	   */ 

	case SelectionNotify:
#if 0
	  ErrorF ("winClipboardFlushXEvents - SelectionNotify\n");
	  {
	    char		*pszAtomName;
	    
	    pszAtomName = XGetAtomName (pDisplay,
					event.xselection.selection);

	    ErrorF ("winClipboardFlushXEvents - SelectionNotify - ATOM: %s\n",
		    pszAtomName);
	    
	    XFree (pszAtomName);
	  }
#endif


	  /*
	   * Request conversion of UTF8 and CompoundText targets.
	   */
	  if (event.xselection.property == None)
	    {
	      if (event.xselection.target == XA_STRING)
		{
#if 0
		  ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
			  "XA_STRING\n");
#endif
		  return WIN_XEVENTS_CONVERT;
		}
	      else if (event.xselection.target == atomUTF8String)
		{
#if 0
		  ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
			  "Requesting conversion of UTF8 target.\n");
#endif
		  iReturn = XConvertSelection (pDisplay,
					       event.xselection.selection,
					       XA_STRING,
					       atomLocalProperty,
					       iWindow,
					       CurrentTime);
		  if (iReturn != Success)
		    {
		      ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
			      "XConvertSelection () failed for UTF8String, "
			      "aborting: %d\n",
			      iReturn);
		      break;
		    }

		  /* Process the ConvertSelection event */
		  XFlush (pDisplay);
		  return WIN_XEVENTS_CONVERT;
		}
#ifdef X_HAVE_UTF8_STRING
	      else if (event.xselection.target == atomCompoundText)
		{
#if 0
		  ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
			  "Requesting conversion of CompoundText target.\n");
#endif
		  iReturn = XConvertSelection (pDisplay,
					       event.xselection.selection,
					       atomUTF8String,
					       atomLocalProperty,
					       iWindow,
					       CurrentTime);
		  if (iReturn != Success)
		    {
		      ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
			      "XConvertSelection () failed for CompoundText, "
			      "aborting: %d\n",
			      iReturn);
		      break;
		    }

		  /* Process the ConvertSelection event */
		  XFlush (pDisplay);
		  return WIN_XEVENTS_CONVERT;
		}
#endif
	      else
		{
		  ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
			  "Unknown format.  Cannot request conversion, "
			  "aborting.\n");
		  break;
		}
	    }

	  /* Retrieve the size of the stored data */
	  iReturn = XGetWindowProperty (pDisplay,
					iWindow,
					atomLocalProperty,
					0,
					0, /* Don't get data, just size */
					False,
					AnyPropertyType,
					&xtpText.encoding,
					&xtpText.format,
					&xtpText.nitems,
					&ulReturnBytesLeft,
					&xtpText.value);
	  if (iReturn != Success)
	    {
	      ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
		      "XGetWindowProperty () failed, aborting: %d\n",
		      iReturn);
	      break;
	    }

#if 0
	  ErrorF ("SelectionNotify - returned data %d left %d\n",
		  xtpText.nitems, ulReturnBytesLeft);
#endif

	  /* Request the selection data */
	  iReturn = XGetWindowProperty (pDisplay,
					iWindow,
					atomLocalProperty,
					0,
					ulReturnBytesLeft,
					False,
					AnyPropertyType,
					&xtpText.encoding,
					&xtpText.format,
					&xtpText.nitems,
					&ulReturnBytesLeft,
					&xtpText.value);
	  if (iReturn != Success)
	    {
	      ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
		      "XGetWindowProperty () failed, aborting: %d\n",
		      iReturn);
	      break;
	    }

#if 0
	    {
	      char		*pszAtomName = NULL;

	      ErrorF ("SelectionNotify - returned data %d left %d\n",
		      xtpText.nitems, ulReturnBytesLeft);
	      
	      pszAtomName = XGetAtomName(pDisplay, xtpText.encoding);
	      ErrorF ("Notify atom name %s\n", pszAtomName);
	      XFree (pszAtomName);
	      pszAtomName = NULL;
	    }
#endif

	  if (fUseUnicode)
	    {
#ifdef X_HAVE_UTF8_STRING
	      /* Convert the text property to a text list */
	      iReturn = Xutf8TextPropertyToTextList (pDisplay,
						     &xtpText,
						     &ppszTextList,
						     &iCount);
#endif
	    }
	  else
	    {
	      iReturn = XmbTextPropertyToTextList (pDisplay,
						   &xtpText,
						   &ppszTextList,
						   &iCount);
	    }
	  if (iReturn == Success || iReturn > 0)
	    {
	      /* Conversion succeeded or some unconvertible characters */
	      if (ppszTextList != NULL)
		{
		  for (i = 0; i < iCount; i++)
		    {
		      iReturnDataLen += strlen(ppszTextList[i]);
		    }
		  pszReturnData = malloc (iReturnDataLen + 1);
		  pszReturnData[0] = '\0';
		  for (i = 0; i < iCount; i++)
		    {
		      strcat (pszReturnData, ppszTextList[i]);
		    }
		}
	      else
		{
		  ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
			  "X*TextPropertyToTextList list_return is NULL.\n");
		  pszReturnData = malloc (1);
		  pszReturnData[0] = '\0';
		}
	    }
	  else
	    {
	      ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
		      "X*TextPropertyToTextList returned: ");
	      switch (iReturn)
		{
		case XNoMemory:
		  ErrorF ("XNoMemory\n");
		  break;
		case XConverterNotFound:
		  ErrorF ("XConverterNotFound\n");
		  break;
		default:
		  ErrorF ("%d", iReturn);
		  break;
		}
	      pszReturnData = malloc (1);
	      pszReturnData[0] = '\0';
	    }

	  /* Free the data returned from XGetWindowProperty */
	  if (ppszTextList)
	    XFreeStringList (ppszTextList);
	  ppszTextList = NULL;
	  XFree (xtpText.value);
	  xtpText.value = NULL;

	  /* Convert the X clipboard string to DOS format */
	  winClipboardUNIXtoDOS (&pszReturnData, strlen (pszReturnData));

	  if (fUseUnicode)
	    {
	      /* Find out how much space needed to convert MBCS to Unicode */
	      iUnicodeLen = MultiByteToWideChar (CP_UTF8,
						 0,
						 pszReturnData,
						 -1,
						 NULL,
						 0);

	      /* Allocate memory for the Unicode string */
	      pwszUnicodeStr
		= (wchar_t*) malloc (sizeof (wchar_t) * (iUnicodeLen + 1));
	      if (!pwszUnicodeStr)
		{
		  ErrorF ("winClipboardFlushXEvents - SelectionNotify "
			  "malloc failed for pwszUnicodeStr, aborting.\n");

		  /* Abort */
		  fAbort = TRUE;
		  goto winClipboardFlushXEvents_SelectionNotify_Done;
		}

	      /* Do the actual conversion */
	      MultiByteToWideChar (CP_UTF8,
				   0,
				   pszReturnData,
				   -1,
				   pwszUnicodeStr,
				   iUnicodeLen);
	      
	      /* Allocate global memory for the X clipboard data */
	      hGlobal = GlobalAlloc (GMEM_MOVEABLE,
				     sizeof (wchar_t) * (iUnicodeLen + 1));
	    }
	  else
	    {
	      pszConvertData = strdup (pszReturnData);
	      iConvertDataLen = strlen (pszConvertData) + 1;

	      /* Allocate global memory for the X clipboard data */
	      hGlobal = GlobalAlloc (GMEM_MOVEABLE, iConvertDataLen);
	    }

	  /* Check that global memory was allocated */
	  if (!hGlobal)
	    {
	      ErrorF ("winClipboardFlushXEvents - SelectionNotify "
		      "GlobalAlloc failed, aborting: %ld\n",
		      GetLastError ());

	      /* Abort */
	      fAbort = TRUE;
	      goto winClipboardFlushXEvents_SelectionNotify_Done;
	    }

	  /* Obtain a pointer to the global memory */
	  pszGlobalData = GlobalLock (hGlobal);
	  if (pszGlobalData == NULL)
	    {
	      ErrorF ("winClipboardFlushXEvents - Could not lock global "
		      "memory for clipboard transfer\n");

	      /* Abort */
	      fAbort = TRUE;
	      goto winClipboardFlushXEvents_SelectionNotify_Done;
	    }

	  /* Copy the returned string into the global memory */
	  if (fUseUnicode)
	    {
	      memcpy (pszGlobalData,
		      pwszUnicodeStr,
		      sizeof (wchar_t) * (iUnicodeLen + 1));
	      free (pwszUnicodeStr);
	      pwszUnicodeStr = NULL;
	    }
	  else
	    {
	      strcpy (pszGlobalData, pszConvertData);
	      free (pszConvertData);
	      pszConvertData = NULL;
	    }

	  /* Release the pointer to the global memory */
	  GlobalUnlock (hGlobal);
	  pszGlobalData = NULL;

	  /* Push the selection data to the Windows clipboard */
	  if (fUseUnicode)
	    SetClipboardData (CF_UNICODETEXT, hGlobal);
	  else
	    SetClipboardData (CF_TEXT, hGlobal);

	  /* Flag that SetClipboardData has been called */
	  fSetClipboardData = FALSE;

	  /*
	   * NOTE: Do not try to free pszGlobalData, it is owned by
	   * Windows after the call to SetClipboardData ().
	   */

	winClipboardFlushXEvents_SelectionNotify_Done:
	  /* Free allocated resources */
	  if (ppszTextList)
	    XFreeStringList (ppszTextList);
	  if (xtpText.value)
	    XFree (xtpText.value);
	  if (pszConvertData)
	    free (pszConvertData);
	  if (pwszUnicodeStr)
	    free (pwszUnicodeStr);
	  if (hGlobal && pszGlobalData)
	    GlobalUnlock (hGlobal);
	  if (fSetClipboardData && g_fUnicodeSupport)
	    SetClipboardData (CF_UNICODETEXT, NULL);
	  if (fSetClipboardData)
	    SetClipboardData (CF_TEXT, NULL);
	  return WIN_XEVENTS_NOTIFY;

	default:
	  break;
	}
    }

  return WIN_XEVENTS_SUCCESS;
}
void cheat_handle_debug ( HWND wnd )
{
	static const int	data_size[4] = { 1, 2, 4, 4 };
	struct debug_info	*debug = &cheat_state->debug;
	int					move = 0, hist_chng = 0;

	if ( !cheat_state->debug_enabled )
		return;

	/* go to pointer */
	if ( KEY_PRESSED(VK_NUMPAD1) )
	{
		setDebugPointer( *(void **)debug->cursor_data );
		hist_chng = 1;
	}

	/* go back */
	if ( KEY_PRESSED(VK_NUMPAD7) )
	{
		if ( debug->hist_pos > 0 )
		{
			debug->hist_pos--;
			hist_chng = 1;
		}
		else if ( debug->hist_pos == 0 )
			setDebugPointer( (void *)NULL );
	}

	/* change data type */
	if ( KEY_PRESSED(VK_DIVIDE) )
		debug->data_type = ( debug->data_type + 1 ) % 4;

	/* inc/dec value */
	if ( KEY_DOWN(VK_ADD) || KEY_DOWN(VK_SUBTRACT) )
	{
		const int	value = KEY_DOWN( VK_ADD ) ? 1 : -1;
		uint8_t		data[4] = { 0, 0, 0, 0 };

		if ( memcpy_safe(data, debug->ptr[debug->hist_pos] + debug->offset[debug->hist_pos], data_size[debug->data_type]) )
		{
			switch ( debug->data_type )
			{
#pragma warning( disable : 4244 )

			case 0:
				( *(uint8_t *)data ) += ( uint8_t ) value;
				break;

			case 1:
				( *(uint16_t *)data ) += ( uint16_t ) value;
				break;

			case 2:
				( *(uint32_t *)data ) += ( uint32_t ) value;
				break;

			case 3:
				( *(float *)data ) += (float)value / 10.0f;
				break;
			}

			memcpy_safe( debug->ptr[debug->hist_pos] + debug->offset[debug->hist_pos], data, data_size[debug->data_type] );
		}
	}

	/* copy info to clipboard */
	if ( KEY_PRESSED(VK_MULTIPLY) )
	{
		if ( OpenClipboard(wnd) )
		{
			HGLOBAL mem = GlobalAlloc( GMEM_MOVEABLE, sizeof(debug->ptr_hist_str) );

			if ( mem != NULL )
			{
				char	*str = (char *)GlobalLock( mem );

				strlcpy( str, debug->ptr_hist_str, sizeof(debug->ptr_hist_str) );
				Log( "%s", str );
				GlobalUnlock( str );

				EmptyClipboard();

				if ( !SetClipboardData(CF_TEXT, mem) )
					Log( "SetClipboardData() %d", GetLastError() );

				/*SetClipboardData(CF_TEXT, mem);*/
			}

			CloseClipboard();
		}
		else
		{
			Log( "OpenClipboard() %d", GetLastError() );
		}
	}

	if ( KEY_PRESSED(VK_NUMPAD4) )
		move -= data_size[debug->data_type];
	if ( KEY_PRESSED(VK_NUMPAD6) )
		move += data_size[debug->data_type];
	if ( KEY_PRESSED(VK_NUMPAD8) )
		move += -16;
	if ( KEY_PRESSED(VK_NUMPAD2) )
		move += 16;
	if ( KEY_PRESSED(VK_NUMPAD9) )
		move += -160;
	if ( KEY_PRESSED(VK_NUMPAD3) )
		move += 160;

	debug->offset[debug->hist_pos] += move;

	if ( move != 0 || hist_chng )
	{
		memset( debug->modify_time, 0, DEBUG_DATA_SIZE * sizeof(uint32_t) );
		debug->data_prev_clear = 1;
	}

	for ( int i = 0; i < 9; i++ )
		KEY_CONSUME( VK_NUMPAD1 + i );
	KEY_CONSUME( VK_MULTIPLY );
	KEY_CONSUME( VK_DIVIDE );
	KEY_CONSUME( VK_ADD );
	KEY_CONSUME( VK_SUBTRACT );
}
Example #17
0
static void test_PrintDlgA(void)
{
    DWORD       res;
    LPPRINTDLGA pDlg;
    DEVNAMES    *pDevNames;
    LPCSTR driver;
    LPCSTR device;
    LPCSTR port;
    CHAR   buffer[MAX_PATH];
    LPSTR  ptr;


    pDlg = HeapAlloc(GetProcessHeap(), 0, (sizeof(PRINTDLGA)) * 2);
    if (!pDlg) return;


    /* will crash with unpatched wine */
    SetLastError(0xdeadbeef);
    res = PrintDlgA(NULL);
    ok( !res && (CommDlgExtendedError() == CDERR_INITIALIZATION),
        "returned %d with 0x%x and 0x%x (expected '0' and "
        "CDERR_INITIALIZATION)\n", res, GetLastError(), CommDlgExtendedError());

    ZeroMemory(pDlg, sizeof(PRINTDLGA));
    pDlg->lStructSize = sizeof(PRINTDLGA) - 1;
    SetLastError(0xdeadbeef);
    res = PrintDlgA(pDlg);
    ok( !res && (CommDlgExtendedError() == CDERR_STRUCTSIZE),
        "returned %d with 0x%x and 0x%x (expected '0' and "
        "CDERR_STRUCTSIZE)\n", res, GetLastError(), CommDlgExtendedError());

    ZeroMemory(pDlg, sizeof(PRINTDLGA));
    pDlg->lStructSize = sizeof(PRINTDLGA) + 1;
    pDlg->Flags = PD_RETURNDEFAULT;
    SetLastError(0xdeadbeef);
    res = PrintDlgA(pDlg);
    ok( !res && (CommDlgExtendedError() == CDERR_STRUCTSIZE),
        "returned %u with %u and 0x%x (expected '0' and "
        "CDERR_STRUCTSIZE)\n", res, GetLastError(), CommDlgExtendedError());


    ZeroMemory(pDlg, sizeof(PRINTDLGA));
    pDlg->lStructSize = sizeof(PRINTDLGA);
    pDlg->Flags = PD_RETURNDEFAULT;
    SetLastError(0xdeadbeef);
    res = PrintDlgA(pDlg);
    ok( res || (CommDlgExtendedError() == PDERR_NODEFAULTPRN),
        "returned %d with 0x%x and 0x%x (expected '!= 0' or '0' and "
        "PDERR_NODEFAULTPRN)\n", res, GetLastError(), CommDlgExtendedError());

    if (!res && (CommDlgExtendedError() == PDERR_NODEFAULTPRN)) {
        skip("No printer configured.\n");
        HeapFree(GetProcessHeap(), 0, pDlg);
        return;
    }

    ok(pDlg->hDevNames != NULL, "(expected '!= NULL')\n");
    pDevNames = GlobalLock(pDlg->hDevNames);
    ok(pDevNames != NULL, "(expected '!= NULL')\n");

    if (pDevNames) {
        ok(pDevNames->wDriverOffset, "(expected '!= 0' for wDriverOffset)\n");
        ok(pDevNames->wDeviceOffset, "(expected '!= 0' for wDeviceOffset)\n");
        ok(pDevNames->wOutputOffset, "(expected '!= 0' for wOutputOffset)\n");
        ok(pDevNames->wDefault == DN_DEFAULTPRN, "got 0x%x (expected DN_DEFAULTPRN)\n", pDevNames->wDefault);

        driver = (LPCSTR)pDevNames + pDevNames->wDriverOffset;
        device = (LPCSTR)pDevNames + pDevNames->wDeviceOffset;
        port = (LPCSTR)pDevNames + pDevNames->wOutputOffset;
        trace("driver '%s' device '%s' port '%s'\n", driver, device, port);

        /* The Driver Entry does not include a Path */
        ptr = strrchr(driver, '\\');
        ok( ptr == NULL, "got %p for '%s' (expected NULL for a simple name)\n", ptr, driver);

        /* The Driver Entry does not have an extension (fixed to ".drv") */
        ptr = strrchr(driver, '.');
        todo_wine {
        ok( ptr == NULL, "got %p for '%s' (expected NULL for no extension)\n", ptr, driver);
        }


        buffer[0] = '\0';
        SetLastError(0xdeadbeef);
        res = GetProfileStringA(PrinterPortsA, device, emptyA, buffer, sizeof(buffer));
        ptr = strchr(buffer, ',');
        ok( (res > 1) && (ptr != NULL),
            "got %u with %u and %p for '%s' (expected '>1' and '!= NULL')\n",
            res, GetLastError(), ptr, buffer);

        if (ptr) ptr[0] = '\0';
        ok( lstrcmpiA(driver, buffer) == 0,
            "got driver '%s' (expected '%s')\n", driver, buffer);
    }

    GlobalUnlock(pDlg->hDevNames);

    GlobalFree(pDlg->hDevMode);
    GlobalFree(pDlg->hDevNames);
    HeapFree(GetProcessHeap(), 0, pDlg);

}
Example #18
0
HBITMAP g_load_png_gdiplus_throw(HDC dc, const char * fn, unsigned target_cx, unsigned target_cy)
{
	//FIXME m_gdiplus_initialised = (Gdiplus::Ok == Gdiplus::GdiplusStartup(&m_gdiplus_instance, &Gdiplus::GdiplusStartupInput(), NULL));
	pfc::string8 canPath;
	HBITMAP bm = 0;

	abort_callback_dummy p_abort;
	file::ptr p_file;
	filesystem::g_get_canonical_path(fn, canPath);
	filesystem::g_open_read(p_file, canPath, p_abort);
	t_size fsize = pfc::downcast_guarded<t_size>(p_file->get_size_ex(p_abort));
	pfc::array_staticsize_t<t_uint8> buffer(fsize);
	p_file->read(buffer.get_ptr(), fsize, p_abort);
	p_file.release();

	IStream *pStream = NULL;
	HGLOBAL gd = GlobalAlloc(GMEM_FIXED | GMEM_MOVEABLE, buffer.get_size());
	if (gd == NULL)
		throw exception_win32(GetLastError());
	void * p_data = GlobalLock(gd);
	if (p_data == NULL)
	{
		GlobalFree(gd);
		throw exception_win32(GetLastError());
	}

	memcpy(p_data, buffer.get_ptr(), buffer.get_size());
	GlobalUnlock(gd);

	HRESULT hr = CreateStreamOnHGlobal(gd, TRUE, &pStream);
	if (FAILED(hr))
	{
		GlobalFree(gd);
		throw exception_win32(hr);
	}

	Gdiplus::Bitmap pImage(pStream);

	CheckGdiplusStatus() << pImage.GetLastStatus();
	{
		Gdiplus::BitmapData bitmapData;
		//Gdiplus::Bitmap * ppImage = &pImage;
		if (target_cx != pfc_infinite || target_cy != pfc_infinite)
		{
			Gdiplus::Bitmap pBitmapResized(target_cx == pfc_infinite ? pImage.GetWidth() : target_cx, target_cy == pfc_infinite ? pImage.GetHeight() : target_cy, PixelFormat32bppARGB);
			CheckGdiplusStatus() << pBitmapResized.GetLastStatus();
			Gdiplus::Graphics pGraphics(&pBitmapResized);
			CheckGdiplusStatus() << pGraphics.GetLastStatus();
			CheckGdiplusStatus() << pGraphics.SetPixelOffsetMode(Gdiplus::PixelOffsetModeHighQuality);
			CheckGdiplusStatus() << pGraphics.SetInterpolationMode(Gdiplus::InterpolationModeBicubic);
			Gdiplus::ImageAttributes imageAttributes;
			CheckGdiplusStatus() << imageAttributes.SetWrapMode(Gdiplus::WrapModeTileFlipXY);
			CheckGdiplusStatus() << pGraphics.DrawImage(&pImage, Gdiplus::Rect(0, 0, pBitmapResized.GetWidth(), pBitmapResized.GetHeight()), 0, 0, pImage.GetWidth(), pImage.GetHeight(), Gdiplus::UnitPixel, &imageAttributes);

			CheckGdiplusStatus() << pBitmapResized.LockBits(&Gdiplus::Rect(0, 0, pBitmapResized.GetWidth(), pBitmapResized.GetHeight()), Gdiplus::ImageLockModeRead, PixelFormat32bppARGB, &bitmapData);
			bm = g_CreateHbitmapFromGdiplusBitmapData32bpp(bitmapData);
			CheckGdiplusStatus() << pBitmapResized.UnlockBits(&bitmapData);
		}
		else
		{
			CheckGdiplusStatus() << pImage.LockBits(&Gdiplus::Rect(0, 0, pImage.GetWidth(), pImage.GetHeight()), Gdiplus::ImageLockModeRead, PixelFormat32bppARGB, &bitmapData);
			//assert bitmapData.Stride == bitmapData.Width
			bm = g_CreateHbitmapFromGdiplusBitmapData32bpp(bitmapData);
			CheckGdiplusStatus() << pImage.UnlockBits(&bitmapData);
		}
	}
	return bm;

}
Example #19
0
void CDynamoRIOView::OnEditCopystats()
{
    if (m_ProcessList.GetCurSel() == 0) {
        MessageBox(_T("No instance selected"), _T("Error"), MB_OK | MYMBFLAGS);
        return;
    }
    if (!OpenClipboard()) {
        MessageBox(_T("Error opening clipboard"), _T("Error"),
                   MB_OK | MYMBFLAGS);
        return;
    }
    EmptyClipboard();

#define CLIPBOARD_BUFSZ USHRT_MAX
    TCHAR buf[CLIPBOARD_BUFSZ];
    TCHAR *pos = buf;

    if (m_selected_pid > 0) {
        if (m_stats != NULL) {
            pos += _stprintf(pos, _T("Process id                  = %d\r\n"),
                             m_stats->process_id);
            pos += _stprintf(pos, _T("Process name                = %") ASCII_PRINTF
                             _T("\r\n"), m_stats->process_name);
            pos += _stprintf(pos, _T("Status                      = %s\r\n"),
                             m_Exited.GetBuffer(0));
#ifndef DRGUI_DEMO
            pos += _stprintf(pos, _T("Log mask                    = %s\r\n"),
                             m_LogMask.GetBuffer(0));
            pos += _stprintf(pos, _T("Log level                   = %s\r\n"),
                             m_LogLevel.GetBuffer(0));
            pos += _stprintf(pos, _T("Log file                    = %s\r\n"),
                             m_LogDir.GetBuffer(0));
#endif
            pos += _stprintf(pos, _T("\r\nSTATS\r\n"));
            uint i;
            for (i = 0; i < m_stats->num_stats; i++) {
                if (pos >= &buf[STATS_BUFSZ-STAT_NAME_MAX_LEN*2])
                    break;
                // FIXME: Filter here too
                pos += PrintStat(pos, i, TRUE/*filter*/);
                assert(pos < &buf[STATS_BUFSZ-1]);
            }
        } else {
            CString pname;
            m_ProcessList.GetLBText(m_ProcessList.GetCurSel(), pname);
            _stprintf(pos, _T("%s"), pname);
            pos += _tcslen(pos);
        }
    }
    if (m_clientStats != NULL) {
        pos += PrintClientStats(pos, &buf[STATS_BUFSZ-1]);
    }

    size_t len = _tcslen(buf);

    // Allocate a global memory object for the text.
    HGLOBAL hglbCopy = GlobalAlloc(GMEM_DDESHARE,
                                   (len + 1) * sizeof(TCHAR));
    if (hglbCopy == NULL) {
        CloseClipboard();
        return;
    }

    // Lock the handle and copy the text to the buffer.
    LPTSTR lptstrCopy = (LPTSTR) GlobalLock(hglbCopy);
    memcpy(lptstrCopy, buf, (len + 1) * sizeof(TCHAR));
    lptstrCopy[len] = (TCHAR) 0;    // null TCHARacter
    GlobalUnlock(hglbCopy);

    // Place the handle on the clipboard.
    SetClipboardData(
#ifdef UNICODE
        CF_UNICODETEXT,
#else
        CF_TEXT,
#endif
        hglbCopy);

    CloseClipboard();
}
Example #20
0
HPALETTE CreateDIBPalette(HDIB hDIB)
{
   LPLOGPALETTE lpPal;      // pointer to a logical palette
   HANDLE hLogPal;          // handle to a logical palette
   HPALETTE hPal = NULL;    // handle to a palette
   int i, wNumColors;       // loop index, number of colors in color table
   LPSTR lpbi;              // pointer to packed-DIB
   LPBITMAPINFO lpbmi;      // pointer to BITMAPINFO structure (Win3.0)
   LPBITMAPCOREINFO lpbmc;  // pointer to BITMAPCOREINFO structure (OS/2)
   BOOL bWinStyleDIB;       // flag which signifies whether this is a Win3.0 DIB

   /* if handle to DIB is invalid, return NULL */

   if (!hDIB)
      return NULL;

   /* lock DIB memory block and get a pointer to it */
   lpbi = (LPSTR) GlobalLock(hDIB);

   /* get pointer to BITMAPINFO (Win 3.0) */
   lpbmi = (LPBITMAPINFO)lpbi;

   /* get pointer to BITMAPCOREINFO (OS/2 1.x) */
   lpbmc = (LPBITMAPCOREINFO)lpbi;

   /* get the number of colors in the DIB */
   wNumColors = DIBNumColors(lpbi);

   /* is this a Win 3.0 DIB? */
   bWinStyleDIB = IS_WIN30_DIB(lpbi);
   if (wNumColors)
   {
      /* allocate memory block for logical palette */
      hLogPal = GlobalAlloc(GHND, sizeof(LOGPALETTE) + sizeof(PALETTEENTRY) *
                            wNumColors);

      /* if not enough memory, clean up and return NULL */
      if (!hLogPal)
      {
         GlobalUnlock(hDIB);
         return NULL;
      }

      /* lock memory block and get pointer to it */
      lpPal = (LPLOGPALETTE)GlobalLock(hLogPal);

      /* set version and number of palette entries */
      lpPal->palVersion = PALVERSION;
      lpPal->palNumEntries = wNumColors;

      /*  store RGB triples (if Win 3.0 DIB) or RGB quads (if OS/2 DIB)
       *  into palette
       */
      for (i = 0; i < wNumColors; i++)
      {
         if (bWinStyleDIB)
         {
            lpPal->palPalEntry[i].peRed = lpbmi->bmiColors[i].rgbRed;
            lpPal->palPalEntry[i].peGreen = lpbmi->bmiColors[i].rgbGreen;
            lpPal->palPalEntry[i].peBlue = lpbmi->bmiColors[i].rgbBlue;
            lpPal->palPalEntry[i].peFlags = 0;
         }
         else
         {
            lpPal->palPalEntry[i].peRed = lpbmc->bmciColors[i].rgbtRed;
            lpPal->palPalEntry[i].peGreen = lpbmc->bmciColors[i].rgbtGreen;
            lpPal->palPalEntry[i].peBlue = lpbmc->bmciColors[i].rgbtBlue;
            lpPal->palPalEntry[i].peFlags = 0;
         }
      }

      /* create the palette and get handle to it */
      hPal = CreatePalette(lpPal);

      /* if error getting handle to palette, clean up and return NULL */
      if (!hPal)
      {
         GlobalUnlock(hLogPal);
         GlobalFree(hLogPal);
         return NULL;
      }
   }

   /* clean up */
   GlobalUnlock(hLogPal);
   GlobalFree(hLogPal);
   GlobalUnlock(hDIB);

   /* return handle to DIB's palette */
   return hPal;
}
Example #21
0
static HRESULT WriteUsingWIC(const char* out_file_name, int use_stdout,
                             REFGUID container_guid,
                             uint8_t* rgb, int stride,
                             uint32_t width, uint32_t height, int has_alpha) {
  HRESULT hr = S_OK;
  IWICImagingFactory* factory = NULL;
  IWICBitmapFrameEncode* frame = NULL;
  IWICBitmapEncoder* encoder = NULL;
  IStream* stream = NULL;
  WICPixelFormatGUID pixel_format = has_alpha ? GUID_WICPixelFormat32bppBGRA
                                              : GUID_WICPixelFormat24bppBGR;

  if (out_file_name == NULL || rgb == NULL) return E_INVALIDARG;

  IFS(CoInitialize(NULL));
  IFS(CoCreateInstance(MAKE_REFGUID(CLSID_WICImagingFactory), NULL,
                       CLSCTX_INPROC_SERVER,
                       MAKE_REFGUID(IID_IWICImagingFactory),
                       (LPVOID*)&factory));
  if (hr == REGDB_E_CLASSNOTREG) {
    fprintf(stderr,
            "Couldn't access Windows Imaging Component (are you running "
            "Windows XP SP3 or newer?). PNG support not available. "
            "Use -ppm or -pgm for available PPM and PGM formats.\n");
  }
  IFS(CreateOutputStream(out_file_name, use_stdout, &stream));
  IFS(IWICImagingFactory_CreateEncoder(factory, container_guid, NULL,
                                       &encoder));
  IFS(IWICBitmapEncoder_Initialize(encoder, stream,
                                   WICBitmapEncoderNoCache));
  IFS(IWICBitmapEncoder_CreateNewFrame(encoder, &frame, NULL));
  IFS(IWICBitmapFrameEncode_Initialize(frame, NULL));
  IFS(IWICBitmapFrameEncode_SetSize(frame, width, height));
  IFS(IWICBitmapFrameEncode_SetPixelFormat(frame, &pixel_format));
  IFS(IWICBitmapFrameEncode_WritePixels(frame, height, stride,
                                        height * stride, rgb));
  IFS(IWICBitmapFrameEncode_Commit(frame));
  IFS(IWICBitmapEncoder_Commit(encoder));

  if (SUCCEEDED(hr) && use_stdout) {
    HGLOBAL image;
    IFS(GetHGlobalFromStream(stream, &image));
    if (SUCCEEDED(hr)) {
      HANDLE std_output = GetStdHandle(STD_OUTPUT_HANDLE);
      DWORD mode;
      const BOOL update_mode = GetConsoleMode(std_output, &mode);
      const void* const image_mem = GlobalLock(image);
      DWORD bytes_written = 0;

      // Clear output processing if necessary, then output the image.
      if (update_mode) SetConsoleMode(std_output, 0);
      if (!WriteFile(std_output, image_mem, (DWORD)GlobalSize(image),
                     &bytes_written, NULL) ||
          bytes_written != GlobalSize(image)) {
        hr = E_FAIL;
      }
      if (update_mode) SetConsoleMode(std_output, mode);
      GlobalUnlock(image);
    }
  }

  if (frame != NULL) IUnknown_Release(frame);
  if (encoder != NULL) IUnknown_Release(encoder);
  if (factory != NULL) IUnknown_Release(factory);
  if (stream != NULL) IUnknown_Release(stream);
  return hr;
}
Example #22
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;
}
Example #23
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;
}
Example #24
0
//////////////////////////////////////////////////////////////////////////
// IDataObject
//////////////////////////////////////////////////////////////////////////
STDMETHODIMP SVNDataObject::GetData(FORMATETC* pformatetcIn, STGMEDIUM* pmedium)
{
	if (pformatetcIn == NULL)
		return E_INVALIDARG;
	if (pmedium == NULL)
		return E_POINTER;
	pmedium->hGlobal = NULL;

	if ((pformatetcIn->tymed & TYMED_ISTREAM) && (pformatetcIn->dwAspect == DVASPECT_CONTENT) && (pformatetcIn->cfFormat == CF_FILECONTENTS))
	{
		// supports the IStream format.
		// The lindex param is the index of the file to return

		// Note: we don't get called for directories since those are simply created and don't
		// need to be fetched.

		// Note2: It would be really nice if we could get a stream from the subversion library
		// from where we could read the file contents. But the Subversion lib is not implemented
		// to *read* from a remote stream but so that the library *writes* to a stream we pass.
		// Since we can't get such a read stream, we have to fetch the file in whole first to
		// a temp location and then pass the shell an IStream for that temp file.
		CTSVNPath filepath;
		IStream * pIStream = NULL;
		if (m_revision.IsWorking())
		{
			if ((pformatetcIn->lindex >= 0)&&(pformatetcIn->lindex < (LONG)m_allPaths.size()))
			{
				filepath = m_allPaths[pformatetcIn->lindex].rootpath;
			}
		}
		else
		{
			filepath = CTempFiles::Instance().GetTempFilePath(true);
			if ((pformatetcIn->lindex >= 0)&&(pformatetcIn->lindex < (LONG)m_allPaths.size()))
			{
				if (!m_svn.Cat(CTSVNPath(m_allPaths[pformatetcIn->lindex].infodata.url), m_pegRev, m_revision, filepath))
				{
					DeleteFile(filepath.GetWinPath());
					return STG_E_ACCESSDENIED;
				}
			}
		}
		HRESULT res = SHCreateStreamOnFile(filepath.GetWinPath(), STGM_READ, &pIStream);
		if (res == S_OK)
		{
			pmedium->pstm = pIStream;
			pmedium->tymed = TYMED_ISTREAM;
			return S_OK;
		}
		return res;
	}
	else if ((pformatetcIn->tymed & TYMED_HGLOBAL) && (pformatetcIn->dwAspect == DVASPECT_CONTENT) && (pformatetcIn->cfFormat == CF_FILEDESCRIPTOR))
	{
		// now it is time to get all sub folders for the directories we have
		SVNInfo svnInfo;
		// find the common directory of all the paths
		CTSVNPath commonDir;
		bool bAllUrls = true;
		for (int i=0; i<m_svnPaths.GetCount(); ++i)
		{
			if (!m_svnPaths[i].IsUrl())
				bAllUrls = false;
			if (commonDir.IsEmpty())
				commonDir = m_svnPaths[i].GetContainingDirectory();
			if (!commonDir.IsEquivalentTo(m_svnPaths[i].GetContainingDirectory()))
			{
				commonDir.Reset();
				break;
			}
		}
		if (bAllUrls && (m_svnPaths.GetCount() > 1) && !commonDir.IsEmpty())
		{
			// if all paths are in the same directory, we can fetch the info recursively
			// from the parent folder to save a lot of time.
			const SVNInfoData * infodata = svnInfo.GetFirstFileInfo(commonDir, m_pegRev, m_revision, svn_depth_infinity);
			while (infodata)
			{
				// check if the returned item is one in our list
				for (int i=0; i<m_svnPaths.GetCount(); ++i)
				{
					if (m_svnPaths[i].IsAncestorOf(CTSVNPath(infodata->url)))
					{
						SVNDataObject::SVNObjectInfoData id = {m_svnPaths[i], *infodata};
						m_allPaths.push_back(id);
						break;
					}
				}
				infodata = svnInfo.GetNextFileInfo();
			}
		}
		else
		{
			for (int i = 0; i < m_svnPaths.GetCount(); ++i)
			{
				if (m_svnPaths[i].IsUrl())
				{
					const SVNInfoData * infodata = svnInfo.GetFirstFileInfo(m_svnPaths[i], m_pegRev, m_revision, svn_depth_infinity);
					while (infodata)
					{
						SVNDataObject::SVNObjectInfoData id = {m_svnPaths[i], *infodata};
						m_allPaths.push_back(id);
						infodata = svnInfo.GetNextFileInfo();
					}
				}
				else
				{
					SVNDataObject::SVNObjectInfoData id = {m_svnPaths[i], SVNInfoData()};
					m_allPaths.push_back(id);
				}
			}
		}
		size_t dataSize = sizeof(FILEGROUPDESCRIPTOR) + ((m_allPaths.size() - 1) * sizeof(FILEDESCRIPTOR));
		HGLOBAL data = GlobalAlloc(GMEM_MOVEABLE | GMEM_SHARE | GMEM_ZEROINIT, dataSize);

		FILEGROUPDESCRIPTOR* files = (FILEGROUPDESCRIPTOR*)GlobalLock(data);
		files->cItems = static_cast<UINT>(m_allPaths.size());
		int index = 0;
		for (vector<SVNDataObject::SVNObjectInfoData>::const_iterator it = m_allPaths.begin(); it != m_allPaths.end(); ++it)
		{
			CString temp;
			if (it->rootpath.IsUrl())
			{
				temp = CUnicodeUtils::GetUnicode(CPathUtils::PathEscape(CUnicodeUtils::GetUTF8(it->rootpath.GetContainingDirectory().GetSVNPathString())));
				temp = it->infodata.url.Mid(temp.GetLength()+1);
				// we have to unescape the urls since the local file system doesn't need them
				// escaped and it would only look really ugly (and be wrong).
				temp = CPathUtils::PathUnescape(temp);
			}
			else
			{
				temp = it->rootpath.GetUIFileOrDirectoryName();
			}
			_tcscpy_s(files->fgd[index].cFileName, MAX_PATH, (LPCTSTR)temp);
			files->fgd[index].dwFlags = FD_ATTRIBUTES | FD_PROGRESSUI | FD_FILESIZE | FD_LINKUI;
			if (it->rootpath.IsUrl())
			{
				files->fgd[index].dwFileAttributes = (it->infodata.kind == svn_node_dir) ? FILE_ATTRIBUTE_DIRECTORY : FILE_ATTRIBUTE_NORMAL;
			}
			else
			{
				files->fgd[index].dwFileAttributes = it->rootpath.IsDirectory() ? FILE_ATTRIBUTE_DIRECTORY : FILE_ATTRIBUTE_NORMAL;
			}
			// Always set the file size to 0 even if we 'know' the file size (infodata.size64).
			// Because for text files, the file size is too low due to the EOLs getting converted
			// to CRLF (from LF as stored in the repository). And a too low file size set here
			// prevents the shell from reading the full file later - it only reads the stream up
			// to the number of bytes specified here. Which means we would end up with a truncated
			// text file (binary files are still ok though).
			files->fgd[index].nFileSizeLow = 0;
			files->fgd[index].nFileSizeHigh = 0;

			++index;
		}

		GlobalUnlock(data);

		pmedium->hGlobal = data;
		pmedium->tymed = TYMED_HGLOBAL;
		return S_OK;
	}
	// handling CF_PREFERREDDROPEFFECT is necessary to tell the shell that it should *not* ask for the
	// CF_FILEDESCRIPTOR until the drop actually occurs. If we don't handle CF_PREFERREDDROPEFFECT, the shell
	// will ask for the file descriptor for every object (file/folder) the mouse pointer hovers over and is
	// a potential drop target.
	else if ((pformatetcIn->tymed & TYMED_HGLOBAL) && (pformatetcIn->cfFormat == CF_PREFERREDDROPEFFECT))
	{
		HGLOBAL data = GlobalAlloc(GMEM_MOVEABLE | GMEM_SHARE | GMEM_ZEROINIT, sizeof(DWORD));
		DWORD* effect = (DWORD*) GlobalLock(data);
		(*effect) = DROPEFFECT_COPY;
		GlobalUnlock(data);
		pmedium->hGlobal = data;
		pmedium->tymed = TYMED_HGLOBAL;
		return S_OK;
	}
	else if ((pformatetcIn->tymed & TYMED_HGLOBAL) && (pformatetcIn->dwAspect == DVASPECT_CONTENT) && (pformatetcIn->cfFormat == CF_TEXT))
	{
		// caller wants text
		// create the string from the path list
		CString text;
		if (m_svnPaths.GetCount())
		{
			// create a single string where the URLs are separated by newlines
			for (int i=0; i<m_svnPaths.GetCount(); ++i)
			{
				if (m_svnPaths[i].IsUrl())
					text += m_svnPaths[i].GetSVNPathString();
				else
					text += m_svnPaths[i].GetWinPathString();
				text += _T("\r\n");
			}
		}
		CStringA texta = CUnicodeUtils::GetUTF8(text);
		pmedium->tymed = TYMED_HGLOBAL;
		pmedium->hGlobal = GlobalAlloc(GHND, (texta.GetLength()+1)*sizeof(char));
		if (pmedium->hGlobal)
		{
			char* pMem = (char*)GlobalLock(pmedium->hGlobal);
			strcpy_s(pMem, texta.GetLength()+1, (LPCSTR)texta);
			GlobalUnlock(pmedium->hGlobal);
		}
		pmedium->pUnkForRelease = NULL;
		return S_OK;
	}
	else if ((pformatetcIn->tymed & TYMED_HGLOBAL) && (pformatetcIn->dwAspect == DVASPECT_CONTENT) && (pformatetcIn->cfFormat == CF_UNICODETEXT))
	{
		// caller wants Unicode text
		// create the string from the path list
		CString text;
		if (m_svnPaths.GetCount())
		{
			// create a single string where the URLs are separated by newlines
			for (int i=0; i<m_svnPaths.GetCount(); ++i)
			{
				if (m_svnPaths[i].IsUrl())
					text += m_svnPaths[i].GetSVNPathString();
				else
					text += m_svnPaths[i].GetWinPathString();
				text += _T("\r\n");
			}
		}
		pmedium->tymed = TYMED_HGLOBAL;
		pmedium->hGlobal = GlobalAlloc(GHND, (text.GetLength()+1)*sizeof(TCHAR));
		if (pmedium->hGlobal)
		{
			TCHAR* pMem = (TCHAR*)GlobalLock(pmedium->hGlobal);
			_tcscpy_s(pMem, text.GetLength()+1, (LPCTSTR)text);
			GlobalUnlock(pmedium->hGlobal);
		}
		pmedium->pUnkForRelease = NULL;
		return S_OK;
	}
	else if ((pformatetcIn->tymed & TYMED_HGLOBAL) && (pformatetcIn->dwAspect == DVASPECT_CONTENT) && (pformatetcIn->cfFormat == CF_SVNURL))
	{
		// caller wants the svn url
		// create the string from the path list
		CString text;
		if (m_svnPaths.GetCount())
		{
			// create a single string where the URLs are separated by newlines
			for (int i=0; i<m_svnPaths.GetCount(); ++i)
			{
				if (m_svnPaths[i].IsUrl())
				{
					text += m_svnPaths[i].GetSVNPathString();
					text += _T("?");
					text += m_revision.ToString();
				}
				else
					text += m_svnPaths[i].GetWinPathString();
				text += _T("\r\n");
			}
		}
		pmedium->tymed = TYMED_HGLOBAL;
		pmedium->hGlobal = GlobalAlloc(GHND, (text.GetLength()+1)*sizeof(TCHAR));
		if (pmedium->hGlobal)
		{
			TCHAR* pMem = (TCHAR*)GlobalLock(pmedium->hGlobal);
			_tcscpy_s(pMem, text.GetLength()+1, (LPCTSTR)text);
			GlobalUnlock(pmedium->hGlobal);
		}
		pmedium->pUnkForRelease = NULL;
		return S_OK;
	}
	else if ((pformatetcIn->tymed & TYMED_HGLOBAL) && (pformatetcIn->dwAspect == DVASPECT_CONTENT) && (pformatetcIn->cfFormat == CF_HDROP))
	{
		int nLength = 0;

		for (int i=0;i<m_svnPaths.GetCount();i++)
		{
			nLength += m_svnPaths[i].GetWinPathString().GetLength();
			nLength += 1; // '\0' separator
		}

		int nBufferSize = sizeof(DROPFILES) + (nLength+1)*sizeof(TCHAR);
		char * pBuffer = new char[nBufferSize];

		SecureZeroMemory(pBuffer, nBufferSize);

		DROPFILES* df = (DROPFILES*)pBuffer;
		df->pFiles = sizeof(DROPFILES);
		df->fWide = 1;

		TCHAR* pFilenames = (TCHAR*)(pBuffer + sizeof(DROPFILES));
		TCHAR* pCurrentFilename = pFilenames;

		for (int i=0;i<m_svnPaths.GetCount();i++)
		{
			CString str = m_svnPaths[i].GetWinPathString();
			wcscpy_s(pCurrentFilename, str.GetLength()+1, (LPCWSTR)str);
			pCurrentFilename += str.GetLength();
			*pCurrentFilename = '\0'; // separator between file names
			pCurrentFilename++;
		}
		*pCurrentFilename = '\0'; // terminate array

		pmedium->tymed = TYMED_HGLOBAL;
		pmedium->hGlobal = GlobalAlloc(GMEM_ZEROINIT|GMEM_MOVEABLE|GMEM_DDESHARE, nBufferSize);
		if (pmedium->hGlobal)
		{
			LPVOID pMem = ::GlobalLock(pmedium->hGlobal);
			if (pMem)
				memcpy(pMem, pBuffer, nBufferSize);
			GlobalUnlock(pmedium->hGlobal);
		}
		pmedium->pUnkForRelease = NULL;
		delete [] pBuffer;
		return S_OK;
	}

	for (size_t i=0; i<m_vecFormatEtc.size(); ++i)
	{
		if ((pformatetcIn->tymed == m_vecFormatEtc[i]->tymed) &&
			(pformatetcIn->dwAspect == m_vecFormatEtc[i]->dwAspect) &&
			(pformatetcIn->cfFormat == m_vecFormatEtc[i]->cfFormat))
		{
			CopyMedium(pmedium, m_vecStgMedium[i], m_vecFormatEtc[i]);
			return S_OK;
		}
	}

	return DV_E_FORMATETC;
}
Example #25
0
void CompileNSISScript() {
  DragAcceptFiles(g_sdata.hwnd,FALSE);
  ClearLog(g_sdata.hwnd);
  SetTitle(g_sdata.hwnd,NULL);
  if (lstrlen(g_sdata.script)==0) {
    LogMessage(g_sdata.hwnd,USAGE);

    static const PACKEDCMDID_T cmds [] = {
      PACKCMDID(IDM_RECOMPILE),PACKCMDID(IDM_RECOMPILE_TEST),PACKCMDID(IDM_TEST), 
      PACKCMDID(IDM_BROWSESCR),PACKCMDID(IDM_EDITSCRIPT)
    };
    for (UINT i = 0; i < COUNTOF(cmds); ++i) {
      int id = UNPACKCMDID(cmds[i]);
      EnableMenuItem(g_sdata.menu,id,MF_GRAYED);
      EnableToolBarButton(id,FALSE);
    }
    EnableWindow(GetDlgItem(g_sdata.hwnd,IDC_TEST),FALSE);
    DragAcceptFiles(g_sdata.hwnd,TRUE);
    return;
  }
  if (!g_sdata.compile_command) {
    TCHAR *symbols = BuildSymbols();
    TCHAR compressor[40];

    compressor[0] = _T('\0');
    if(*g_sdata.compressor_name)
      wsprintf(compressor,_T("/X\"SetCompressor /FINAL %s\""),g_sdata.compressor_name);

    TCHAR *args = (TCHAR *) GlobalLock(g_sdata.script_cmd_args);

    size_t byteSize = sizeof(TCHAR)*(
      /* makensis.exe        */ lstrlen(EXENAME)        + /* space */ 1 +
      /* script path         */ lstrlen(g_sdata.script) + /* space */ 1 +
      /* script cmd args     */ lstrlen(args)           + /* space */ 1 +
      /* defines /Dblah=...  */ lstrlen(symbols)        + /* space */ 1 +
      /* /XSetCompressor...  */ lstrlen(compressor)     + /* space */ 1 +
      /* /V + UINT8          */ 2 + 3                   + /* space */ 1 +
      /* /NOTIFYHWND + HWND  */ COUNTOF(_T("/NOTIFYHWND -4294967295")) + /* space */ 1
      +6); /* for -- \"\" and NULL */
      
    g_sdata.compile_command = (TCHAR*) MemAlloc(byteSize);

    wsprintf(
      g_sdata.compile_command,
      _T("%s /V%u %s %s /NOTIFYHWND %d %s -- \"%s\""),
      EXENAME,
      g_sdata.verbosity,
      compressor,
      symbols,
      g_sdata.hwnd,
      args,
      g_sdata.script
    );

    GlobalUnlock(g_sdata.script_cmd_args);
    MemFree(symbols);
  }
  MemSafeFree(g_sdata.input_script);
  MemSafeFree(g_sdata.output_exe);
  g_sdata.input_script = 0;
  g_sdata.output_exe = 0;
  g_sdata.warnings = 0;
  g_sdata.logLength = 0;
  // Disable buttons during compile
  DisableItems(g_sdata.hwnd);
  DWORD tid;
  g_sdata.thread=CreateThread(NULL,0,MakeNSISProc,0,0,&tid);
}
Example #26
0
/***********************************************************************
 *           dibdrv_SelectBrush
 */
HBRUSH CDECL dibdrv_SelectBrush( PHYSDEV dev, HBRUSH hbrush )
{
    PHYSDEV next = GET_NEXT_PHYSDEV( dev, pSelectBrush );
    dibdrv_physdev *pdev = get_dibdrv_pdev(dev);
    LOGBRUSH logbrush;

    TRACE("(%p, %p)\n", dev, hbrush);

    if (!GetObjectW( hbrush, sizeof(logbrush), &logbrush )) return 0;

    if (hbrush == GetStockObject( DC_BRUSH ))
        logbrush.lbColor = GetDCBrushColor( dev->hdc );

    pdev->brush_style = logbrush.lbStyle;

    pdev->defer |= DEFER_BRUSH;

    free_pattern_brush( pdev );

    switch(logbrush.lbStyle)
    {
    case BS_SOLID:
        pdev->brush_colorref = logbrush.lbColor;
        pdev->brush_color = get_fg_color( pdev, pdev->brush_colorref );
        calc_and_xor_masks(GetROP2(dev->hdc), pdev->brush_color, &pdev->brush_and, &pdev->brush_xor);
        pdev->brush_rects = solid_brush;
        pdev->defer &= ~DEFER_BRUSH;
        break;

    case BS_NULL:
        pdev->brush_rects = null_brush;
        pdev->defer &= ~DEFER_BRUSH;
        break;

    case BS_DIBPATTERN:
    {
        BITMAPINFOHEADER *bi = GlobalLock((HGLOBAL)logbrush.lbHatch);
        dib_info orig_dib;
        WORD usage = LOWORD(logbrush.lbColor);
        HPALETTE pal = (usage == DIB_PAL_COLORS) ? GetCurrentObject(dev->hdc, OBJ_PAL) : NULL;

        if(!bi) return NULL;
        if(init_dib_info_from_packed(&orig_dib, bi, usage, pal))
        {
            copy_dib_color_info(&pdev->brush_dib, &pdev->dib);
            if(convert_dib(&pdev->brush_dib, &orig_dib))
            {
                pdev->brush_rects = pattern_brush;
                pdev->defer &= ~DEFER_BRUSH;
            }
            free_dib_info(&orig_dib, FALSE);
        }
        GlobalUnlock((HGLOBAL)logbrush.lbHatch);
        break;
    }

    case BS_HATCHED:
    {
        if(logbrush.lbHatch > HS_DIAGCROSS) return 0;
        pdev->brush_hatch = logbrush.lbHatch;
        pdev->brush_colorref = logbrush.lbColor;
        pdev->brush_color = get_fg_color( pdev, pdev->brush_colorref );
        calc_and_xor_masks(GetROP2(dev->hdc), pdev->brush_color, &pdev->brush_and, &pdev->brush_xor);
        pdev->brush_rects = pattern_brush;
        pdev->defer &= ~DEFER_BRUSH;
        break;
    }

    default:
        break;
    }

    return next->funcs->pSelectBrush( next, hbrush );
}
Example #27
0
__declspec(dllexport) int Div(HWND hWnd,struct TPCLIPINFO *ClipInfo,int Flag,int cnt)
{

	HGLOBAL hRetMem;
	char *buf,*ret;
	char options[256];
	char buffer[256];
	int hSize;

	//データが無い場合は処理を行わない。
	if(ClipInfo == NULL){
		return -1;
	}

	//テキスト以外は処理を行わない。
	if(ClipInfo->Type != CF_TEXT && ClipInfo->Type != CF_OEMTEXT){
		return -1;
	}

	//メモリのサイズを取得する。
	if((hSize = GlobalSize((HGLOBAL)ClipInfo->Mem)) == 0){
		return -1;
	}
	if((buf = GlobalLock((HGLOBAL)ClipInfo->Mem)) == NULL){
		return -1;
	}

	//戻り用のメモリを確保する。
	//とりあえず2倍の量を確保していますが、必要な分で構いません。
	if((hRetMem = GlobalAlloc(GHND,hSize * 2+256)) == NULL){
		GlobalUnlock((HGLOBAL)ClipInfo->Mem);
		return -1;
	}
	if((ret = GlobalLock(hRetMem)) == NULL){
		GlobalUnlock((HGLOBAL)ClipInfo->Mem);
		GlobalFree(hRetMem);
		return -1;
	}




	// **************************************
	// ここで文字列の処理を行います。
	// buf は処理対象の文字列が入ったバッファです。
	// ret は処理後のバッファです。
	// ret に処理を施した文字列を入れて下さい。
	// **************************************
	memset(options,0x00,sizeof(options));
	Dlg(ret,GetForegroundWindow(),"class=?","input class","");
	if(strcmp(ret,"\0")!=0){
		wsprintf(buffer," class=\"%s\"",ret);
		strcat(options,buffer);
	}

	wsprintf(ret,"<div%s>%s</div>",options,buf);

	//処理したバッファのサイズを取得する。
	hSize = lstrlen(ret) + 1;

	GlobalUnlock(hRetMem);
	//再確保を行う。
	if((hRetMem = GlobalReAlloc(hRetMem,hSize,0)) == NULL){
		GlobalUnlock((HGLOBAL)ClipInfo->Mem);
		return -1;
	}

	//元のメモリは解放する。
	GlobalUnlock((HGLOBAL)ClipInfo->Mem);
	GlobalFree(ClipInfo->Mem);

	//構造体に処理をしたメモリのハンドルを設定する。
	ClipInfo->Mem = hRetMem;

	return 0;
}
Example #28
0
/*
 * DialogTemplate - build a dialog template
 */
TEMPLATE_HANDLE DialogTemplate( LONG dtStyle, int dtx, int dty, int dtcx,
                                int dtcy, char *menuname, char *classname,
                                char *captiontext, int pointsize,
                                char *typeface )
{
    TEMPLATE_HANDLE     data;
    UINT                blocklen,menulen, classlen, captionlen, typefacelen;
    UINT                _ISFAR *numbytes;
    char                _ISFAR *dlgtemp;
    char                _ISFAR *dlgtypeface;
    _DLGTEMPLATE        _ISFAR *dt;
    FONTINFO            _ISFAR *fi;


    /*
     * get size of block and allocate memory
     */
    menulen = SLEN( menuname );
    classlen = SLEN( classname );
    captionlen = SLEN( captiontext );

    blocklen = sizeof( UINT ) + sizeof( _DLGTEMPLATE ) + menulen + classlen +
              captionlen;

    if( dtStyle & DS_SETFONT ) {
      typefacelen = SLEN( typeface );
      blocklen += sizeof(short) + typefacelen;
    } else {
      typefacelen = 0;
    }

    ADJUST_BLOCKLEN( blocklen );
    data = GlobalAlloc( GMEM_MOVEABLE | GMEM_ZEROINIT, blocklen );
    if( data == NULL ) return( NULL );

    numbytes = (UINT _ISFAR *) MK_FP32( GlobalLock( data ) );
    *numbytes = (UINT) blocklen;

    /*
     * set up template
     */

    dt = (_DLGTEMPLATE _ISFAR *) (numbytes + 1);

    dt->dtStyle = dtStyle;
    dt->dtItemCount = 0;
    dt->dtX = dtx;
    dt->dtY = dty;
    dt->dtCX = dtcx;
    dt->dtCY = dtcy;

    dlgtemp = (char _ISFAR *) (dt + 1);

    /*
     * add extra strings to block
     */
    dlgtemp = copyString( dlgtemp, menuname, menulen );
    dlgtemp = copyString( dlgtemp, classname, classlen );
    dlgtemp = copyString( dlgtemp, captiontext, captionlen );


    /*
     * add font data (if needed)
     */
    if (dtStyle & DS_SETFONT) {
      #ifdef ALIGN_WORDS
          fi = (FONTINFO _ISFAR *) ((u_int)dlgtemp + 4 - (u_int)dlgtemp % 4);
      #else
          fi = (FONTINFO _ISFAR *) dlgtemp;
      #endif
      fi->PointSize = pointsize;
      dlgtypeface = (char _ISFAR *) (fi + 1);
      copyString( dlgtypeface, typeface, typefacelen );
    }

    GlobalUnlock( data );
    return( data );

} /* DialogTemplate */
Example #29
0
BOOL CDialogTemplate::SetFont(LPCTSTR lpFaceName, WORD nFontSize)
{
	ASSERT(m_hTemplate != NULL);

	if (m_dwTemplateSize == 0)
		return FALSE;

	DLGTEMPLATE* pTemplate = (DLGTEMPLATE*)GlobalLock(m_hTemplate);

	BOOL bDialogEx = IsDialogEx(pTemplate);
	BOOL bHasFont = ::HasFont(pTemplate);
	int cbFontAttr = FontAttrSize(bDialogEx);

	if (bDialogEx)
		((DLGTEMPLATEEX*)pTemplate)->style |= DS_SETFONT;
	else
		pTemplate->style |= DS_SETFONT;

	int nFaceNameLen = lstrlen(lpFaceName);
	if( nFaceNameLen >= LF_FACESIZE )
	{
		// Name too long
		return FALSE;
	}

#ifdef _UNICODE
	int cbNew = cbFontAttr + ((nFaceNameLen + 1) * sizeof(TCHAR));
	BYTE* pbNew = (BYTE*)lpFaceName;
#else
	WCHAR wszFaceName [LF_FACESIZE];
	int cbNew = cbFontAttr + 2 * MultiByteToWideChar(CP_ACP, 0, lpFaceName, -1, wszFaceName, LF_FACESIZE);
	BYTE* pbNew = (BYTE*)wszFaceName;
#endif
	if (cbNew < cbFontAttr)
	{
		return FALSE;
	}
	BYTE* pb = GetFontSizeField(pTemplate);
	int cbOld = (int)(bHasFont ? cbFontAttr + 2 * (wcslen((WCHAR*)(pb + cbFontAttr)) + 1) : 0);

	BYTE* pOldControls = (BYTE*)(((DWORD_PTR)pb + cbOld + 3) & ~DWORD_PTR(3));
	BYTE* pNewControls = (BYTE*)(((DWORD_PTR)pb + cbNew + 3) & ~DWORD_PTR(3));

	WORD nCtrl = bDialogEx ? (WORD)((DLGTEMPLATEEX*)pTemplate)->cDlgItems :
		(WORD)pTemplate->cdit;

	if (cbNew != cbOld && nCtrl > 0)
	{
		size_t nBuffLeftSize=(size_t)(m_dwTemplateSize - (pOldControls - (BYTE*)pTemplate));
		if (nBuffLeftSize > m_dwTemplateSize)
		{
			return FALSE;
		}
		Checked::memmove_s(pNewControls,nBuffLeftSize, pOldControls, nBuffLeftSize);
	}

	*(WORD*)pb = nFontSize;
	Checked::memmove_s(pb + cbFontAttr, cbNew - cbFontAttr, pbNew, cbNew - cbFontAttr);

   //IA64: Max dialog template size of 4GB should be fine
	m_dwTemplateSize += ULONG(pNewControls - pOldControls);

	GlobalUnlock(m_hTemplate);
	m_bSystemFont = FALSE;
	return TRUE;
}
Example #30
0
HDIB FAR CreateDIB(DWORD dwWidth, DWORD dwHeight, WORD wBitCount)
{
   BITMAPINFOHEADER bi;         // bitmap header
   LPBITMAPINFOHEADER lpbi;     // pointer to BITMAPINFOHEADER
   DWORD dwLen;                 // size of memory block
   HDIB hDIB;
   DWORD dwBytesPerLine;        // Number of bytes per scanline


   // Make sure bits per pixel is valid
   if (wBitCount <= 1)
      wBitCount = 1;
   else if (wBitCount <= 4)
      wBitCount = 4;
   else if (wBitCount <= 8)
      wBitCount = 8;
   else if (wBitCount <= 24)
      wBitCount = 24;
   else
      wBitCount = 4;  // set default value to 4 if parameter is bogus

   // initialize BITMAPINFOHEADER
   bi.biSize = sizeof(BITMAPINFOHEADER);
   bi.biWidth = dwWidth;         // fill in width from parameter
   bi.biHeight = dwHeight;       // fill in height from parameter
   bi.biPlanes = 1;              // must be 1
   bi.biBitCount = wBitCount;    // from parameter
   bi.biCompression = BI_RGB;    
   bi.biSizeImage = 0;           // 0's here mean "default"
   bi.biXPelsPerMeter = 0;
   bi.biYPelsPerMeter = 0;
   bi.biClrUsed = 0;
   bi.biClrImportant = 0;

   // calculate size of memory block required to store the DIB.  This
   // block should be big enough to hold the BITMAPINFOHEADER, the color
   // table, and the bits

   dwBytesPerLine = WIDTHBYTES(wBitCount * dwWidth);
   dwLen = bi.biSize + PaletteSize((LPSTR)&bi) + (dwBytesPerLine * dwHeight);

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

   // major bummer if we couldn't get memory block
   if (!hDIB)
   {
      return NULL;
   }

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

   // use our bitmap info structure to fill in first part of
   // our DIB with the BITMAPINFOHEADER
   *lpbi = bi;

   // Since we don't know what the colortable and bits should contain,
   // just leave these blank.  Unlock the DIB and return the HDIB.

   GlobalUnlock(hDIB);

   /* return handle to the DIB */
   return hDIB;
}