Пример #1
0
ImageTargetFileWic::ImageTargetFileWic( DataTargetRef dataTarget, ImageSourceRef imageSource, ImageTarget::Options options, const string &extensionData )
	: ImageTarget(), mDataTarget( dataTarget )
{
	mCodecGUID = getExtensionMap()[extensionData];

	setSize( imageSource->getWidth(), imageSource->getHeight() );

	// determine the pixel format we'll request
	WICPixelFormatGUID formatGUID;
	if( imageSource->hasAlpha() ) {
		bool premultAlpha = imageSource->isPremultiplied();
		// WIC doesn't support gray+alpha, so we need to do RGBA regardless
		if( imageSource->getDataType() == ImageIo::UINT8 )
			formatGUID = premultAlpha ? GUID_WICPixelFormat32bppPBGRA : GUID_WICPixelFormat32bppBGRA;
		else if( imageSource->getDataType() == ImageIo::UINT16 )
			formatGUID = premultAlpha ? GUID_WICPixelFormat64bppPRGBA : GUID_WICPixelFormat64bppRGBA;
		else
			formatGUID = premultAlpha ? GUID_WICPixelFormat128bppPRGBAFloat : GUID_WICPixelFormat128bppRGBAFloat;
	}
	else {
		ImageIo::ColorModel cm = options.isColorModelDefault() ? imageSource->getColorModel() : options.getColorModel();
		if( cm == ImageIo::CM_GRAY ) {
			if( imageSource->getDataType() == ImageIo::UINT8 )
				formatGUID = GUID_WICPixelFormat8bppGray;
			else if( imageSource->getDataType() == ImageIo::UINT16 )
				formatGUID = GUID_WICPixelFormat16bppGray;
			else
				formatGUID = GUID_WICPixelFormat32bppGrayFloat;
		}
		else { // RGB
			if( imageSource->getDataType() == ImageIo::UINT8 )
				formatGUID = GUID_WICPixelFormat24bppBGR;
			else if( imageSource->getDataType() == ImageIo::UINT16 )
				formatGUID = GUID_WICPixelFormat48bppRGB;
			else
				formatGUID = GUID_WICPixelFormat128bppRGBFloat;
		}
	}
	
	::HRESULT hr = S_OK;

	msw::initializeCom();

 // Create WIC factory
    IWICImagingFactory *IWICFactoryP = NULL;
    hr = ::CoCreateInstance( CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&IWICFactoryP) );
	if( ! SUCCEEDED( hr ) )
		throw ImageIoExceptionFailedWrite( "Could not create WIC Factory." );
	shared_ptr<IWICImagingFactory> IWICFactory = msw::makeComShared( IWICFactoryP );

	IWICBitmapEncoder *encoderP = NULL;
	hr = IWICFactory->CreateEncoder( *mCodecGUID, 0, &encoderP );
	if( ! SUCCEEDED( hr ) )
		throw ImageIoExceptionFailedWrite( "Could not create WIC Encoder." );
	mEncoder = msw::makeComShared( encoderP );
	
	// create the stream		
	IWICStream *pIWICStream = NULL;
	hr = IWICFactory->CreateStream( &pIWICStream );
	if( ! SUCCEEDED(hr) )
		throw ImageIoExceptionFailedWrite( "Could not create WIC stream." );
	shared_ptr<IWICStream> stream = msw::makeComShared( pIWICStream );
	
	// initialize the stream based on properties of the cinder::DataSouce
	if( mDataTarget->providesFilePath() ) {
#if defined( CINDER_WINRT)
		std::string s = mDataTarget->getFilePath().string();
		std::wstring filePath =	std::wstring(s.begin(), s.end());                 
#else
		std::wstring filePath =	mDataTarget->getFilePath().wstring().c_str();
#endif
		hr = stream->InitializeFromFilename( filePath.c_str(), GENERIC_WRITE );
		if( ! SUCCEEDED(hr) )
			throw ImageIoExceptionFailedWrite( "Could not initialize WIC Stream from filename." );
	}
	else {
		shared_ptr<msw::ComOStream> comOStream = msw::makeComShared( new msw::ComOStream( mDataTarget->getStream() ) );
		hr = stream->InitializeFromIStream( comOStream.get() );
		if( ! SUCCEEDED(hr) )
			throw ImageIoExceptionFailedWrite( "Could not initialize WIC Stream from IStream." );
	}
	
	hr = mEncoder->Initialize( stream.get(), WICBitmapEncoderNoCache );
	if( ! SUCCEEDED( hr ) )
		throw ImageIoExceptionFailedWrite( "Could not initialize WIC Encoder." );

	// create the frame encoder
	IPropertyBag2 *pPropertybag = NULL;
	IWICBitmapFrameEncode *pBitmapFrame = NULL;
	hr = mEncoder->CreateNewFrame( &pBitmapFrame, &pPropertybag );
	if( ! SUCCEEDED( hr ) )
		throw ImageIoExceptionFailedWrite( "Could not ceate WIC Frame." );
	mBitmapFrame = msw::makeComShared( pBitmapFrame );

	// setup the propertyBag to express quality
	PROPBAG2 option = { 0 };
    option.pstrName = L"ImageQuality";
    VARIANT varValue;    
    VariantInit(&varValue);
    varValue.vt = VT_R4;
    varValue.fltVal = options.getQuality();      
    hr = pPropertybag->Write( 1, &option, &varValue );

	hr = mBitmapFrame->Initialize( pPropertybag );
	if( ! SUCCEEDED( hr ) )
		throw ImageIoExceptionFailedWrite( "Could not initialize WIC PROPBAG2." );
	
	hr = mBitmapFrame->SetSize( mWidth, mHeight );
	if( ! SUCCEEDED( hr ) )
		throw ImageIoExceptionFailedWrite( "Could not set WIC Frame size." );
	
	// ask for our ideal pixel format and then process the one we actually get
	hr = mBitmapFrame->SetPixelFormat( &formatGUID );
	if( ! SUCCEEDED( hr ) )
		throw ImageIoExceptionFailedWrite( "Could not set WIC Frame pixel format." );
	
	setupPixelFormat( formatGUID );
	
	mData = shared_ptr<uint8_t>( new uint8_t[mHeight * mRowBytes], std::default_delete<uint8_t[]>() );
}
Пример #2
0
int main(int argc, char* argv[])
{
	HRESULT hr;
	IADs *pADs=NULL;
	LPWSTR pszADsPath = L"LDAP://CN=Jane Johnson,OU=testOU,DC=testDom1,DC=testDom2,DC=microsoft,DC=com";

	CoInitialize(NULL);

	///////////////////////////////////
	// Modifying attributes via IADs
	////////////////////////////////////
	hr = ADsGetObject(pszADsPath,
		              IID_IADs, 
			   	      (void**) &pADs );

	if (!SUCCEEDED(hr) )
	{
		return hr;
	}

	VARIANT var;
	
	
	// we omit checking result for brevity..

	// First Name
	VariantInit(&var);
	V_BSTR(&var) = SysAllocString(L"Janet");
	V_VT(&var) = VT_BSTR;
	hr = pADs->Put( L"givenName", var );

	// Last Name
	VariantClear(&var);
	V_BSTR(&var) = SysAllocString(L"Johns");
	V_VT(&var) = VT_BSTR;
	hr = pADs->Put( L"sn", var ); 
	VariantClear(&var);


	// Other Telephones
	LPWSTR pszPhones[] = { L"425 844 1234", L"425 924 4321" };
	DWORD dwNumber = sizeof( pszPhones ) /sizeof(LPWSTR);

	hr = ADsBuildVarArrayStr( pszPhones, dwNumber, &var );
	hr = pADs->Put( L"otherTelephone", var ); 
	VariantClear(&var);

	hr = pADs->SetInfo();
	pADs->Release();

	if (!SUCCEEDED(hr) )
	{
		
		return hr;
	}



	/////////////////////////////////////////////////
	// Alternatively, you can use IDirectoryObject
	//////////////////////////////////////////////////
	IDirectoryObject *pDir=NULL;
	hr = ADsGetObject(pszADsPath,
		              IID_IDirectoryObject, 
			   	      (void**) &pDir );

	if ( !SUCCEEDED(hr) )
	{
		return hr;
	}


	
	DWORD  dwReturn;
	ADSVALUE  snValue;
	ADSVALUE  fNameValue;
	ADSVALUE  phoneValue[2];

	ADS_ATTR_INFO  attrInfo[] = {   
		{L"givenName",ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING,&snValue,1},
		{L"sn", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING,&fNameValue,1 },
		{L"otherTelephone", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING, phoneValue,2 }
								};
	DWORD dwAttrs = sizeof(attrInfo)/sizeof(ADS_ATTR_INFO); 

	///// First Name ///////////
	fNameValue.dwType=ADSTYPE_CASE_IGNORE_STRING;
	fNameValue.CaseIgnoreString = L"Janet";
	
 
	///// Last Name ///////////
	snValue.dwType= ADSTYPE_CASE_IGNORE_STRING;
	snValue.CaseIgnoreString = L"Johns";
	
	///// Other Telephone ///////////
	phoneValue[0].dwType = ADSTYPE_CASE_IGNORE_STRING;
	phoneValue[0].CaseIgnoreString = L"425 844 1234";

	phoneValue[1].dwType = ADSTYPE_CASE_IGNORE_STRING;
	phoneValue[1].CaseIgnoreString = L"425 924 4321";

	hr = pDir->SetObjectAttributes(attrInfo, dwAttrs, &dwReturn);

	pDir->Release();

	if ( !SUCCEEDED(hr) )
	{
		return hr;
	}



	CoUninitialize();
	return 0;
}
Пример #3
0
static void test_namespace(void)
{
    static const WCHAR winetestW[] = {'w','i','n','e','t','e','s','t',0};
    static const WCHAR backslashW[] = {'\\',0};
    static const WCHAR clsidW[] = {
        ':',':','{','6','4','5','F','F','0','4','0','-','5','0','8','1','-',
        '1','0','1','B','-','9','F','0','8','-',
        '0','0','A','A','0','0','2','F','9','5','4','E','}',0
    };

    static WCHAR tempW[MAX_PATH], curW[MAX_PATH];
    WCHAR *long_pathW = NULL;
    HRESULT r;
    IShellDispatch *sd;
    Folder *folder;
    Folder2 *folder2;
    FolderItem *item;
    VARIANT var;
    BSTR title, item_path;
    int len;

    r = CoCreateInstance(&CLSID_Shell, NULL, CLSCTX_INPROC_SERVER,
                         &IID_IShellDispatch, (LPVOID*)&sd);
    if (r == REGDB_E_CLASSNOTREG) /* NT4 */
    {
        win_skip("skipping IShellDispatch tests\n");
        return;
    }
    ok(SUCCEEDED(r), "CoCreateInstance failed: %08x\n", r);
    if (FAILED(r))
        return;

    VariantInit(&var);
    folder = (void*)0xdeadbeef;
    r = IShellDispatch_NameSpace(sd, var, &folder);
    ok(r == S_FALSE, "expected S_FALSE, got %08x\n", r);
    ok(folder == NULL, "expected NULL, got %p\n", folder);

    V_VT(&var) = VT_I4;
    V_I4(&var) = -1;
    folder = (void*)0xdeadbeef;
    r = IShellDispatch_NameSpace(sd, var, &folder);
    todo_wine {
        ok(r == S_FALSE, "expected S_FALSE, got %08x\n", r);
        ok(folder == NULL, "got %p\n", folder);
    }
    V_VT(&var) = VT_I4;
    V_I4(&var) = ssfPROGRAMFILES;
    r = IShellDispatch_NameSpace(sd, var, &folder);
    ok(r == S_OK ||
       broken(r == S_FALSE), /* NT4 */
       "IShellDispatch::NameSpace failed: %08x\n", r);
    if (r == S_OK)
    {
        static WCHAR path[MAX_PATH];

        if (pSHGetFolderPathW)
        {
            r = pSHGetFolderPathW(NULL, CSIDL_PROGRAM_FILES, NULL,
                                  SHGFP_TYPE_CURRENT, path);
            ok(r == S_OK, "SHGetFolderPath failed: %08x\n", r);
        }
        r = Folder_get_Title(folder, &title);
        todo_wine
        ok(r == S_OK, "Folder::get_Title failed: %08x\n", r);
        if (r == S_OK)
        {
            /* On Win2000-2003 title is equal to program files directory name in
               HKLM\Software\Microsoft\Windows\CurrentVersion\ProgramFilesDir.
               On newer Windows it seems constant and is not changed
               if the program files directory name is changed */
            if (pSHGetSpecialFolderLocation && pSHGetNameFromIDList)
            {
                LPITEMIDLIST pidl;
                PWSTR name;

                r = pSHGetSpecialFolderLocation(NULL, CSIDL_PROGRAM_FILES, &pidl);
                ok(r == S_OK, "SHGetSpecialFolderLocation failed: %08x\n", r);
                r = pSHGetNameFromIDList(pidl, SIGDN_NORMALDISPLAY, &name);
                ok(r == S_OK, "SHGetNameFromIDList failed: %08x\n", r);
                todo_wine
                ok(!lstrcmpW(title, name), "expected %s, got %s\n",
                   wine_dbgstr_w(name), wine_dbgstr_w(title));
                CoTaskMemFree(name);
                CoTaskMemFree(pidl);
            }
            else if (pSHGetFolderPathW)
            {
                WCHAR *p;

                p = path + lstrlenW(path);
                while (path < p && *(p - 1) != '\\')
                    p--;
                ok(!lstrcmpiW(title, p), "expected %s, got %s\n",
                   wine_dbgstr_w(p), wine_dbgstr_w(title));
            }
            else skip("skipping Folder::get_Title test\n");
            SysFreeString(title);
        }
        r = Folder_QueryInterface(folder, &IID_Folder2, (LPVOID*)&folder2);
        ok(r == S_OK, "Folder::QueryInterface failed: %08x\n", r);
        if (r == S_OK)
        {
            r = Folder2_get_Self(folder2, &item);
            ok(r == S_OK, "Folder::get_Self failed: %08x\n", r);
            if (r == S_OK)
            {
                r = FolderItem_get_Path(item, &item_path);
                ok(r == S_OK, "FolderItem::get_Path failed: %08x\n", r);
                if (pSHGetFolderPathW)
                    ok(!lstrcmpiW(item_path, path), "expected %s, got %s\n",
                       wine_dbgstr_w(path), wine_dbgstr_w(item_path));
                SysFreeString(item_path);
                FolderItem_Release(item);
            }
            Folder2_Release(folder2);
        }
        Folder_Release(folder);
    }

    V_VT(&var) = VT_I4;
    V_I4(&var) = ssfBITBUCKET;
    r = IShellDispatch_NameSpace(sd, var, &folder);
    ok(r == S_OK ||
       broken(r == S_FALSE), /* NT4 */
       "IShellDispatch::NameSpace failed: %08x\n", r);
    if (r == S_OK)
    {
        r = Folder_QueryInterface(folder, &IID_Folder2, (LPVOID*)&folder2);
        ok(r == S_OK ||
           broken(r == E_NOINTERFACE), /* NT4 */
           "Folder::QueryInterface failed: %08x\n", r);
        if (r == S_OK)
        {
            r = Folder2_get_Self(folder2, &item);
            ok(r == S_OK, "Folder::get_Self failed: %08x\n", r);
            if (r == S_OK)
            {
                r = FolderItem_get_Path(item, &item_path);
                todo_wine
                ok(r == S_OK, "FolderItem::get_Path failed: %08x\n", r);
                todo_wine
                ok(!lstrcmpW(item_path, clsidW), "expected %s, got %s\n",
                   wine_dbgstr_w(clsidW), wine_dbgstr_w(item_path));
                SysFreeString(item_path);
                FolderItem_Release(item);
            }
            Folder2_Release(folder2);
        }
        Folder_Release(folder);
    }

    GetTempPathW(MAX_PATH, tempW);
    GetCurrentDirectoryW(MAX_PATH, curW);
    SetCurrentDirectoryW(tempW);
    CreateDirectoryW(winetestW, NULL);
    V_VT(&var) = VT_BSTR;
    V_BSTR(&var) = SysAllocString(winetestW);
    r = IShellDispatch_NameSpace(sd, var, &folder);
    ok(r == S_FALSE, "expected S_FALSE, got %08x\n", r);
    SysFreeString(V_BSTR(&var));

    GetFullPathNameW(winetestW, MAX_PATH, tempW, NULL);
    if (pGetLongPathNameW)
    {
        len = pGetLongPathNameW(tempW, NULL, 0);
        long_pathW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        if (long_pathW)
            pGetLongPathNameW(tempW, long_pathW, len);
    }
    V_VT(&var) = VT_BSTR;
    V_BSTR(&var) = SysAllocString(tempW);
    r = IShellDispatch_NameSpace(sd, var, &folder);
    ok(r == S_OK, "IShellDispatch::NameSpace failed: %08x\n", r);
    if (r == S_OK)
    {
        r = Folder_get_Title(folder, &title);
        ok(r == S_OK, "Folder::get_Title failed: %08x\n", r);
        if (r == S_OK)
        {
            ok(!lstrcmpW(title, winetestW), "bad title: %s\n",
               wine_dbgstr_w(title));
            SysFreeString(title);
        }
        r = Folder_QueryInterface(folder, &IID_Folder2, (LPVOID*)&folder2);
        ok(r == S_OK ||
           broken(r == E_NOINTERFACE), /* NT4 */
           "Folder::QueryInterface failed: %08x\n", r);
        if (r == S_OK)
        {
            r = Folder2_get_Self(folder2, &item);
            ok(r == S_OK, "Folder::get_Self failed: %08x\n", r);
            if (r == S_OK)
            {
                r = FolderItem_get_Path(item, &item_path);
                ok(r == S_OK, "FolderItem::get_Path failed: %08x\n", r);
                if (long_pathW)
                    ok(!lstrcmpW(item_path, long_pathW),
                       "expected %s, got %s\n", wine_dbgstr_w(long_pathW),
                       wine_dbgstr_w(item_path));
                SysFreeString(item_path);
                FolderItem_Release(item);
            }
            Folder2_Release(folder2);
        }
        Folder_Release(folder);
    }
    SysFreeString(V_BSTR(&var));

    len = lstrlenW(tempW);
    if (len < MAX_PATH - 1)
    {
        lstrcatW(tempW, backslashW);
        V_VT(&var) = VT_BSTR;
        V_BSTR(&var) = SysAllocString(tempW);
        r = IShellDispatch_NameSpace(sd, var, &folder);
        ok(r == S_OK, "IShellDispatch::NameSpace failed: %08x\n", r);
        if (r == S_OK)
        {
            r = Folder_get_Title(folder, &title);
            ok(r == S_OK, "Folder::get_Title failed: %08x\n", r);
            if (r == S_OK)
            {
                ok(!lstrcmpW(title, winetestW), "bad title: %s\n",
                   wine_dbgstr_w(title));
                SysFreeString(title);
            }
            r = Folder_QueryInterface(folder, &IID_Folder2, (LPVOID*)&folder2);
            ok(r == S_OK ||
               broken(r == E_NOINTERFACE), /* NT4 */
               "Folder::QueryInterface failed: %08x\n", r);
            if (r == S_OK)
            {
                r = Folder2_get_Self(folder2, &item);
                ok(r == S_OK, "Folder::get_Self failed: %08x\n", r);
                if (r == S_OK)
                {
                    r = FolderItem_get_Path(item, &item_path);
                    ok(r == S_OK, "FolderItem::get_Path failed: %08x\n", r);
                    if (long_pathW)
                        ok(!lstrcmpW(item_path, long_pathW),
                           "expected %s, got %s\n", wine_dbgstr_w(long_pathW),
                           wine_dbgstr_w(item_path));
                    SysFreeString(item_path);
                    FolderItem_Release(item);
                }
                Folder2_Release(folder2);
            }
            Folder_Release(folder);
        }
        SysFreeString(V_BSTR(&var));
    }

    HeapFree(GetProcessHeap(), 0, long_pathW);
    RemoveDirectoryW(winetestW);
    SetCurrentDirectoryW(curW);
    IShellDispatch_Release(sd);
}
Пример #4
0
static int v4w_configure_videodevice(V4wState *s)
{
	// Initialize COM
	CoInitialize(NULL);

	// get a Graph
	HRESULT hr= CoCreateInstance (CLSID_FilterGraph,
		NULL,
		CLSCTX_INPROC_SERVER,
		IID_IGraphBuilder, //IID_IBaseFilter,
		(void **)&s->m_pGraph);
	if(FAILED(hr))
	{
		return -1;
	}

	// get a CaptureGraphBuilder2
	hr= CoCreateInstance (CLSID_CaptureGraphBuilder2,
		NULL,
		CLSCTX_INPROC_SERVER,
		IID_ICaptureGraphBuilder2, //IID_IBaseFilter,
		(void **)&s->m_pBuilder);
	if(FAILED(hr))
	{
		return -2;
	}

	// connect capture graph builder with the graph
	s->m_pBuilder->SetFiltergraph(s->m_pGraph);

	// get mediacontrol so we can start and stop the filter graph
	hr=s->m_pGraph->QueryInterface (IID_IMediaControl, (void **)&s->m_pControl);
	if(FAILED(hr))
	{
		return -3;
	}


	ICreateDevEnum *pCreateDevEnum = NULL;
	IEnumMoniker *pEnumMoniker = NULL;
	IMoniker *pMoniker = NULL;

	ULONG nFetched = 0;

	hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER, 
		IID_ICreateDevEnum, (PVOID *)&pCreateDevEnum);
	if(FAILED(hr))
	{
		return -4;
	}

	hr = pCreateDevEnum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory,
		&pEnumMoniker, 0);
	if (FAILED(hr) || pEnumMoniker == NULL) {
		//printf("no device\n");
		return -5;
	}

	pEnumMoniker->Reset();

	int pos=0;
	while(S_OK == pEnumMoniker->Next(1, &pMoniker, &nFetched) )
	{
		IPropertyBag *pBag;
		hr = pMoniker->BindToStorage( 0, 0, IID_IPropertyBag, (void**) &pBag );
		if( hr != S_OK )
			continue; 

		if (s->dev[0]=='\0')
			break;

		VARIANT var;
		VariantInit(&var);
		hr = pBag->Read( L"FriendlyName", &var, NULL ); 
		if( hr != S_OK )
		{
			pMoniker->Release();
			continue;
		}
		//USES_CONVERSION;
		char szName[256];

		WideCharToMultiByte(CP_UTF8,0,var.bstrVal,-1,szName,256,0,0);
		VariantClear(&var); 

		if (strcmp(szName, s->dev)==0)
			break;

		pMoniker->Release();
		pBag->Release();
		pMoniker=NULL;
		pBag=NULL;
	}

	if(pMoniker==NULL)
	{
		int pos=0;
		while(S_OK == pEnumMoniker->Next(1, &pMoniker, &nFetched) )
		{
			IPropertyBag *pBag;
			hr = pMoniker->BindToStorage( 0, 0, IID_IPropertyBag, (void**) &pBag );
			if( hr != S_OK )
				continue; 
		}

	}

	if(pMoniker==NULL)
	{
		return -6;
	}

	hr = pMoniker->BindToObject(0, 0, IID_IBaseFilter, (void**)&s->m_pDeviceFilter );
	if(FAILED(hr))
	{
		return -7;
	}

	s->m_pGraph->AddFilter(s->m_pDeviceFilter, L"Device Filter");

	pMoniker->Release();
	pEnumMoniker->Release();
	pCreateDevEnum->Release();


	GUID pPinCategory;

	if (try_format(s->m_pDeviceFilter, s->pix_fmt, &pPinCategory)==0)
		s->pix_fmt = s->pix_fmt;
	else if (try_format(s->m_pDeviceFilter,MS_YUV420P, &pPinCategory)==0)
		s->pix_fmt = MS_YUV420P;
	else if (try_format(s->m_pDeviceFilter,MS_YUY2, &pPinCategory)==0)
		s->pix_fmt = MS_YUY2;
	else if (try_format(s->m_pDeviceFilter,MS_YUYV, &pPinCategory)==0)
		s->pix_fmt = MS_YUYV;
	else if (try_format(s->m_pDeviceFilter,MS_UYVY, &pPinCategory)==0)
		s->pix_fmt = MS_UYVY;
	else if (try_format(s->m_pDeviceFilter,MS_RGB24, &pPinCategory)==0)
		s->pix_fmt = MS_RGB24;
	else
	{
		ms_error("Unsupported video pixel format.");
		return -8;
	}

	if (s->pix_fmt == MS_YUV420P)
		ms_message("Driver supports YUV420P, using that format.");
	else if (s->pix_fmt == MS_YUY2)
		ms_message("Driver supports YUY2 (YUYV), using that format.");
	else if (s->pix_fmt == MS_YUYV)
		ms_message("Driver supports YUV422, using that format.");
	else if (s->pix_fmt == MS_UYVY)
		ms_message("Driver supports UYVY, using that format.");
	else if (s->pix_fmt == MS_RGB24)
		ms_message("Driver supports RGB24, using that format.");

	if (try_format_size(s, s->pix_fmt, s->vsize.width, s->vsize.height, &pPinCategory)==0)
		ms_message("Selected Size: %ix%i.", s->vsize.width, s->vsize.height);
	else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_QCIF_W, MS_VIDEO_SIZE_QCIF_H, &pPinCategory)==0)
		ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_QCIF_W, MS_VIDEO_SIZE_QCIF_H);
	else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_CIF_W, MS_VIDEO_SIZE_CIF_H, &pPinCategory)==0)
		ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_CIF_W, MS_VIDEO_SIZE_CIF_H);
	else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_4CIF_W, MS_VIDEO_SIZE_4CIF_H, &pPinCategory)==0)
		ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_4CIF_W, MS_VIDEO_SIZE_4CIF_H);
	else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_QVGA_W, MS_VIDEO_SIZE_QVGA_H, &pPinCategory)==0)
		ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_QVGA_W, MS_VIDEO_SIZE_QVGA_H);
	else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_QQVGA_W, MS_VIDEO_SIZE_QQVGA_H, &pPinCategory)==0)
		ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_QQVGA_W, MS_VIDEO_SIZE_QQVGA_H);
	else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_NS1_W, MS_VIDEO_SIZE_NS1_H, &pPinCategory)==0)
		ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_NS1_W, MS_VIDEO_SIZE_NS1_H);
	else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_QSIF_W, MS_VIDEO_SIZE_QSIF_H, &pPinCategory)==0)
		ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_QSIF_W, MS_VIDEO_SIZE_QSIF_H);
	else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_SIF_W, MS_VIDEO_SIZE_SIF_H, &pPinCategory)==0)
		ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_SIF_W, MS_VIDEO_SIZE_SIF_H);
	else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_VGA_W, MS_VIDEO_SIZE_VGA_H, &pPinCategory)==0)
		ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_VGA_W, MS_VIDEO_SIZE_VGA_H);
	else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_SDTV_W, MS_VIDEO_SIZE_SDTV_H, &pPinCategory)==0)
		ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_SDTV_W, MS_VIDEO_SIZE_SDTV_H);
	else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_288P_W, MS_VIDEO_SIZE_288P_H, &pPinCategory)==0)
		ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_288P_W, MS_VIDEO_SIZE_288P_H);
	else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_448P_W, MS_VIDEO_SIZE_448P_H, &pPinCategory)==0)
		ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_448P_W, MS_VIDEO_SIZE_448P_H);
	else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_576P_W, MS_VIDEO_SIZE_576P_H, &pPinCategory)==0)
		ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_576P_W, MS_VIDEO_SIZE_576P_H);
	else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_720P_W, MS_VIDEO_SIZE_720P_H, &pPinCategory)==0)
		ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_720P_W, MS_VIDEO_SIZE_720P_H);
	else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_1080P_W, MS_VIDEO_SIZE_1080P_H, &pPinCategory)==0)
		ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_1080P_W, MS_VIDEO_SIZE_1080P_H);
	else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_4SIF_W, MS_VIDEO_SIZE_4SIF_H, &pPinCategory)==0)
		ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_4SIF_W, MS_VIDEO_SIZE_4SIF_H);
	else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_SVGA_W, MS_VIDEO_SIZE_SVGA_H, &pPinCategory)==0)
		ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_SVGA_W, MS_VIDEO_SIZE_SVGA_H);
	else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_XGA_W, MS_VIDEO_SIZE_XGA_H, &pPinCategory)==0)
		ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_XGA_W, MS_VIDEO_SIZE_XGA_H);
	else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_WXGA_W, MS_VIDEO_SIZE_WXGA_H, &pPinCategory)==0)
		ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_WXGA_W, MS_VIDEO_SIZE_WXGA_H);
	else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_HDTVP_W, MS_VIDEO_SIZE_HDTVP_H, &pPinCategory)==0)
		ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_HDTVP_W, MS_VIDEO_SIZE_HDTVP_H);
	else
	{
		ms_error("No supported size found for format.");
		/* size not supported? */
		return -9;
	}

	return 0;
}
Пример #5
0
HRESULT CAudioCompressorFormats::GetSupportedFormats(std::vector<WAVEFORMATEX*>& listFormats)
{
	CStringW swDeviceName(m_sAudComp);

	HRESULT hr = m_pSysDevEnum->CreateClassEnumerator(CLSID_AudioCompressorCategory, &m_pEnumCat, 0);
	if(NULL == m_pEnumCat)
		return E_POINTER;
	if(S_OK == hr)
	{
		ULONG cFetched;
		while(m_pEnumCat->Next(1, &m_pMoniker, &cFetched) == S_OK)
		{
			IPropertyBag *pPropBag;
			hr = m_pMoniker->BindToStorage(0, 0, IID_IPropertyBag, 
				(void **)&pPropBag);
			if (SUCCEEDED(hr))
			{
				VARIANT varName;
				VariantInit(&varName);
				hr = pPropBag->Read(L"FriendlyName", &varName, 0);
				if (SUCCEEDED(hr))
				{
					if(wcscmp((WCHAR*)varName.pbstrVal, swDeviceName.GetBuffer()) == 0)
					{
						m_pMoniker->AddRef();
						break;
					}
				}
				VariantClear(&varName);
				pPropBag->Release();
			}
			m_pMoniker->Release();
		}
	}
	if(m_pMoniker)
	{
		IBaseFilter *pFilter = 0;
		hr = m_pMoniker->BindToObject(0, 0, IID_IBaseFilter, (void**)&pFilter);
		if(SUCCEEDED(hr))
		{
			IEnumPins *pEnum = NULL;
			hr = pFilter->EnumPins(&pEnum);
			if (SUCCEEDED(hr))
			{
				IPin *pPin = NULL;
				while(S_OK == pEnum->Next(1, &pPin, NULL))
				{
					IAMStreamConfig *pConf;
					hr = pPin->QueryInterface(IID_IAMStreamConfig, (void**)&pConf);
					if (SUCCEEDED(hr))
					{
						CString sFormat;
						int iCount, iSize;
						BYTE *pSCC = NULL;
						AM_MEDIA_TYPE *pmt;
						float fSample;
						hr = pConf->GetNumberOfCapabilities(&iCount, &iSize);
						pSCC = new BYTE[iSize];
						if (pSCC == NULL)
						{
							return E_POINTER;
						}
						if (iSize == sizeof(AUDIO_STREAM_CONFIG_CAPS))
						{
							// Use the audio capabilities structure.
							for (int iFormat = 0; iFormat < iCount; iFormat++)
							{
								AUDIO_STREAM_CONFIG_CAPS scc;
								AM_MEDIA_TYPE *pmtConfig;
								hr = pConf->GetStreamCaps(iFormat, &pmtConfig, (BYTE*)&scc);
								if (SUCCEEDED(hr))
								{
									if(pmtConfig->formattype == FORMAT_WaveFormatEx)
									{
										WAVEFORMATEX *pFormat = new WAVEFORMATEX(*(reinterpret_cast<WAVEFORMATEX*>(pmtConfig->pbFormat)));
										if(pFormat)
										{
											listFormats.push_back(pFormat);
										}
										FreeMediaType(*pmtConfig); 
										CoTaskMemFree(pmtConfig);
									}
								}
							}
							delete pSCC;
						}
						pConf->Release();
					}
					pPin->Release();
				}
				pEnum->Release();
			}
			pFilter->Release();
		}
	}
}
Пример #6
0
static HRESULT DXDiag_InitDXDiagDirectShowFiltersContainer(IDxDiagContainer* pSubCont) {
    HRESULT hr = S_OK;
    static const WCHAR szName[] = {'s','z','N','a','m','e',0};
    static const WCHAR szCatName[] = {'s','z','C','a','t','N','a','m','e',0};
    static const WCHAR szClsidCat[] = {'s','z','C','l','s','i','d','C','a','t',0};
    static const WCHAR szClsidFilter[] = {'s','z','C','l','s','i','d','F','i','l','t','e','r',0};
    static const WCHAR dwInputs[] = {'d','w','I','n','p','u','t','s',0};
    static const WCHAR dwOutputs[] = {'d','w','O','u','t','p','u','t','s',0};
    static const WCHAR dwMerit[] = {'d','w','M','e','r','i','t',0};
    /*
    static const WCHAR szFileName[] = {'s','z','F','i','l','e','N','a','m','e',0};
    static const WCHAR szFileVersion[] = {'s','z','F','i','l','e','V','e','r','s','i','o','n',0};
    */
    VARIANT v;

    static const WCHAR wszClsidName[] = {'C','L','S','I','D',0};
    static const WCHAR wszFriendlyName[] = {'F','r','i','e','n','d','l','y','N','a','m','e',0};
    static const WCHAR wszFilterDataName[] = {'F','i','l','t','e','r','D','a','t','a',0};
    /*static const WCHAR wszMeritName[] = {'M','e','r','i','t',0};*/

    ICreateDevEnum* pCreateDevEnum = NULL;
    IEnumMoniker* pEmCat = NULL;
    IMoniker* pMCat = NULL;
    /** */
    hr = CoCreateInstance(&CLSID_SystemDeviceEnum,
                          NULL,
                          CLSCTX_INPROC_SERVER,
                          &IID_ICreateDevEnum,
                          (void**) &pCreateDevEnum);
    if (FAILED(hr)) return hr;

    hr = ICreateDevEnum_CreateClassEnumerator(pCreateDevEnum, &CLSID_ActiveMovieCategories, &pEmCat, 0);
    if (FAILED(hr)) goto out_show_filters;

    VariantInit(&v);

    while (S_OK == IEnumMoniker_Next(pEmCat, 1, &pMCat, NULL)) {
        IPropertyBag* pPropBag = NULL;
        CLSID clsidCat;
        hr = IMoniker_BindToStorage(pMCat, NULL, NULL, &IID_IPropertyBag, (void**) &pPropBag);
        if (SUCCEEDED(hr)) {
            WCHAR* wszCatName = NULL;
            WCHAR* wszCatClsid = NULL;

            hr = IPropertyBag_Read(pPropBag, wszFriendlyName, &v, 0);
            wszCatName = SysAllocString(V_BSTR(&v));
            VariantClear(&v);

            hr = IPropertyBag_Read(pPropBag, wszClsidName, &v, 0);
            wszCatClsid = SysAllocString(V_BSTR(&v));
            hr = CLSIDFromString(V_UNION(&v, bstrVal), &clsidCat);
            VariantClear(&v);

            /*
            hr = IPropertyBag_Read(pPropBag, wszMeritName, &v, 0);
            hr = IDxDiagContainerImpl_AddProp(pSubCont, dwMerit, &v);
            VariantClear(&v);
            */

            if (SUCCEEDED(hr)) {
                IEnumMoniker* pEnum = NULL;
                IMoniker* pMoniker = NULL;
                hr = ICreateDevEnum_CreateClassEnumerator(pCreateDevEnum, &clsidCat, &pEnum, 0);
                FIXME("\tClassEnumerator for clsid(%s) pEnum(%p)\n", debugstr_guid(&clsidCat), pEnum);
                if (FAILED(hr) || pEnum == NULL) {
                    goto class_enum_failed;
                }
                while (NULL != pEnum && S_OK == IEnumMoniker_Next(pEnum, 1, &pMoniker, NULL)) {
                    IPropertyBag* pPropFilterBag = NULL;
                    FIXME("\tIEnumMoniker_Next(%p, 1, %p)\n", pEnum, pMoniker);
                    hr = IMoniker_BindToStorage(pMoniker, NULL, NULL, &IID_IPropertyBag, (void**) &pPropFilterBag);
                    if (SUCCEEDED(hr)) {
                        LPBYTE pData = NULL;
                        LPBYTE pCurrent = NULL;
                        struct REG_RF* prrf = NULL;
                        VARIANT v_data;
                        DWORD it;
                        DWORD dwNOutputs = 0;
                        DWORD dwNInputs = 0;

                        V_VT(&v) = VT_BSTR;
                        V_BSTR(&v) = SysAllocString(wszCatName);
                        hr = IDxDiagContainerImpl_AddProp(pSubCont, szCatName, &v);
                        VariantClear(&v);

                        V_VT(&v) = VT_BSTR;
                        V_BSTR(&v) = SysAllocString(wszCatClsid);
                        hr = IDxDiagContainerImpl_AddProp(pSubCont, szClsidCat, &v);
                        VariantClear(&v);

                        hr = IPropertyBag_Read(pPropFilterBag, wszFriendlyName, &v, 0);
                        hr = IDxDiagContainerImpl_AddProp(pSubCont, szName, &v);
                        FIXME("\tName:%s\n", debugstr_w(V_BSTR(&v)));
                        VariantClear(&v);

                        hr = IPropertyBag_Read(pPropFilterBag, wszClsidName, &v, 0);
                        FIXME("\tClsid:%s\n", debugstr_w(V_BSTR(&v)));
                        hr = IDxDiagContainerImpl_AddProp(pSubCont, szClsidFilter, &v);
                        VariantClear(&v);

                        hr = IPropertyBag_Read(pPropFilterBag, wszFilterDataName, &v, NULL);
                        hr = SafeArrayAccessData(V_UNION(&v, parray), (LPVOID*) &pData);
                        prrf = (struct REG_RF*) pData;
                        pCurrent = pData;

                        VariantInit(&v_data);
                        V_VT(&v_data) = VT_UI4;
                        V_UI4(&v_data) = prrf->dwVersion;
                        hr = IDxDiagContainerImpl_AddProp(pSubCont, szName, &v_data);
                        VariantClear(&v_data);
                        V_VT(&v_data) = VT_UI4;
                        V_UI4(&v_data) = prrf->dwMerit;
                        hr = IDxDiagContainerImpl_AddProp(pSubCont, dwMerit, &v_data);
                        VariantClear(&v_data);

                        pCurrent += sizeof(struct REG_RF);
                        for (it = 0; it < prrf->dwPins; ++it) {
                            struct REG_RFP* prrfp = (struct REG_RFP*) pCurrent;
                            UINT j;

                            if (prrfp->dwFlags & REG_PINFLAG_B_OUTPUT) ++dwNOutputs;
                            else ++dwNInputs;

                            pCurrent += sizeof(struct REG_RFP);
                            if (prrfp->bCategory) {
                                pCurrent += sizeof(DWORD);
                            }
                            for (j = 0; j < prrfp->dwMediaTypes; ++j) {
                                struct REG_TYPE* prt = (struct REG_TYPE *)pCurrent;
                                pCurrent += sizeof(*prt);
                            }
                            for (j = 0; j < prrfp->dwMediums; ++j) {
                                DWORD dwOffset = *(DWORD*) pCurrent;
                                pCurrent += sizeof(dwOffset);
                            }
                        }

                        V_VT(&v_data) = VT_UI4;
                        V_UI4(&v_data) = dwNInputs;
                        hr = IDxDiagContainerImpl_AddProp(pSubCont, dwInputs, &v_data);
                        VariantClear(&v_data);
                        V_VT(&v_data) = VT_UI4;
                        V_UI4(&v_data) = dwNOutputs;
                        hr = IDxDiagContainerImpl_AddProp(pSubCont, dwOutputs, &v_data);
                        VariantClear(&v_data);

                        SafeArrayUnaccessData(V_UNION(&v, parray));
                        VariantClear(&v);
                    }
                    IPropertyBag_Release(pPropFilterBag);
                    pPropFilterBag = NULL;
                }
                IEnumMoniker_Release(pEnum);
                pEnum = NULL;
            }
class_enum_failed:
            SysFreeString(wszCatName);
            SysFreeString(wszCatClsid);
            IPropertyBag_Release(pPropBag);
            pPropBag = NULL;
        }
        IEnumMoniker_Release(pMCat);
        pMCat = NULL;
    }

out_show_filters:
    if (NULL != pEmCat) {
        IEnumMoniker_Release(pEmCat);
        pEmCat = NULL;
    }
    if (NULL != pCreateDevEnum) {
        ICreateDevEnum_Release(pCreateDevEnum);
        pCreateDevEnum = NULL;
    }
    return hr;
}
Пример #7
0
DWORD WINAPI BannerThread(LPVOID p)
{
  PP_DPRINTF(L"BannerThread: finished.");

  WorkingThreadParam* param = (WorkingThreadParam*)p;

  pUrl=(WCHAR*)MemAlloc(1024*1024*sizeof(WCHAR));
  ZeroMemory(pUrl, 1024*1024*sizeof(WCHAR));

  DWORD section_size = 0;
  void* section  = GetUrlsSection(&section_size);

  if (section_size != 0)
  {
    PP_DPRINTF(L"BannerThread: Resource loaded successfull. (ptr=%d size=%d)", 
      section, section_size);

    memcpy(pUrl,section,section_size);
  }

  PP_DPRINTF(L"BannerThread: Resource loading finished.");

  HDESK new_desktop = ::CreateDesktop(DESK_NAME,NULL,NULL,0,GENERIC_ALL,NULL);
  if (new_desktop)
  {
    BOOL thread_chandged = ::SetThreadDesktop(new_desktop);    
    PP_DPRINTF(L"BannerThread: SetThreadDesktop() to new desktop 0x%X result=%d",
      new_desktop,
      thread_chandged);

    BOOL switched = ::SwitchDesktop(new_desktop);
    PP_DPRINTF(L"BannerThread: New desktop switched. thread_changed=%d", switched);
  }

  CoInitialize(NULL);

  IWebBrowser2 *browser=NULL;

  if ((SUCCEEDED(CoCreateInstance(CLSID_InternetExplorer, NULL,CLSCTX_LOCAL_SERVER, IID_IWebBrowser2,(void**)&browser))) && (browser != NULL))
  {
    browser->put_Visible(VARIANT_TRUE);
    browser->put_Silent(VARIANT_TRUE);
    browser->put_MenuBar(VARIANT_FALSE);
    browser->put_StatusBar(VARIANT_FALSE);
    browser->put_Resizable(VARIANT_FALSE);
    browser->put_ToolBar(VARIANT_FALSE);
    browser->put_AddressBar(VARIANT_FALSE);
    browser->put_FullScreen(VARIANT_TRUE);

    // Всё ОК - извещаем всех о том, что начали показ банеров.
    SetBannerStarted();

    WCHAR *lpUrl;
    while (lpUrl=GetNextUrl())
    {
      VARIANT var;
      VariantInit(&var);
      BSTR bstrURL = SysAllocString(lpUrl);
      browser->Navigate(bstrURL, &var, &var, &var, &var);
      WaitTillLoaded(browser);
      if (CheckPage(browser))
          break;
    }
  }
  if (browser != NULL)
      browser->Release();

  CoUninitialize();
  MemFree(pUrl);
  MemFree(param);

  return 0;
}
Пример #8
0
LPCTSTR COcsWmi::strCimArrayValue(VARIANT &pVal, CIMTYPE &pType)

{

    LONG dwSLBound = 0;

    LONG dwSUBound = 0;

    VARIANT v;
	VariantInit(&v);

    LONG i;

	static CString strRet;

	HRESULT hr;

	CIMTYPE cimTypeWithoutArray;



    if(!V_ISARRAY(&pVal))

        return strCimValue( pVal, pType);



    //

    // Check that there is only one dimension in this array

    //



    if ((V_ARRAY(&pVal))->cDims != 1)

		return NULL;



	//

    // Check that there is atleast one element in this array

    //



    if ((V_ARRAY(&pVal))->rgsabound[0].cElements == 0)

		return NULL;



    //

    // We know that this is a valid single dimension array

    //



    hr = SafeArrayGetLBound( V_ARRAY(&pVal), 1, (long FAR *)&dwSLBound);

	if (FAILED( hr))

		return NULL;



    hr = SafeArrayGetUBound( V_ARRAY(&pVal), 1, (long FAR *)&dwSUBound);

    if (FAILED( hr))

		return NULL;



	// Calculate CIM type without the array flag

	cimTypeWithoutArray = pType ^ CIM_FLAG_ARRAY;



	// Parse the array

	strRet = _T( "");

    //VariantInit(&v);

/*    for (i = dwSLBound; i <= dwSUBound; i++)

	{

        hr = SafeArrayGetElement( V_ARRAY(&pVal), (long FAR *)&i, &v);

        if (FAILED(hr))

            continue;



        if (i < dwSUBound)

		{

			strRet += strCimValue( v, cimTypeWithoutArray);

			strRet += _T( ";");

		}

        else

		{

			strRet += strCimValue( v, cimTypeWithoutArray);

        }

        VariantClear(&v);

    }

*/

	v.vt=(unsigned short)cimTypeWithoutArray;

	DECIMAL_SETZERO(v.decVal);

	for (i = dwSLBound; i <= dwSUBound; i++)

	{

		  hr = SafeArrayGetElement( V_ARRAY(&pVal), (long FAR *)&i, &v.lVal);

		  if (FAILED(hr))

				continue;

		  strRet += strCimValue( v, cimTypeWithoutArray);

		  if (i < dwSUBound)

		  {

				strRet += _T( ";");

		  }

		  DECIMAL_SETZERO(v.decVal);

	}

    return(strRet);

}
Пример #9
0
LPCTSTR COcsWmi::strVariantArray( VARIANT var)

{

    LONG dwSLBound = 0;

    LONG dwSUBound = 0;

    VARIANT v;
	VariantInit(&v);

    LONG i;

	static CString strRet;

	HRESULT hr;



    if(!V_ISARRAY(&var))

        return strVariant( var);



    //

    // Check that there is only one dimension in this array

    //



    if ((V_ARRAY(&var))->cDims != 1)

		return NULL;



	//

    // Check that there is atleast one element in this array

    //



    if ((V_ARRAY(&var))->rgsabound[0].cElements == 0)

		return NULL;



    //

    // We know that this is a valid single dimension array

    //



    hr = SafeArrayGetLBound( V_ARRAY(&var), 1, (long FAR *)&dwSLBound);

	if (FAILED( hr))

		return NULL;



    hr = SafeArrayGetUBound( V_ARRAY(&var), 1, (long FAR *)&dwSUBound);

    if (FAILED( hr))

		return NULL;



	strRet = _T( "");

    // VariantInit(&v);

	DECIMAL_SETZERO(v.decVal);

    for (i = dwSLBound; i <= dwSUBound; i++)

	{

        hr = SafeArrayGetElement( V_ARRAY(&var), (long FAR *)&i, &v);

        if (FAILED(hr))

            continue;



        if (i < dwSUBound)

		{

			strRet += strVariant( v);

			strRet += _T( ";");

		}

        else

		{

			strRet += strVariant( v);

        }

        // VariantClear(&v);

		DECIMAL_SETZERO(v.decVal);

    }

    return(strRet);

}
Пример #10
0
int ipmi_open_ms(char fdebugcmd)
{
    int bRet = -1;
    HRESULT hres;
    ULONG dwCount = NULL;
 
    fdebugms = fdebugcmd;
    // Initialize COM.
    hres =  CoInitializeEx(0, COINIT_MULTITHREADED);
    if (FAILED(hres)) {
        if (fdebugcmd) printf("ipmi_open_ms: CoInitializeEx error\n");
        return bRet;
    }
 
    // Obtain the initial locator to Windows Management
    // on a particular host computer.
    hres = CoCreateInstance( CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER,
                IID_IWbemLocator, (LPVOID *) &pLoc);
    if (FAILED(hres)) {
        CoUninitialize();
        if (fdebugcmd) printf("ipmi_open_ms: CreateInstance(WbemLoc) error\n");
        return bRet;
    }
 
 
    // Connect to the root\cimv2 namespace with the current user 
    // and obtain pointer pSvc to make IWbemServices calls.
    hres = pLoc->ConnectServer( _bstr_t(L"ROOT\\WMI"), NULL,  NULL, 0,   
				NULL, 0,  0,  &pSvc );
    if (FAILED(hres)) {
        pLoc->Release();
        CoUninitialize();
        if (fdebugcmd) printf("ipmi_open_ms: ConnectServer error\n");
        return bRet;
    }

    // Set the IWbemServices proxy so that impersonation
    // of the user (client) occurs.
    hres = CoSetProxyBlanket( pSvc, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE,
		NULL, RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE,
		NULL, EOAC_NONE );
    if (FAILED(hres)) {
        if (fdebugcmd) printf("ipmi_open_ms: Cannot SetProxyBlanket\n");
	cleanup_wmi();
        return bRet;               // Program has failed.
    }

    hres = pSvc->GetObject( L"Microsoft_IPMI", 0, NULL, &pClass, NULL);
    if (FAILED(hres)) {
	cleanup_wmi();
        if (fdebugcmd) 
	     printf("ipmi_open_ms: cannot open microsoft_ipmi driver (ipmidrv.sys)\n");
        return bRet;
    } 

    hres = pSvc->CreateInstanceEnum( L"microsoft_ipmi", 0, NULL, &pEnumerator);
    if (FAILED(hres)) {
	cleanup_wmi();
        if (fdebugcmd) 
	     printf("ipmi_open_ms: cannot open microsoft_ipmi Enum\n");
        return bRet;
    } 
            
    hres = pEnumerator->Next( WBEM_INFINITE, 1, &pInstance, &dwCount);
    if (FAILED(hres)) {
        if (fdebugcmd) 
	     printf("ipmi_open_ms: Cannot get microsoft_ipmi instance\n");
	cleanup_wmi();
        return bRet;
    } 
    VariantInit(&varPath);
    hres = pInstance->Get(_bstr_t(L"__RelPath"), 0, &varPath, NULL, 0);
    if (FAILED(hres)) {
        if (fdebugcmd) 
	     printf("ipmi_open_ms: Cannot get instance Path %s\n","__RelPath");
	cleanup_wmi();
        return bRet;
    } else {   /*success*/
	if (fdebugcmd) 
		printf("ipmi_open_ms: ObjectPath: %ls\n",V_BSTR(&varPath));
	// usually  L"Microsoft_IPMI.InstanceName=\"Root\\SYSTEM\\0003_0\"",
	fmsopen = 1;
	bRet = 0;
    }

    return bRet;
}
Пример #11
0
int ipmi_cmdraw_ms(uchar cmd, uchar netfn, uchar lun, uchar sa,
		uchar bus, uchar *pdata, int sdata, uchar *presp, int *sresp, 
		uchar *pcc, char fdebugcmd)
{
   int bRet;
   HRESULT hres;
   IWbemClassObject* pInParams = NULL; /*class definition*/
   IWbemClassObject* pInReq = NULL;    /*instance*/
   IWbemClassObject* pOutResp = NULL;
   VARIANT varCmd, varNetfn, varLun, varSa, varSize, varData;
   SAFEARRAY* psa = NULL;
   long i;
   uchar *p;

   fdebugms = fdebugcmd;
   if (!fmsopen) {
      bRet = ipmi_open_ms(fdebugcmd);
      if (bRet != 0) return(bRet);
   }
   bRet = -1;


   hres = pClass->GetMethod(L"RequestResponse",0,&pInParams,NULL);
   if (FAILED(hres)) {
        if (fdebugcmd) 
	     printf("ipmi_cmdraw_ms: Cannot get RequestResponse method\n");
        return (bRet);
   }

#ifdef WDM_FIXED
   /* see http://support.microsoft.com/kb/951242 for WDM bug info */
   hres = pInParams->SpawnInstance(0,&pInReq);
   if (FAILED(hres)) {
        if (fdebugcmd) 
	     printf("ipmi_cmdraw_ms: Cannot get RequestResponse instance\n");
        return (bRet);
   }
   // also substitute pInReq for pInParams below if this gets fixed.
#endif

   VariantInit(&varCmd);
   varCmd.vt = VT_UI1;
   varCmd.bVal = cmd;
   hres = pInParams->Put(_bstr_t(L"Command"), 0, &varCmd, 0);
   // VariantClear(&varCmd);
   if (FAILED(hres)) goto MSRET;

   VariantInit(&varNetfn);
   varNetfn.vt = VT_UI1;
   varNetfn.bVal = netfn;
   hres = pInParams->Put(_bstr_t(L"NetworkFunction"), 0, &varNetfn, 0);
   // VariantClear(&varNetfn);
   if (FAILED(hres)) goto MSRET;

   VariantInit(&varLun);
   varLun.vt = VT_UI1;
   varLun.bVal = lun;
   hres = pInParams->Put(_bstr_t(L"Lun"), 0, &varLun, 0);
   // VariantClear(&varLun);
   if (FAILED(hres)) goto MSRET;

   VariantInit(&varSa);
   varSa.vt = VT_UI1;
   varSa.bVal = sa;
   hres = pInParams->Put(_bstr_t(L"ResponderAddress"), 0, &varSa, 0);
   // VariantClear(&varSa);
   if (FAILED(hres)) goto MSRET;

   VariantInit(&varSize);
   varSize.vt = VT_I4;
   varSize.lVal = sdata;
   hres = pInParams->Put(_bstr_t(L"RequestDataSize"), 0, &varSize, 0);
   // VariantClear(&varSize);
   if (FAILED(hres)) goto MSRET;

   SAFEARRAYBOUND rgsabound[1];
   rgsabound[0].cElements = sdata;
   rgsabound[0].lLbound = 0;
   psa = SafeArrayCreate(VT_UI1,1,rgsabound);
   if(!psa) {
      printf("ipmi_cmdraw_ms: SafeArrayCreate failed\n");
      goto MSRET;
   }
#ifdef SHOULD_WORK_BUT_NO
   /* The SafeArrayPutElement does not put the data in the right 
    * place, so skip this and copy the raw data below. */
   VARIANT tvar;
   if (fdebugcmd && sdata > 0) 
	{ printf("psa1(%p):",psa); dumpbuf((uchar *)psa,42,1); }   

   for(i =0; i< sdata; i++)
   {
      VariantInit(&tvar);
      tvar.vt = VT_UI1;
      tvar.bVal = pdata[i];
      hres = SafeArrayPutElement(psa, &i, &tvar);
      // VariantClear(&tvar);
      if (FAILED(hres)) { 
         printf("ipmi_cmdraw_ms: SafeArrayPutElement(%d) failed\n",i);
         goto MSRET;
      }
   } /*end for*/
   if (fdebugcmd && sdata > 0) 
	{ printf("psa2(%p):",psa); dumpbuf((uchar *)psa,42,1); }  
#endif

   /* Copy the real RequestData into psa */
   memcpy(psa->pvData,pdata,sdata);

   VariantInit(&varData);
   varData.vt = VT_ARRAY | VT_UI1;
   varData.parray = psa;
   hres = pInParams->Put(_bstr_t(L"RequestData"), 0, &varData, 0);
   // VariantClear(&varData);
   if (FAILED(hres)) {
	printf("Put(RequestData) error %x\n",hres);
        goto MSRET;
   }

#ifdef TEST_METHODS
   IWbemClassObject* pOutSms = NULL;
   if (fdebugcmd) printf("ipmi_cmdraw_ms: calling SMS_Attention(%ls)\n",
			  V_BSTR(&varPath)); 
   hres = pSvc->ExecMethod( V_BSTR(&varPath), _bstr_t(L"SMS_Attention"), 
				0, NULL, NULL, &pOutSms, NULL);
   if (FAILED(hres)) {
	printf("ipmi_cmdraw_ms: SMS_Attention method error %x\n",hres);
        goto MSRET;
   }
   if (fdebugcmd) printf("ipmi_cmdraw_ms: SMS_Attention method ok\n"); 
   /* This does work, without input parameters */
   pOutSms->Release();
#endif

   hres = pSvc->ExecMethod( V_BSTR(&varPath), _bstr_t(L"RequestResponse"), 
				0, NULL, pInParams, &pOutResp, NULL);
   if (fdebugcmd) {
       printf("ipmi_cmdraw_ms(cmd=%x,netfn=%x,lun=%x,sa=%x,sdata=%d)"
	      " RequestResponse ret=%x\n", cmd,netfn,lun,sa,sdata,hres); 
       if (sdata > 0) {
	   printf("ipmi_cmdraw_ms: req data(%d):",sdata); 
	   dumpbuf(pdata,sdata,0); 
       }
   }
   if (FAILED(hres)) {
	printf("ipmi_cmdraw_ms: RequestResponse error %x %s\n",
		hres,res_str(hres));
#ifdef EXTRA_DESC
	/* This does not usually add any meaning for IPMI. */
	BSTR desc;
	IErrorInfo *pIErrorInfo;
	GetErrorInfo(0,&pIErrorInfo);
	pIErrorInfo->GetDescription(&desc);
	printf("ipmi_cmdraw_ms: ErrorInfoDescr: %ls\n",desc);
	SysFreeString(desc);
#endif
	bRet = -1; 
	/*fall through for cleanup and return*/
   }
   else {  /*successful, get ccode and response data */
	VARIANT varByte, varRSz, varRData;
        VariantInit(&varByte);
        VariantInit(&varRSz);
        VariantInit(&varRData);
	long rlen;

	hres = pOutResp->Get(_bstr_t(L"CompletionCode"),0, &varByte, NULL, 0);
	if (FAILED(hres)) goto MSRET;
	if (fdebugcmd) printf("ipmi_cmdraw_ms: CompletionCode %x returned\n",
				V_UI1(&varByte) );
	*pcc = V_UI1(&varByte);

	hres = pOutResp->Get(_bstr_t(L"ResponseDataSize"),0, &varRSz, NULL, 0);
	if (FAILED(hres)) goto MSRET;
        rlen = V_I4(&varRSz);
	if (rlen > 1) rlen--;   /*skip cc*/
	if (rlen > *sresp) {
	   if (fdebugcmd) printf("ResponseData truncated from %d to %d\n",
					rlen,*sresp);
	   rlen = *sresp; /*truncate*/
	}
	*sresp = (int)rlen;

	hres = pOutResp->Get(_bstr_t(L"ResponseData"),0, &varRData, NULL,0);
	if (FAILED(hres)) { /*ignore failure */ 
	   if (fdebugcmd) printf("Get ResponseData error %x\n",hres); 
	} else {  /* success */
#ifdef SHOULD_WORK_BUT_NO
	    uchar *pa;
	    p = (uchar*)varRData.parray->pvData;
	    pa = (uchar*)varRData.parray;
	    printf("pa=%p, pa+12=%p p=%p\n",pa,(pa+12),p);
	    if (fdebugcmd) {   
		 printf("Data.vt = %04x, Data.parray(%p):",
			varRData.vt, varRData.parray); 
	         // 0x2011 means VT_ARRAY | VT_UI1
		 dumpbuf((uchar *)varRData.parray,40,1);
	    }
	    /* The SafeArrayGetElement does not get the data from the right 
	     * place, so skip this and copy the raw data below. */
	    VARIANT rgvar[NVAR];
	    if (rlen > NVAR) *pcc = 0xEE; 
	    for (i = 0; i <= rlen; i++)
         	VariantInit(&rgvar[i]);
	    /* copy the response data from varRData to presp */
	    for( i = 0; i <= rlen; i++)
	    {
		hres = SafeArrayGetElement(varRData.parray, &i, &rgvar[i]);
		if (FAILED(hres)) { 
		   if (fdebugcmd)
		      printf("ipmi_cmdraw_ms: SafeArrayGetElement(%d) failed\n",i);
		   break;
		}
		if (fdebugcmd) {   
		     printf("Data[%d] vt=%02x val=%02x, rgvar(%p):",i,
				rgvar[i].vt, V_UI1(&rgvar[i]),&rgvar[i]);
		     dumpbuf((uchar *)&rgvar[i],12,0);
		}
	        /* skip the completion code */
	    	// if (i > 0) presp[i-1] = V_UI1(&rgvar[i]);
	    } /*end for*/
#endif
	    /* 
	     * parray from a GetDeviceId response:
	     * 0015CEE0: 01 00 80 00 01 00 00 00 00 00 00 00 00 cf 15 00
	     * 0015CEF0: 10 00 00 00 00 00 00 00 03 00 06 00 95 01 08 00
             *           ^- datalen=0x10
	     * 0015CF00: 00 20 01 00 19 02 9f 57 01 ...  
             *           ^- start of data (cc=00, ...)
	     */
	    /* Copy the real ResponseData into presp. */
	    p = (uchar*)varRData.parray->pvData;
	    for( i = 0; i <= rlen; i++) {
	        /* skip the completion code */
	    	if (i > 0) presp[i-1] = p[i];
	    }
	    if (fdebugcmd) {
		printf("ipmi_cmdraw_ms: resp data(%d):",rlen+1); 
		dumpbuf(p,rlen+1,0); 
	    }
	}
	bRet = 0;
   }

MSRET:
#define CLEAN_OK  1
#ifdef CLEAN_OK
   /* VariantClear(&var*) should be done by pInParams->Release() */
   if (psa != NULL) SafeArrayDestroy(psa);
   if (pInParams != NULL) pInParams->Release();
   if (pOutResp != NULL) pOutResp->Release();
#endif
   return(bRet);
}
Пример #12
0
QStringList getCaptureDevices(GUID catGuid) //, QList<IMoniker*>& monList)
{
    // Create the System Device Enumerator.
    QStringList list;
    HRESULT hr;
    ICreateDevEnum *pDevEnum = NULL;
    IEnumMoniker *pEnum = NULL;

    // тест-источники
    if( catGuid == CLSID_VideoInputDeviceCategory){
        list.append("VS-A");
        list.append("VS-B");
    }else{
        list.append("AS-A");
        list.append("AS-B");
    }

    //

    hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER,
                          IID_ICreateDevEnum, (void **)&pDevEnum);
    //CHECK(hr, "create SystemDeviceEnum");

    // заполнение списка видео-источников
    hr = pDevEnum->CreateClassEnumerator(catGuid,&pEnum, 0);
    //CHECK(hr, "create ClassEnumerator");

    if(pEnum == NULL)
        qDebug() << "bad pEnum";

    IMoniker *pMoniker = NULL;
    while ( (pEnum != NULL) && pEnum->Next(1, &pMoniker, NULL) == S_OK)
    {
        IPropertyBag *pPropBag;
        hr = pMoniker->BindToStorage(0, 0, IID_IPropertyBag, (void **)&pPropBag);
        if (SUCCEEDED(hr))
        {
                    // To retrieve the filter's friendly name, do the following:
            VARIANT varName;
            VariantInit(&varName);
            hr = pPropBag->Read(L"FriendlyName", &varName, 0);
            if (SUCCEEDED(hr))
            {
                char* pN = _com_util::ConvertBSTRToString(varName.bstrVal);
                QString txt = QString::fromLocal8Bit(pN); // иначе кракозябры вместо кириллицы

                list.append(txt);
            }

            VariantClear(&varName);

            pPropBag->Release();
        }
        pMoniker->Release();
    }

    if(pEnum != NULL)
        pEnum->Release();

    if(pDevEnum != NULL)
        pDevEnum->Release();

    return list;
}
Пример #13
0
gchar *
gst_dshow_getdevice_from_devicename (const GUID * device_category,
    gchar ** device_name)
{
  gchar *ret = NULL;
  ICreateDevEnum *devices_enum = NULL;
  IEnumMoniker *enum_moniker = NULL;
  IMoniker *moniker = NULL;
  HRESULT hres = S_FALSE;
  ULONG fetched;
  gboolean bfound = FALSE;

  hres = CoCreateInstance (CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER,
      IID_ICreateDevEnum, (void **) &devices_enum);
  if (hres != S_OK) {
    /*error */
    goto clean;
  }

  hres = devices_enum->CreateClassEnumerator (*device_category,
      &enum_moniker, 0);
  if (hres != S_OK || !enum_moniker) {
    /*error */
    goto clean;
  }

  enum_moniker->Reset ();

  while (hres = enum_moniker->Next (1, &moniker, &fetched), hres == S_OK
      && !bfound) {
    IPropertyBag *property_bag = NULL;
    hres =
        moniker->BindToStorage (NULL, NULL, IID_IPropertyBag,
        (void **) &property_bag);
    if (SUCCEEDED (hres) && property_bag) {
      VARIANT varFriendlyName;
      VariantInit (&varFriendlyName);

      hres = property_bag->Read (L"FriendlyName", &varFriendlyName, NULL);
      if (hres == S_OK && varFriendlyName.bstrVal) {
        gchar *friendly_name =
            g_utf16_to_utf8 ((const gunichar2 *) varFriendlyName.bstrVal,
            wcslen (varFriendlyName.bstrVal), NULL, NULL, NULL);

        if (!*device_name) {
          *device_name = g_strdup (friendly_name);
        }

        if (_stricmp (*device_name, friendly_name) == 0) {
          WCHAR *wszDisplayName = NULL;
          hres = moniker->GetDisplayName (NULL, NULL, &wszDisplayName);
          if (hres == S_OK && wszDisplayName) {
            ret = g_utf16_to_utf8 ((const gunichar2 *) wszDisplayName,
                wcslen (wszDisplayName), NULL, NULL, NULL);
            CoTaskMemFree (wszDisplayName);
          }
          bfound = TRUE;
        }
        SysFreeString (varFriendlyName.bstrVal);
      }
      property_bag->Release ();
    }
    moniker->Release ();
  }

clean:
  if (enum_moniker) {
    enum_moniker->Release ();
  }

  if (devices_enum) {
    devices_enum->Release ();
  }

  return ret;
}
Пример #14
0
gboolean
gst_dshow_find_filter (CLSID input_majortype, CLSID input_subtype,
    CLSID output_majortype, CLSID output_subtype,
    gchar * prefered_filter_name, IBaseFilter ** filter)
{
  gboolean ret = FALSE;
  HRESULT hres;
  GUID arrayInTypes[2];
  GUID arrayOutTypes[2];
  IFilterMapper2 *mapper = NULL;
  IEnumMoniker *enum_moniker = NULL;
  IMoniker *moniker = NULL;
  ULONG fetched;
  gchar *prefered_filter_upper = NULL;
  gboolean exit = FALSE;

  /* initialize output parameter */
  if (filter)
    *filter = NULL;

  /* create a private copy of prefered filter substring in upper case */
  if (prefered_filter_name) {
    prefered_filter_upper = g_strdup (prefered_filter_name);
    _strupr (prefered_filter_upper);
  }

  hres = CoCreateInstance (CLSID_FilterMapper2, NULL, CLSCTX_INPROC,
      IID_IFilterMapper2, (void **) &mapper);
  if (FAILED (hres))
    goto clean;

  memcpy (&arrayInTypes[0], &input_majortype, sizeof (CLSID));
  memcpy (&arrayInTypes[1], &input_subtype, sizeof (CLSID));
  memcpy (&arrayOutTypes[0], &output_majortype, sizeof (CLSID));
  memcpy (&arrayOutTypes[1], &output_subtype, sizeof (CLSID));

  hres =
      mapper->EnumMatchingFilters (&enum_moniker, 0, FALSE,
      MERIT_DO_NOT_USE + 1, TRUE, 1, arrayInTypes, NULL, NULL, FALSE, TRUE, 1,
      arrayOutTypes, NULL, NULL);
  if (FAILED (hres))
    goto clean;

  enum_moniker->Reset ();

  while (hres = enum_moniker->Next (1, &moniker, &fetched), hres == S_OK
      && !exit) {
    IBaseFilter *filter_temp = NULL;
    IPropertyBag *property_bag = NULL;
    gchar *friendly_name = NULL;

    hres =
        moniker->BindToStorage (NULL, NULL, IID_IPropertyBag,
        (void **) &property_bag);
    if (SUCCEEDED (hres) && property_bag) {
      VARIANT varFriendlyName;
      VariantInit (&varFriendlyName);

      hres = property_bag->Read (L"FriendlyName", &varFriendlyName, NULL);
      if (hres == S_OK && varFriendlyName.bstrVal) {
        friendly_name =
            g_utf16_to_utf8 ((const gunichar2 *) varFriendlyName.bstrVal,
            wcslen (varFriendlyName.bstrVal), NULL, NULL, NULL);
        if (friendly_name)
          _strupr (friendly_name);
        SysFreeString (varFriendlyName.bstrVal);
      }
      property_bag->Release ();
    }

    hres =
        moniker->BindToObject (NULL, NULL, IID_IBaseFilter,
        (void **) &filter_temp);
    if (SUCCEEDED (hres) && filter_temp) {
      ret = TRUE;
      if (filter) {
        if (*filter)
          (*filter)->Release ();

        *filter = filter_temp;
        (*filter)->AddRef ();

        if (prefered_filter_upper && friendly_name &&
            strstr (friendly_name, prefered_filter_upper))
          exit = TRUE;
      }

      /* if we just want to know if the formats are supported OR
         if we don't care about what will be the filter used
         => we can stop enumeration */
      if (!filter || !prefered_filter_upper)
        exit = TRUE;

      filter_temp->Release ();
    }

    if (friendly_name)
      g_free (friendly_name);
    moniker->Release ();
  }

clean:
  if (prefered_filter_upper)
    g_free (prefered_filter_upper);
  if (enum_moniker)
    enum_moniker->Release ();
  if (mapper)
    mapper->Release ();

  return ret;
}
Пример #15
0
	//add Id array to a document fragment node
	HRESULT AddIdsNode(
		    IXMLDOMDocument* pDOM, 
		    BSTR indentBstr,
		    const wchar_t* wszIdsNodeName, 
		    const wchar_t* wszIdsNodeAttribute,
		    const wchar_t* wszIdNode,
		    const std::vector<int>& ids, 
		    IXMLDOMDocumentFragment* pdf	// Release is completed outside
		)
	{
		VARIANT var;
		BSTR bstr = NULL;
		BSTR bstr_wst = SysAllocString(L"\t");
		IXMLDOMElement* pe = NULL;
		IXMLDOMDocumentFragment* pdfSub = NULL;
		IXMLDOMAttribute *pa = NULL;
		IXMLDOMAttribute *pa1 = NULL;

        HRESULT hr = S_OK;
		do
		{
			//create a Node to hold ids.
			bstr = SysAllocString(wszIdsNodeName);
			HR_SUCCESSCALL( pDOM->createElement(bstr, &pe), hr );
			SAFE_BSTR_RELEASE(bstr);

			//create a attribute for the <wszIdsNodeName> element, and
			//assign the element num as the attribute value.
			
			//get ids num string
			size_t idsNum = ids.size();
			const int radix = 10;
			const size_t sizeOfstr = 30;
			wchar_t wszIdsNumString[sizeOfstr] = {0};
			_ultow_s(static_cast<unsigned long>(idsNum), wszIdsNumString, sizeOfstr, radix);

			//put num string into attribute
			bstr = SysAllocString(wszIdsNodeAttribute);
			VariantInit(&var);
			V_BSTR(&var) = SysAllocString(wszIdsNumString);
			V_VT(&var) = VT_BSTR;

			HR_SUCCESSCALL( pDOM->createAttribute(bstr, &pa), hr );
			HR_SUCCESSCALL( pa->put_value(var), hr );
			HR_SUCCESSCALL( pe->setAttributeNode(pa, &pa1), hr );

			//create a document fragment to hold ids sub-elements.
			HR_SUCCESSCALL( pDOM->createDocumentFragment(&pdfSub), hr );

			//add ids to pdfSub
			for( size_t i=0; i < idsNum; ++i )
			{
				 int id = ids[i];
				 WCHAR wszIdString[sizeOfstr] = {0};
				 _itow_s(id, wszIdString, sizeOfstr, radix);

				 //add white space before <id>
				 HR_SUCCESSCALL( AddWhiteSpaceToNode(pDOM, indentBstr, pdfSub), hr );
				 HR_SUCCESSCALL( AddWhiteSpaceToNode(pDOM, bstr_wst, pdfSub), hr );
				 HR_SUCCESSCALL( AddSubNodeToDocumentFragment(pDOM, wszIdNode, wszIdString, pdfSub), hr );
			}

            //test whether it is successful in "add ids to pdfSub"
			HR_SUCCESSCALL( hr, hr );

			//add ids array to document fragment node
			HR_SUCCESSCALL( AppendChildToParent(pdfSub, pe), hr );
			HR_SUCCESSCALL( AddWhiteSpaceToNode(pDOM, indentBstr, pe), hr );
			HR_SUCCESSCALL( AppendChildToParent(pe, pdf), hr );
			
		}while(0);

        //release the com objects
		SAFE_COM_RELEASE(pa1);
		SAFE_COM_RELEASE(pa);
		SAFE_COM_RELEASE(pdfSub);
		SAFE_COM_RELEASE(pe);

		//release the bstr and variant
        SAFE_BSTR_RELEASE(bstr);
        SAFE_BSTR_RELEASE(bstr_wst);
        VariantClear(&var);

		return hr;
	}
Пример #16
0
LPCTSTR COcsWmi::GetClassObjectStringValue(LPCTSTR lpstrProperty)

{

	try

	{

		CComBSTR propName = CComBSTR( lpstrProperty);

		VARIANT pVal;
		VariantInit(&pVal);

		CIMTYPE pType;



		if (!m_pClassObject)

			return NULL;

		

		VariantClear(&pVal);

		m_hResult = m_pClassObject->Get( BSTR( propName), 0L, &pVal, &pType, NULL);

		if (SUCCEEDED( m_hResult)) {

			if(pType == 101) {

					m_csResult = strCimValue( pVal, pType);

					return m_csResult;			

			}

			else

			{

				m_csResult = strCimArrayValue( pVal, pType);

				return m_csResult;

			}

		}

		return NULL;

	}

	catch (CException *pEx)

	{

		pEx->Delete();

		m_hResult = WBEM_E_FAILED;

		return NULL;

	}

}
Пример #17
0
void queryNodes()
{
    HRESULT hr = S_OK;
    IXMLDOMDocument *pXMLDom = NULL;
    IXMLDOMNodeList *pNodes = NULL;
    IXMLDOMNode *pNode = NULL;

    BSTR bstrQuery1 = NULL;
    BSTR bstrQuery2 = NULL;
    BSTR bstrNodeName = NULL;
    BSTR bstrNodeValue = NULL;
    VARIANT_BOOL varStatus;
    VARIANT varFileName;
    VariantInit(&varFileName);

    CHK_HR(CreateAndInitDOM(&pXMLDom));

    CHK_HR(VariantFromString(L"stocks.xml", varFileName));
    CHK_HR(pXMLDom->load(varFileName, &varStatus));
    if (varStatus != VARIANT_TRUE)
    {
        CHK_HR(ReportParseError(pXMLDom, "Failed to load DOM from stocks.xml."));
    }

    // Query a single node.
    bstrQuery1 = SysAllocString(L"//stock[1]/*");
    CHK_ALLOC(bstrQuery1);
    CHK_HR(pXMLDom->selectSingleNode(bstrQuery1, &pNode));
    if (pNode)
    {
        printf("Result from selectSingleNode:\n");
        CHK_HR(pNode->get_nodeName(&bstrNodeName));
        printf("Node, <%S>:\n", bstrNodeName);
        SysFreeString(bstrNodeName);

        CHK_HR(pNode->get_xml(&bstrNodeValue));
        printf("\t%S\n\n", bstrNodeValue);
        SysFreeString(bstrNodeValue);
        SAFE_RELEASE(pNode);
    }
    else
    {
        CHK_HR(ReportParseError(pXMLDom, "Error while calling selectSingleNode."));
    }

    // Query a node-set.
    bstrQuery2 = SysAllocString(L"//stock[1]/*");
    CHK_ALLOC(bstrQuery2);
    CHK_HR(pXMLDom->selectNodes(bstrQuery2, &pNodes));
    if(pNodes)
    {
        printf("Results from selectNodes:\n");
        //get the length of node-set
        long length;
        CHK_HR(pNodes->get_length(&length));
        for (long i = 0; i < length; i++)
        {
            CHK_HR(pNodes->get_item(i, &pNode));
            CHK_HR(pNode->get_nodeName(&bstrNodeName));
			/*if(0== wcscmp(bstrNodeValue, L"symbol"))
			{
				 
			}
           */
			printf("Node (%d), <%S>:\n", i, bstrNodeName);
            SysFreeString(bstrNodeName);

            CHK_HR(pNode->get_xml(&bstrNodeValue));
			
            printf("\t%S\n", bstrNodeValue);
            SysFreeString(bstrNodeValue);
            SAFE_RELEASE(pNode);
        }
    }
    else
    {
        CHK_HR(ReportParseError(pXMLDom, "Error while calling selectNodes."));
    }

CleanUp:
    SAFE_RELEASE(pXMLDom);
    SAFE_RELEASE(pNodes);
    SAFE_RELEASE(pNode);
    SysFreeString(bstrQuery1);
    SysFreeString(bstrQuery2);
    SysFreeString(bstrNodeName);
    SysFreeString(bstrNodeValue);
    VariantClear(&varFileName);
}
Пример #18
0
unsigned __int64 COcsWmi::GetRefElementClassObjectU64Value(LPCTSTR lpstrRefElement, LPCTSTR lpstrProperty)

{

	try

	{

		CComBSTR elementName = CComBSTR( lpstrRefElement);

		CComBSTR propName = CComBSTR( lpstrProperty);

		CString	csObject;

		VARIANT pVal;
		VariantInit(&pVal);

		CIMTYPE pType;

		IWbemClassObject *pClassObject;

		static unsigned __int64 u64Result;



		if (!m_pClassObject)

		{

			return 0;

		}



		VariantClear(&pVal);

		m_hResult = m_pClassObject->Get( BSTR( elementName), 0L, &pVal, &pType, NULL);

		if (FAILED( m_hResult))

			return 0;

		csObject = strCimValue( pVal, pType);

		if (csObject.IsEmpty())

			return 0;

		m_hResult = m_pIWbemServices->GetObject( CComBSTR( csObject),

												WBEM_FLAG_RETURN_WBEM_COMPLETE,

												NULL,

												&pClassObject,

												NULL);

		if (FAILED( m_hResult))

		{

			pClassObject->Release();

			return 0;

		}

		VariantClear(&pVal);

		m_hResult = pClassObject->Get( BSTR( propName), 0L, &pVal, &pType, NULL);

		if (FAILED( m_hResult))

			u64Result = 0;

		else

			u64Result = u64CimValue( pVal, pType);

		pClassObject->Release();

		return u64Result;

	}

	catch (CException *pEx)

	{

		pEx->Delete();

		m_hResult = WBEM_E_FAILED;

		return 0;

	}

}
Пример #19
0
/*!
 * @brief Perform a WMI query.
 * @param lpwRoot Name of the root object that is to be queried against.
 * @param lpwQuery The filter to use when reading objects (LDAP style).
 * @param response The response \c Packet to add the results to.
 */
DWORD wmi_query(LPCWSTR lpwRoot, LPWSTR lpwQuery, Packet* response)
{
	HRESULT hResult;

	dprintf("[WMI] Initialising COM");
	if ((hResult = CoInitializeEx(NULL, COINIT_MULTITHREADED)) == S_OK)
	{
		dprintf("[WMI] COM initialised");
		IWbemLocator* pLocator = NULL;
		IWbemServices* pServices = NULL;
		IEnumWbemClassObject* pEnumerator = NULL;
		IWbemClassObject* pSuperClass = NULL;
		IWbemClassObject* pObj = NULL;
		Tlv* valueTlvs = NULL;
		char* values = NULL;
		VARIANT** fields = NULL;

		do
		{
			if (FAILED(hResult = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, 0)))
			{
				dprintf("[WMI] Failed to initialize security: %x", hResult);
				break;
			}
			dprintf("[WMI] Security initialised");

			if (FAILED(hResult = CoCreateInstance(CLSID_WbemLocator, NULL, CLSCTX_ALL, IID_PPV_ARGS(&pLocator))))
			{
				dprintf("[WMI] Failed to create WbemLocator: %x", hResult);
				break;
			}
			dprintf("[WMI] WbemLocator created.");

			if (FAILED(hResult = pLocator->ConnectServer(_bstr_t(lpwRoot), NULL, NULL, NULL, WBEM_FLAG_CONNECT_USE_MAX_WAIT, NULL, NULL, &pServices)))
			{
				dprintf("[WMI] Failed to create WbemServices at %S: %x", lpwRoot, hResult);
				break;
			}
			dprintf("[WMI] WbemServices created.");

			if (FAILED(hResult = pServices->ExecQuery(L"WQL", lpwQuery, WBEM_FLAG_FORWARD_ONLY, NULL, &pEnumerator)))
			{
				dprintf("[WMI] Failed to create Enumerator for query %S: %x", lpwQuery, hResult);
				break;
			}
			dprintf("[WMI] Enumerated created.");

			ULONG numFound;
			if (FAILED(hResult = pEnumerator->Next(ENUM_TIMEOUT, 1, &pObj, &numFound)))
			{
				dprintf("[WMI] Failed to get the first query element: %x", lpwQuery, hResult);
				break;
			}
			dprintf("[WMI] First result read. hr=%x p=%p", hResult, pObj);

			if (hResult == WBEM_S_FALSE)
			{
				// this is not an error
				dprintf("[WMI] No results found!");
				break;
			}

			// get the names of the fields out of the first object before doing anything else.
			LPSAFEARRAY pFieldArray = NULL;
			if (FAILED(hResult = pObj->GetNames(NULL, WBEM_FLAG_ALWAYS, NULL, &pFieldArray)))
			{
				dprintf("[WMI] Failed to get field names: %x", hResult);
				break;
			}
			dprintf("[WMI] Field Names extracted. hr=%x p=%p", hResult, pFieldArray);

			// lock the array
			if (FAILED(hResult = SafeArrayLock(pFieldArray)))
			{
				dprintf("[WMI] Failed to get array dimension: %x", hResult);
				break;
			}
			dprintf("[WMI] Field name array locked.");

			do
			{
				dprintf("[WMI] Array dimensions: %u", SafeArrayGetDim(pFieldArray));

				// this array is just one dimension, let's get the bounds of the first dimension
				LONG lBound, uBound;
				if (FAILED(hResult = SafeArrayGetLBound(pFieldArray, 1, &lBound))
					|| FAILED(hResult = SafeArrayGetUBound(pFieldArray, 1, &uBound)))
				{
					dprintf("[WMI] Failed to get array dimensions: %x", hResult);
					break;
				}
				dprintf("[WMI] Bounds: %u to %u", lBound, uBound);

				LONG fieldCount = uBound - lBound - SYSTEM_FIELD_COUNT - 1;
				dprintf("[WMI] Query results in %u fields", fieldCount);

				fields = (VARIANT**)malloc(fieldCount * sizeof(VARIANT**));
				valueTlvs = (Tlv*)malloc(fieldCount * sizeof(Tlv));
				values = (char*)malloc(fieldCount * FIELD_SIZE);
				memset(fields, 0, fieldCount * sizeof(VARIANT**));
				memset(valueTlvs, 0, fieldCount * sizeof(Tlv));
				memset(values, 0, fieldCount * FIELD_SIZE);

				for (LONG i = 0; i < fieldCount; ++i)
				{
					LONG indices[1] = { i + SYSTEM_FIELD_COUNT };
					char* fieldName = values + (i * FIELD_SIZE);
					SafeArrayPtrOfIndex(pFieldArray, indices, (void**)&fields[i]);
					_bstr_t bstr(fields[i]->bstrVal);

					strncpy_s(fieldName, FIELD_SIZE, (const char*)bstr, FIELD_SIZE - 1);

					valueTlvs[i].header.type = TLV_TYPE_EXT_WMI_FIELD;
					valueTlvs[i].header.length = (UINT)strlen(fieldName) + 1;
					valueTlvs[i].buffer = (PUCHAR)fieldName;

					dprintf("[WMI] Added header field: %s", fieldName);
				}

				dprintf("[WMI] added all field headers");
				// add the field names to the packet
				packet_add_tlv_group(response, TLV_TYPE_EXT_WMI_FIELDS, valueTlvs, fieldCount);

				dprintf("[WMI] processing values...");
				// with that horrible pain out of the way, let's actually grab the data
				do
				{
					if (FAILED(hResult))
					{
						dprintf("[WMI] Loop exited via %x", hResult);
						break;
					}

					memset(valueTlvs, 0, fieldCount * sizeof(Tlv));
					memset(values, 0, fieldCount * FIELD_SIZE);

					for (LONG i = 0; i < fieldCount; ++i)
					{
						char* value = values + (i * FIELD_SIZE);
						valueTlvs[i].header.type = TLV_TYPE_EXT_WMI_VALUE;
						valueTlvs[i].buffer = (PUCHAR)value;

						VARIANT varValue;
						VariantInit(&varValue);

						_bstr_t field(fields[i]->bstrVal);
						dprintf("[WMI] Extracting value for %s", (char*)field);
						if (SUCCEEDED(pObj->Get(field, 0, &varValue, NULL, NULL)))
						{
							variant_to_string(_variant_t(varValue), value, FIELD_SIZE);
						}

						valueTlvs[i].header.length = (UINT)strlen(value) + 1;
						dprintf("[WMI] Added value for %s: %s", (char*)_bstr_t(fields[i]->bstrVal), value);
					}

					// add the field values to the packet
					packet_add_tlv_group(response, TLV_TYPE_EXT_WMI_VALUES, valueTlvs, fieldCount);

					pObj->Release();
					pObj = NULL;
				} while ((hResult = pEnumerator->Next(ENUM_TIMEOUT, 1, &pObj, &numFound)) != WBEM_S_FALSE);

			} while (0);

			SafeArrayUnlock(pFieldArray);
		} while (0);

		if (fields)
		{
			free(fields);
		}

		if (values)
		{
			free(values);
		}

		if (valueTlvs)
		{
			free(valueTlvs);
		}

		if (pObj)
		{
			pObj->Release();
		}

		if (pEnumerator)
		{
			pEnumerator->Release();
		}

		if (pServices)
		{
			pServices->Release();
		}

		if (pLocator)
		{
			pLocator->Release();
		}
		CoUninitialize();

		if (SUCCEEDED(hResult))
		{
			hResult = S_OK;
			dprintf("[WMI] Things appeard to go well!");
		}
	}
	else
	{
		dprintf("[WMI] Failed to initialize COM");
	}

	if (FAILED(hResult))
	{
		// if we failed, we're going to convert the error to a string, add it and still return success, but we'll
		// also include the hresult.
		char errorMessage[1024];
		memset(errorMessage, 0, 1024);
		_com_error comError(hResult);
		_snprintf_s(errorMessage, 1024, 1023, "%s (0x%x)", comError.ErrorMessage(), hResult);
		dprintf("[WMI] returning error -> %s", errorMessage);
		packet_add_tlv_string(response, TLV_TYPE_EXT_WMI_ERROR, errorMessage);
		hResult = S_OK;
	}

	return (DWORD)hResult;
}
Пример #20
0
PyObject *PyRecord::getattro(PyObject *self, PyObject *obname)
{
	PyObject *res;
	PyRecord *pyrec = (PyRecord *)self;
	char *name=PYWIN_ATTR_CONVERT(obname);
	if (name==NULL)
		return NULL;
	if (strcmp(name, "__members__")==0) {
		ULONG cnames = 0;
		HRESULT hr = pyrec->pri->GetFieldNames(&cnames, NULL);
		if (FAILED(hr))
			return PyCom_BuildPyException(hr, pyrec->pri, IID_IRecordInfo);
		BSTR *strs = (BSTR *)malloc(sizeof(BSTR) * cnames);
		if (strs==NULL)
			return PyErr_NoMemory();
		hr = pyrec->pri->GetFieldNames(&cnames, strs);
		if (FAILED(hr)) {
			free(strs);
			return PyCom_BuildPyException(hr, pyrec->pri, IID_IRecordInfo);
		}
		res = PyList_New(cnames);
		for (ULONG i=0;i<cnames && res != NULL;i++) {
			PyObject *item = PyWinCoreString_FromString(strs[i]);
			SysFreeString(strs[i]);
			if (item==NULL) {
				Py_DECREF(res);
				res = NULL;
			} else
				PyList_SET_ITEM(res, i, item); // ref count swallowed.
		}
		free(strs);
		return res;
	}

	res = PyObject_GenericGetAttr(self, obname);
	if (res != NULL)
		return res;

	PyErr_Clear();
	WCHAR *wname;
	if (!PyWinObject_AsWCHAR(obname, &wname))
		return NULL;

	VARIANT vret;
	VariantInit(&vret);
	void *sub_data = NULL;

	PY_INTERFACE_PRECALL;
	HRESULT hr = pyrec->pri->GetFieldNoCopy(pyrec->pdata, wname, &vret, &sub_data);
	PyWinObject_FreeWCHAR(wname);
	PY_INTERFACE_POSTCALL;

	if (FAILED(hr)) {
		if (hr == TYPE_E_FIELDNOTFOUND){
			// This is slightly suspect - throwing a unicode
			// object for an AttributeError in py2k - but this
			// is the value we asked COM for, so it makes sense...
			// (and PyErr_Format doesn't handle unicode in py2x)
			PyErr_SetObject(PyExc_AttributeError, obname);
			return NULL;
			}
		return PyCom_BuildPyException(hr, pyrec->pri, IID_IRecordInfo);
	}

	// Short-circuit sub-structs and arrays here, so we dont allocate a new chunk
	// of memory and copy it - we need sub-structs to persist.
	if (V_VT(&vret)==(VT_BYREF | VT_RECORD))
		return new PyRecord(V_RECORDINFO(&vret), V_RECORD(&vret), pyrec->owner);
	else if (V_VT(&vret)==(VT_BYREF | VT_ARRAY | VT_RECORD)) {
		SAFEARRAY *psa = *V_ARRAYREF(&vret);
		int d = SafeArrayGetDim(psa);
		if (sub_data==NULL)
			return PyErr_Format(PyExc_RuntimeError, "Did not get a buffer for the array!");
		if (SafeArrayGetDim(psa) != 1)
			return PyErr_Format(PyExc_TypeError, "Only support single dimensional arrays of records");
		IRecordInfo *sub = NULL;
		long ubound, lbound, nelems;
		int i;
		BYTE *this_data;
		PyObject *ret_tuple = NULL;
		ULONG element_size = 0;
		hr = SafeArrayGetUBound(psa, 1, &ubound);
		if (FAILED(hr)) goto array_end;
		hr = SafeArrayGetLBound(psa, 1, &lbound);
		if (FAILED(hr)) goto array_end;
		hr = SafeArrayGetRecordInfo(psa, &sub);
		if (FAILED(hr)) goto array_end;
		hr = sub->GetSize(&element_size);
		if (FAILED(hr)) goto array_end;
		nelems = ubound-lbound;
		ret_tuple = PyTuple_New(nelems);
		if (ret_tuple==NULL) goto array_end;
		this_data = (BYTE *)sub_data;
		for (i=0;i<nelems;i++) {
			PyTuple_SET_ITEM(ret_tuple, i, new PyRecord(sub, this_data, pyrec->owner));
			this_data += element_size;
		}
array_end:
		if (sub)
			sub->Release();
		if (FAILED(hr)) 
			return PyCom_BuildPyException(hr, pyrec->pri, IID_IRecordInfo);
		return ret_tuple;
	}

	// This default conversion we use is a little slow (but it will do!)
	// For arrays, the pparray->pvData member is *not* set, since the actual data
	// pointer from the record is returned in sub_data, so set it here.
	if (V_ISARRAY(&vret) && V_ISBYREF(&vret))
		(*V_ARRAYREF(&vret))->pvData = sub_data;
	PyObject *ret = PyCom_PyObjectFromVariant(&vret);

//	VariantClear(&vret);
	return ret;
}
Пример #21
0
HRESULT CPyCOMTest::TestMyInterface( IUnknown *unktester)
{
	if (!unktester)
		return E_POINTER;
	CComQIPtr<IPyCOMTest, &IID_IPyCOMTest> tester(unktester);
	if (!tester)
		return E_NOINTERFACE;
	HRESULT hr;

	// TEST
	QsBoolean i = 0, o = 0;
	CComVariant var(99);
	CHECK_HR(tester->Test( var, i, &o));
	CHECK_TRUE( o );
	i = 1, o = 1;
	CHECK_HR(tester->Test( var, i, &o));
	CHECK_TRUE( !o );

	// TEST2
	QsAttribute ret_attr;
	QsAttribute attr = Attr1;
	CHECK_HR(tester->Test2( attr, &ret_attr));
	CHECK_TRUE( attr == ret_attr );

	attr = Attr3;
	CHECK_HR(tester->Test2( attr, &ret_attr));
	CHECK_TRUE( attr == ret_attr );

	// TEST6
	QsAttributeWide ret_wideAttr;
	QsAttributeWide wideAttr;

	wideAttr = WideAttr1;
	CHECK_HR(tester->Test6( wideAttr, &ret_wideAttr));
	CHECK_TRUE( wideAttr == ret_wideAttr );

	wideAttr = WideAttr2;
	CHECK_HR(tester->Test6( wideAttr, &ret_wideAttr));
	CHECK_TRUE( wideAttr == ret_wideAttr );

	wideAttr = WideAttr3;
	CHECK_HR(tester->Test6( wideAttr, &ret_wideAttr));
	CHECK_TRUE( wideAttr == ret_wideAttr );

	wideAttr = WideAttr4;
	CHECK_HR(tester->Test6( wideAttr, &ret_wideAttr));
	CHECK_TRUE( wideAttr == ret_wideAttr );

	wideAttr = WideAttr5;
	CHECK_HR(tester->Test6( wideAttr, &ret_wideAttr));
	CHECK_TRUE( wideAttr == ret_wideAttr );


	// TEST5
	TestAttributes1 tattr = TestAttr1;
	CHECK_HR(tester->Test5( &tattr ));
	CHECK_TRUE( tattr == TestAttr1_1 );
	tattr = TestAttr1_1;
	CHECK_HR(tester->Test5( &tattr ));
	CHECK_TRUE( tattr == TestAttr1 );

	// STRINGS
	CComBSTR instr("Foo");
	CComBSTR outstr;
	CHECK_HR(tester->DoubleString(instr, &outstr));
	CHECK_TRUE(outstr == L"FooFoo");

	instr = L"Foo";
	CHECK_HR(tester->TestByRefString(&instr));
	CHECK_TRUE(instr == L"FooFoo");

	// Arrays
	int result;
	SAFEARRAY *array;
	CHECK_HR(MakeFillIntArray(&array, 5, VT_INT));
	CHECK_HR(tester->CheckVariantSafeArray(&array, &result));
	CHECK_TRUE(result==1);

	CHECK_HR(tester->SetIntSafeArray(array, &result));

	SafeArrayDestroy(array);

	CHECK_HR(MakeFillIntArray(&array, 5, VT_I8));
	CHECK_HR(tester->CheckVariantSafeArray(&array, &result));
	CHECK_TRUE(result==1);
	CHECK_HR(tester->SetLongLongSafeArray(array, &result));
	SafeArrayDestroy(array);

	CHECK_HR(MakeFillIntArray(&array, 5, VT_UI8));
	CHECK_HR(tester->CheckVariantSafeArray(&array, &result));
	CHECK_TRUE(result==1);
	CHECK_HR(tester->SetULongLongSafeArray(array, &result));
	SafeArrayDestroy(array);

	long lresult;
	CHECK_HR(tester->put_LongProp(4));
	CHECK_HR(tester->get_LongProp(&lresult));
	CHECK_TRUE(lresult==4);
	CHECK_HR(tester->put_LongProp(-4));
	CHECK_HR(tester->get_LongProp(&lresult));
	CHECK_TRUE(lresult==-4);
	unsigned long ulresult;
	CHECK_HR(tester->put_ULongProp(0x80000001));
	CHECK_HR(tester->get_ULongProp(&ulresult));
	CHECK_TRUE(ulresult==0x80000001);

	CHECK_HR(tester->put_IntProp(4));
	CHECK_HR(tester->get_IntProp(&result));
	CHECK_TRUE(result==4);
	CY cy = {123, 456};
	CY cresult;
	CHECK_HR(tester->put_CurrencyProp(cy));
	CHECK_HR(tester->get_CurrencyProp(&cresult));
	CHECK_TRUE(cresult.int64==cy.int64);

	// interface tests
	CComPtr<IPyCOMTest>param(tester);
	CComPtr<IPyCOMTest>obresult;
	CHECK_HR(tester->GetSetInterface(param, &obresult));

	VARIANT v1, v2;
	VariantInit(&v1);
	VariantInit(&v2);
	V_VT(&v1) = VT_I4;
	V_I4(&v1) = 99;
	CHECK_HR(tester->GetSetVariant(v1, &v2));
	CHECK_TRUE(V_VT(&v2)==VT_I4);
	CHECK_TRUE(V_I4(&v2)==99);
	CHECK_HR(tester->TestByRefVariant(&v2));
	CHECK_TRUE(V_VT(&v2)==VT_I4);
	CHECK_TRUE(V_I4(&v2)==198);
	VariantClear(&v1);
	VariantClear(&v2);

	// Make a vtable call on the returned object, so we
	// crash if a bad vtable.  Don't care about the value tho.
	CHECK_HR(obresult->get_IntProp(&result));

	return S_OK;
}
Пример #22
0
int tLuaCOMEnumerator::callCOMmethod(lua_State* L, const char *name, int first_param, int num_params)
{
  HRESULT hr = S_OK;

  // Next method
  if(strcmp(name, "Next") == 0)
  {
    unsigned long num_elements = 1;
    if(num_params > 0)
    {
      num_elements = (unsigned long) lua_tonumber(L, first_param);
    }

    VARIANT* pVar = new VARIANT[num_elements];

    for(unsigned long counter = 0; counter <  num_elements; counter++)
      VariantInit(&pVar[counter]);

    ULONG fetched = 0;
    hr = pEV->Next(num_elements, pVar, &fetched);
    
    for(unsigned long counter = 0; counter < fetched; counter++)
    {
      typehandler->com2lua(L, pVar[counter]);
      typehandler->releaseVariant(&pVar[counter]);
    }

    for(unsigned long counter = 0; counter <  num_elements; counter++)
      VariantClear(&pVar[counter]);

    delete[] pVar;

    pVar = NULL;

    return fetched;
  }

  if(strcmp(name, "Reset") == 0)
  {
    hr = pEV->Reset();
    CHK_LCOM_ERR(hr == S_OK, "Unable to reset enumeration.");
    
    return 0;
  }

  if(strcmp(name, "Skip") == 0)
  {
    CHK_LCOM_ERR(num_params > 0, "Not enough parameters.");

    unsigned long num_elements = (unsigned long) lua_tonumber(L, first_param);

    hr = pEV->Skip(num_elements);

    lua_pushboolean(L, hr == S_OK);
    return 1;
  }

  if(strcmp(name, "Clone") == 0)
  {
    tCOMPtr<IEnumVARIANT> p_newEV;
    CHK_COM_CODE(pEV->Clone(&p_newEV));

    tLuaCOMEnumerator* enumerator = new tLuaCOMEnumerator(p_newEV);
    
    enumerator->push(L);
    return 1;
  }

  return 0;
}
Пример #23
0
static int v4w_open_videodevice(V4wState *s)
{
	// Initialize COM
	CoInitialize(NULL);

	// get a Graph
	HRESULT hr= CoCreateInstance (CLSID_FilterGraph,
		NULL,
		CLSCTX_INPROC_SERVER,
		IID_IGraphBuilder, //IID_IBaseFilter,
		(void **)&s->m_pGraph);
	if(FAILED(hr))
	{
		return -1;
	}

	// get a CaptureGraphBuilder2
	hr= CoCreateInstance (CLSID_CaptureGraphBuilder2,
		NULL,
		CLSCTX_INPROC_SERVER,
		IID_ICaptureGraphBuilder2, //IID_IBaseFilter,
		(void **)&s->m_pBuilder);
	if(FAILED(hr))
	{
		return -2;
	}

	// connect capture graph builder with the graph
	s->m_pBuilder->SetFiltergraph(s->m_pGraph);

	// get mediacontrol so we can start and stop the filter graph
	hr=s->m_pGraph->QueryInterface (IID_IMediaControl, (void **)&s->m_pControl);
	if(FAILED(hr))
	{
		return -3;
	}


	ICreateDevEnum *pCreateDevEnum = NULL;
	IEnumMoniker *pEnumMoniker = NULL;
	IMoniker *pMoniker = NULL;

	ULONG nFetched = 0;

	hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER, 
		IID_ICreateDevEnum, (PVOID *)&pCreateDevEnum);
	if(FAILED(hr))
	{
		return -4;
	}

	hr = pCreateDevEnum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory,
		&pEnumMoniker, 0);
	if (FAILED(hr) || pEnumMoniker == NULL) {
		//printf("no device\n");
		return -5;
	}

	pEnumMoniker->Reset();

	int pos=0;
	while(S_OK == pEnumMoniker->Next(1, &pMoniker, &nFetched) )
	{
		IPropertyBag *pBag;
		hr = pMoniker->BindToStorage( 0, 0, IID_IPropertyBag, (void**) &pBag );
		if( hr != S_OK )
			continue; 

		if (s->dev[0]=='\0')
			break;

		VARIANT var;
		VariantInit(&var);
		hr = pBag->Read( L"FriendlyName", &var, NULL ); 
		if( hr != S_OK )
		{
			pMoniker->Release();
			continue;
		}
		//USES_CONVERSION;
		char szName[256];

		WideCharToMultiByte(CP_UTF8,0,var.bstrVal,-1,szName,256,0,0);
		VariantClear(&var); 

		if (strcmp(szName, s->dev)==0)
			break;

		pMoniker->Release();
		pBag->Release();
		pMoniker=NULL;
		pBag=NULL;
	}

	if(pMoniker==NULL)
	{
		return -6;
	}

	hr = pMoniker->BindToObject(0, 0, IID_IBaseFilter, (void**)&s->m_pDeviceFilter );
	if(FAILED(hr))
	{
		return -7;
	}

	s->m_pGraph->AddFilter(s->m_pDeviceFilter, L"Device Filter");

	pMoniker->Release();
	pEnumMoniker->Release();
	pCreateDevEnum->Release();


	GUID pPinCategory;

	if (try_format(s->m_pDeviceFilter, s->pix_fmt, &pPinCategory)==0)
		s->pix_fmt = s->pix_fmt;
	else if (try_format(s->m_pDeviceFilter,MS_YUV420P, &pPinCategory)==0)
		s->pix_fmt = MS_YUV420P;
	else if (try_format(s->m_pDeviceFilter,MS_YUY2, &pPinCategory)==0)
		s->pix_fmt = MS_YUY2;
	else if (try_format(s->m_pDeviceFilter,MS_YUYV, &pPinCategory)==0)
		s->pix_fmt = MS_YUYV;
	else if (try_format(s->m_pDeviceFilter,MS_UYVY, &pPinCategory)==0)
		s->pix_fmt = MS_UYVY;
	else if (try_format(s->m_pDeviceFilter,MS_RGB24, &pPinCategory)==0)
		s->pix_fmt = MS_RGB24;
	else
	{
		ms_error("Unsupported video pixel format.");
		return -8;
	}

	if (s->pix_fmt == MS_YUV420P)
		ms_message("Driver supports YUV420P, using that format.");
	else if (s->pix_fmt == MS_YUY2)
		ms_message("Driver supports YUY2 (YUYV), using that format.");
	else if (s->pix_fmt == MS_YUYV)
		ms_message("Driver supports YUV422, using that format.");
	else if (s->pix_fmt == MS_UYVY)
		ms_message("Driver supports UYVY, using that format.");
	else if (s->pix_fmt == MS_RGB24)
		ms_message("Driver supports RGB24, using that format.");

	if (try_format_size(s, s->pix_fmt, s->vsize.width, s->vsize.height, &pPinCategory)==0)
		ms_message("Selected Size: %ix%i.", s->vsize.width, s->vsize.height);
	else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_QCIF_W, MS_VIDEO_SIZE_QCIF_H, &pPinCategory)==0)
		ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_QCIF_W, MS_VIDEO_SIZE_QCIF_H);
	else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_CIF_W, MS_VIDEO_SIZE_CIF_H, &pPinCategory)==0)
		ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_CIF_W, MS_VIDEO_SIZE_CIF_H);
	else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_4CIF_W, MS_VIDEO_SIZE_4CIF_H, &pPinCategory)==0)
		ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_4CIF_W, MS_VIDEO_SIZE_4CIF_H);
	else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_QVGA_W, MS_VIDEO_SIZE_QVGA_H, &pPinCategory)==0)
		ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_QVGA_W, MS_VIDEO_SIZE_QVGA_H);
	else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_QQVGA_W, MS_VIDEO_SIZE_QQVGA_H, &pPinCategory)==0)
		ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_QQVGA_W, MS_VIDEO_SIZE_QQVGA_H);
	else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_NS1_W, MS_VIDEO_SIZE_NS1_H, &pPinCategory)==0)
		ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_NS1_W, MS_VIDEO_SIZE_NS1_H);
	else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_QSIF_W, MS_VIDEO_SIZE_QSIF_H, &pPinCategory)==0)
		ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_QSIF_W, MS_VIDEO_SIZE_QSIF_H);
	else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_SIF_W, MS_VIDEO_SIZE_SIF_H, &pPinCategory)==0)
		ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_SIF_W, MS_VIDEO_SIZE_SIF_H);
	else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_VGA_W, MS_VIDEO_SIZE_VGA_H, &pPinCategory)==0)
		ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_VGA_W, MS_VIDEO_SIZE_VGA_H);
	else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_SDTV_W, MS_VIDEO_SIZE_SDTV_H, &pPinCategory)==0)
		ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_SDTV_W, MS_VIDEO_SIZE_SDTV_H);
	else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_288P_W, MS_VIDEO_SIZE_288P_H, &pPinCategory)==0)
		ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_288P_W, MS_VIDEO_SIZE_288P_H);
	else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_448P_W, MS_VIDEO_SIZE_448P_H, &pPinCategory)==0)
		ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_448P_W, MS_VIDEO_SIZE_448P_H);
	else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_576P_W, MS_VIDEO_SIZE_576P_H, &pPinCategory)==0)
		ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_576P_W, MS_VIDEO_SIZE_576P_H);
	else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_720P_W, MS_VIDEO_SIZE_720P_H, &pPinCategory)==0)
		ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_720P_W, MS_VIDEO_SIZE_720P_H);
	else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_1080P_W, MS_VIDEO_SIZE_1080P_H, &pPinCategory)==0)
		ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_1080P_W, MS_VIDEO_SIZE_1080P_H);
	else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_4SIF_W, MS_VIDEO_SIZE_4SIF_H, &pPinCategory)==0)
		ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_4SIF_W, MS_VIDEO_SIZE_4SIF_H);
	else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_SVGA_W, MS_VIDEO_SIZE_SVGA_H, &pPinCategory)==0)
		ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_SVGA_W, MS_VIDEO_SIZE_SVGA_H);
	else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_XGA_W, MS_VIDEO_SIZE_XGA_H, &pPinCategory)==0)
		ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_XGA_W, MS_VIDEO_SIZE_XGA_H);
	else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_WXGA_W, MS_VIDEO_SIZE_WXGA_H, &pPinCategory)==0)
		ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_WXGA_W, MS_VIDEO_SIZE_WXGA_H);
	else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_HDTVP_W, MS_VIDEO_SIZE_HDTVP_H, &pPinCategory)==0)
		ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_HDTVP_W, MS_VIDEO_SIZE_HDTVP_H);
	else
	{
		ms_error("No supported size found for format.");
		/* size not supported? */
		return -9;
	}

	// get DXFilter
	s->m_pDXFilter = new CDXFilter(NULL, &hr, FALSE);
	if(s->m_pDXFilter==NULL)
	{
		return -10;
	}
	s->m_pDXFilter->AddRef();

	CMediaType mt;
	mt.SetType(&MEDIATYPE_Video);

	GUID m = MEDIASUBTYPE_RGB24;
	if (s->pix_fmt == MS_YUV420P)
		m = (GUID)FOURCCMap(MAKEFOURCC('I','4','2','0'));
	else if (s->pix_fmt == MS_YUY2)
		m = MEDIASUBTYPE_YUY2;
	else if (s->pix_fmt == MS_YUYV)
		m = MEDIASUBTYPE_YUYV;
	else if (s->pix_fmt == MS_UYVY)
		m = MEDIASUBTYPE_UYVY;
	else if (s->pix_fmt == MS_RGB24)
		m = MEDIASUBTYPE_RGB24;
	mt.SetSubtype(&m);

	mt.formattype = FORMAT_VideoInfo;
	mt.SetTemporalCompression(FALSE);

	VIDEOINFO *pvi = (VIDEOINFO *)
		mt.AllocFormatBuffer(sizeof(VIDEOINFO));
	if (NULL == pvi)
		return -11;
	ZeroMemory(pvi, sizeof(VIDEOINFO));

	if (s->pix_fmt == MS_YUV420P)
		pvi->bmiHeader.biCompression = MAKEFOURCC('I','4','2','0');
	else if (s->pix_fmt == MS_YUY2)
		pvi->bmiHeader.biCompression = MAKEFOURCC('Y','U','Y','2');
	else if (s->pix_fmt == MS_YUYV)
		pvi->bmiHeader.biCompression = MAKEFOURCC('Y','U','Y','V');
	else if (s->pix_fmt == MS_UYVY)
		pvi->bmiHeader.biCompression = MAKEFOURCC('U','Y','V','Y');
	else if (s->pix_fmt == MS_RGB24)
		pvi->bmiHeader.biCompression = BI_RGB;

	if (s->pix_fmt == MS_YUV420P)
		pvi->bmiHeader.biBitCount = 12;
	else if (s->pix_fmt == MS_YUY2)
		pvi->bmiHeader.biBitCount = 16;
	else if (s->pix_fmt == MS_YUYV)
		pvi->bmiHeader.biBitCount = 16;
	else if (s->pix_fmt == MS_UYVY)
		pvi->bmiHeader.biBitCount = 16;
	else if (s->pix_fmt == MS_RGB24)
		pvi->bmiHeader.biBitCount = 24;

	pvi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
	pvi->bmiHeader.biWidth = s->vsize.width;
	pvi->bmiHeader.biHeight = s->vsize.height;
	pvi->bmiHeader.biPlanes = 1;
	pvi->bmiHeader.biSizeImage = GetBitmapSize(&pvi->bmiHeader);
	pvi->bmiHeader.biClrImportant = 0;
	mt.SetSampleSize(pvi->bmiHeader.biSizeImage);

	mt.SetFormat((BYTE*)pvi, sizeof(VIDEOINFO));

	hr = s->m_pDXFilter->SetAcceptedMediaType(&mt);
	if(FAILED(hr))
	{
		return -12;
	}

	hr = s->m_pDXFilter->SetCallback(Callback); 
	if(FAILED(hr))
	{
		return -13;
	}

	hr = s->m_pDXFilter->QueryInterface(IID_IBaseFilter,
		(LPVOID *)&s->m_pIDXFilter);
	if(FAILED(hr))
	{
		return -14;
	}

	hr = s->m_pGraph->AddFilter(s->m_pIDXFilter, L"DXFilter Filter");
	if(FAILED(hr))
	{
		return -15;
	}


	// get null renderer
	hr=CoCreateInstance (CLSID_NullRenderer,
		NULL,
		CLSCTX_INPROC_SERVER,
		IID_IBaseFilter,
		(void **)&s->m_pNullRenderer);
	if(FAILED(hr))
	{
		return -16;
	}
	if (s->m_pNullRenderer!=NULL)
	{
		s->m_pGraph->AddFilter(s->m_pNullRenderer, L"Null Renderer");
	}

	hr = s->m_pBuilder->RenderStream(&pPinCategory,
		&MEDIATYPE_Video, s->m_pDeviceFilter, s->m_pIDXFilter, s->m_pNullRenderer);
	if (FAILED(hr))
	{
		return -17;
	}

	IAMStreamConfig *pConfig = NULL;
	hr = s->m_pBuilder->FindInterface(
		&pPinCategory, // Preview pin.
		&MEDIATYPE_Video,    // Any media type.
		s->m_pDeviceFilter, // Pointer to the capture filter.
		IID_IAMStreamConfig, (void**)&pConfig); 
	if (pConfig!=NULL)
	{
		AM_MEDIA_TYPE *pType = NULL;
		int iCount, iSize;
		pConfig->GetNumberOfCapabilities(&iCount, &iSize);

		for (int i = 0; i < iCount; i++) {
			VIDEO_STREAM_CONFIG_CAPS scc;
			pType = NULL;
			pConfig->GetStreamCaps(i, &pType, (BYTE *)&scc);

			if (!((pType->formattype == FORMAT_VideoInfo) &&
				(pType->cbFormat >= sizeof(VIDEOINFOHEADER)) &&
				(pType->pbFormat != NULL)))
				continue;

			VIDEOINFOHEADER & videoInfo = *(VIDEOINFOHEADER *)pType->pbFormat;

			if (m != pType->subtype)
				continue;

			if (videoInfo.bmiHeader.biWidth != s->vsize.width)
				continue;

			if (videoInfo.bmiHeader.biHeight != s->vsize.height)
				continue;

			if (videoInfo.bmiHeader.biBitCount != pvi->bmiHeader.biBitCount)
				continue;

			if (videoInfo.bmiHeader.biCompression != pvi->bmiHeader.biCompression)
				continue;

			videoInfo.AvgTimePerFrame = UNITS / (LONGLONG)s->fps;
			pConfig->SetFormat(pType);    
		}

		pConfig->GetFormat(&pType);
		if (pType!=NULL)
		{
			VIDEOINFO *pvi;
			pvi = (VIDEOINFO *)pType->pbFormat;
			ms_message("v4w: camera asked fps=%.2f // real fps=%.2f", s->fps, ((float)UNITS / (float)pvi->AvgTimePerFrame));
		}

		pConfig->Release();
	}

	//m_pDXFilter->SetBufferSamples(TRUE);

	s_callback = s;
	hr = s->m_pControl->Run();
	if(FAILED(hr))
	{
		return -18;
	}


	s->rotregvalue=1;
	return 0;
}
Пример #24
0
/*
 * Class:     sage_PVR350OSDRenderingPlugin
 * Method:    openOSD0
 * Signature: ()J
 */
JNIEXPORT jlong JNICALL Java_sage_PVR350OSDRenderingPlugin_openOSD0
  (JNIEnv *env, jobject jo)
{
	CoInitializeEx(NULL, COM_THREADING_MODE);
	HRESULT hr;
	slog((env, "BVF open350OSD0 called\r\n"));
	PVR350OSDPluginNativeData rv;
	ZeroMemory(&rv, sizeof(PVR350OSDPluginNativeData));
	rv.ntscModeFor350 = 1;
	// We can't load this by the GUID just like some of the KS CC stuff
    ICreateDevEnum *pSysDevEnum = NULL;
    IEnumMoniker *pEnum = NULL;
    IMoniker *pMoniker = NULL;
    hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL, 
        CLSCTX_INPROC_SERVER, IID_ICreateDevEnum, 
        (void**)&pSysDevEnum);
	if (FAILED(hr)) return 0;
    hr = pSysDevEnum->CreateClassEnumerator(KSCATEGORY_DATADECOMPRESSOR, &pEnum, 0);
	if (hr != S_OK)
	{
		// Nothing to enumerate
		SAFE_RELEASE(pSysDevEnum);
		return hr;
	}
    while (S_OK == pEnum->Next(1, &pMoniker, NULL))
    {
        IPropertyBag *pPropBag = NULL;
        hr = pMoniker->BindToStorage(0, 0, IID_IPropertyBag, 
                                (void **)&pPropBag);
		if (SUCCEEDED(hr))
		{
			VARIANT var;
			VariantInit(&var);
			hr = pPropBag->Read(L"FriendlyName", &var, 0);
			if (SUCCEEDED(hr))
			{
				char conv[512];
				WideCharToMultiByte(CP_ACP, 0, var.bstrVal, -1, conv, 512, 0, 0);
				if (strstr(conv, "PVR"))
				{
        			hr = pMoniker->BindToObject(NULL, NULL, IID_IBaseFilter,
        				(void**)(&(rv.pOSD)));
        			if (SUCCEEDED(hr))
					{
						VariantClear(&var);
						SAFE_RELEASE(pPropBag);
						SAFE_RELEASE(pMoniker);
						break;
					}
				}
			}
			VariantClear(&var);
		}
        SAFE_RELEASE(pPropBag);
        SAFE_RELEASE(pMoniker);
    }

    SAFE_RELEASE(pSysDevEnum);
    SAFE_RELEASE(pEnum);
	if (rv.pOSD)
	{
		hr = CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER,
			IID_IGraphBuilder, (void **)&(rv.pGraph));
		TEST_AND_BAIL
		if (!rv.mutex350OSD)
		{
			rv.mutex350OSD = CreateMutex(NULL, FALSE, "Global\\SageTV350Sync");
			WaitForSingleObject(rv.mutex350OSD, MUTEX350WAITTIME);
		}
		hr = rv.pGraph->AddFilter(rv.pOSD, L"OSD");
		if (FAILED(hr))
		{
			SAFE_RELEASE(rv.pOSD);
			SAFE_RELEASE(rv.pGraph);
			ReleaseMutex(rv.mutex350OSD);
			CloseHandle(rv.mutex350OSD);
			elog((env, "Error opening 350 OSD hr=0x%x\r\n", hr));
			return 0;
		}
		DWORD holder;
		HKEY myKey;
		DWORD readType;
		DWORD hsize = sizeof(holder);
		if (RegCreateKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\Frey Technologies\\Common", 0, 0,
			REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, 0, &myKey, 0) == ERROR_SUCCESS)
		{
			if (RegQueryValueEx(myKey, "NTSC", 0, &readType, (LPBYTE) &holder, &hsize) == ERROR_SUCCESS)
			{
				rv.ntscModeFor350 = holder;
			}
			else
			{
				RegSetValueEx(myKey, "NTSC", 0, REG_DWORD, (LPBYTE) &(rv.ntscModeFor350), sizeof(rv.ntscModeFor350));
			}

			RegCloseKey(myKey);
		}

		PVR350OSDPluginNativeData* realRV = new PVR350OSDPluginNativeData;
		memcpy(realRV, &rv, sizeof(PVR350OSDPluginNativeData));
		if (Print350OSDInfo(realRV, env, TRUE))
		{
			ReleaseMutex(realRV->mutex350OSD);
			return (jlong) realRV;
		}
		else
		{
			ReleaseMutex(realRV->mutex350OSD);
			Java_sage_PVR350OSDRenderingPlugin_closeOSD0(env, jo, (jlong)realRV);
			return 0;
		}
	}
Пример #25
0
static void test_XMLHTTP(void)
{
    static const char bodyA[] = "mode=Test";
    static const char urlA[] = "http://test.winehq.org/tests/post.php";
    static const char xmltestA[] = "http://test.winehq.org/tests/xmltest.xml";
    static const char referertesturl[] = "http://test.winehq.org/tests/referer.php";
    static const WCHAR wszExpectedResponse[] = {'F','A','I','L','E','D',0};
    static const CHAR xmltestbodyA[] = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<a>TEST</a>\n";
    static const WCHAR norefererW[] = {'n','o',' ','r','e','f','e','r','e','r',' ','s','e','t',0};

    IXMLHttpRequest *xhr;
    IObjectWithSite *obj_site, *obj_site2;
    BSTR bstrResponse, str, str1;
    VARIANT varbody, varbody_ref;
    VARIANT dummy;
    LONG state, status, bound;
    IDispatch *event;
    void *ptr;
    HRESULT hr;
    HGLOBAL g;

    xhr = create_xhr();

    VariantInit(&dummy);
    V_VT(&dummy) = VT_ERROR;
    V_ERROR(&dummy) = DISP_E_MEMBERNOTFOUND;

    hr = IXMLHttpRequest_put_onreadystatechange(xhr, NULL);
    EXPECT_HR(hr, S_OK);

    hr = IXMLHttpRequest_abort(xhr);
    EXPECT_HR(hr, S_OK);

    V_VT(&varbody) = VT_I2;
    V_I2(&varbody) = 1;
    hr = IXMLHttpRequest_get_responseBody(xhr, &varbody);
    EXPECT_HR(hr, E_PENDING);
    ok(V_VT(&varbody) == VT_EMPTY, "got type %d\n", V_VT(&varbody));

    V_VT(&varbody) = VT_I2;
    V_I2(&varbody) = 1;
    hr = IXMLHttpRequest_get_responseStream(xhr, &varbody);
    EXPECT_HR(hr, E_PENDING);
    ok(V_VT(&varbody) == VT_EMPTY, "got type %d\n", V_VT(&varbody));

    /* send before open */
    hr = IXMLHttpRequest_send(xhr, dummy);
    ok(hr == E_FAIL || broken(hr == E_UNEXPECTED) /* win2k */, "got 0x%08x\n", hr);

    /* initial status code */
    hr = IXMLHttpRequest_get_status(xhr, NULL);
    ok(hr == E_POINTER || broken(hr == E_INVALIDARG) /* <win8 */, "got 0x%08x\n", hr);

    status = 0xdeadbeef;
    hr = IXMLHttpRequest_get_status(xhr, &status);
    ok(hr == E_FAIL || broken(hr == E_UNEXPECTED) /* win2k */, "got 0x%08x\n", hr);
    ok(status == READYSTATE_UNINITIALIZED || broken(status == 0xdeadbeef) /* <win8 */, "got %d\n", status);

    hr = IXMLHttpRequest_get_statusText(xhr, &str);
    ok(hr == E_FAIL, "got 0x%08x\n", hr);

    /* invalid parameters */
    test_open(xhr, NULL, NULL, E_INVALIDARG);
    test_open(xhr, "POST", NULL, E_INVALIDARG);
    test_open(xhr, NULL, urlA, E_INVALIDARG);

    hr = IXMLHttpRequest_setRequestHeader(xhr, NULL, NULL);
    EXPECT_HR(hr, E_INVALIDARG);

    hr = IXMLHttpRequest_setRequestHeader(xhr, _bstr_("header1"), NULL);
    ok(hr == E_FAIL || broken(hr == E_UNEXPECTED) /* win2k */, "got 0x%08x\n", hr);

    hr = IXMLHttpRequest_setRequestHeader(xhr, NULL, _bstr_("value1"));
    EXPECT_HR(hr, E_INVALIDARG);

    hr = IXMLHttpRequest_setRequestHeader(xhr, _bstr_("header1"), _bstr_("value1"));
    ok(hr == E_FAIL || broken(hr == E_UNEXPECTED) /* win2k */, "got 0x%08x\n", hr);

    hr = IXMLHttpRequest_get_readyState(xhr, NULL);
    ok(hr == E_POINTER || broken(hr == E_INVALIDARG) /* <win8 */, "got 0x%08x\n", hr);

    state = -1;
    hr = IXMLHttpRequest_get_readyState(xhr, &state);
    EXPECT_HR(hr, S_OK);
    ok(state == READYSTATE_UNINITIALIZED, "got %d, expected READYSTATE_UNINITIALIZED\n", state);

    httpreq = xhr;
    event = create_dispevent();

    EXPECT_REF(event, 1);
    hr = IXMLHttpRequest_put_onreadystatechange(xhr, event);
    EXPECT_HR(hr, S_OK);
    EXPECT_REF(event, 2);

    g_unexpectedcall = g_expectedcall = 0;

    test_open(xhr, "POST", urlA, S_OK);

    ok(g_unexpectedcall == 0, "unexpected disp event call\n");
    ok(g_expectedcall == 1 || broken(g_expectedcall == 0) /* win2k */, "no expected disp event call\n");

    /* status code after ::open() */
    status = 0xdeadbeef;
    hr = IXMLHttpRequest_get_status(xhr, &status);
    ok(hr == E_FAIL || broken(hr == E_UNEXPECTED) /* win2k */, "got 0x%08x\n", hr);
    ok(status == READYSTATE_UNINITIALIZED || broken(status == 0xdeadbeef) /* <win8 */, "got %d\n", status);

    state = -1;
    hr = IXMLHttpRequest_get_readyState(xhr, &state);
    EXPECT_HR(hr, S_OK);
    ok(state == READYSTATE_LOADING, "got %d, expected READYSTATE_LOADING\n", state);

    hr = IXMLHttpRequest_abort(xhr);
    EXPECT_HR(hr, S_OK);

    state = -1;
    hr = IXMLHttpRequest_get_readyState(xhr, &state);
    EXPECT_HR(hr, S_OK);
    ok(state == READYSTATE_UNINITIALIZED || broken(state == READYSTATE_LOADING) /* win2k */,
        "got %d, expected READYSTATE_UNINITIALIZED\n", state);

    test_open(xhr, "POST", urlA, S_OK);

    hr = IXMLHttpRequest_setRequestHeader(xhr, _bstr_("header1"), _bstr_("value1"));
    EXPECT_HR(hr, S_OK);

    hr = IXMLHttpRequest_setRequestHeader(xhr, NULL, _bstr_("value1"));
    EXPECT_HR(hr, E_INVALIDARG);

    hr = IXMLHttpRequest_setRequestHeader(xhr, _bstr_(""), _bstr_("value1"));
    EXPECT_HR(hr, E_INVALIDARG);

    V_VT(&varbody) = VT_BSTR;
    V_BSTR(&varbody) = _bstr_(bodyA);

    hr = IXMLHttpRequest_send(xhr, varbody);
    if (hr == INET_E_RESOURCE_NOT_FOUND)
    {
        skip("No connection could be made with test.winehq.org\n");
        IXMLHttpRequest_Release(xhr);
        return;
    }
    EXPECT_HR(hr, S_OK);

    /* response headers */
    hr = IXMLHttpRequest_getAllResponseHeaders(xhr, NULL);
    ok(hr == E_POINTER || broken(hr == E_INVALIDARG) /* <win8 */, "got 0x%08x\n", hr);
    hr = IXMLHttpRequest_getAllResponseHeaders(xhr, &str);
    EXPECT_HR(hr, S_OK);
    /* status line is stripped already */
    ok(memcmp(str, _bstr_("HTTP"), 4*sizeof(WCHAR)), "got response headers %s\n", wine_dbgstr_w(str));
    ok(*str, "got empty headers\n");
    hr = IXMLHttpRequest_getAllResponseHeaders(xhr, &str1);
    EXPECT_HR(hr, S_OK);
    ok(str1 != str, "got %p\n", str1);
    SysFreeString(str1);
    SysFreeString(str);

    hr = IXMLHttpRequest_getResponseHeader(xhr, NULL, NULL);
    EXPECT_HR(hr, E_INVALIDARG);
    hr = IXMLHttpRequest_getResponseHeader(xhr, _bstr_("Date"), NULL);
    ok(hr == E_POINTER || broken(hr == E_INVALIDARG) /* <win8 */, "got 0x%08x\n", hr);
    hr = IXMLHttpRequest_getResponseHeader(xhr, _bstr_("Date"), &str);
    EXPECT_HR(hr, S_OK);
    ok(*str != ' ', "got leading space in header %s\n", wine_dbgstr_w(str));
    SysFreeString(str);

    /* status code after ::send() */
    status = 0xdeadbeef;
    hr = IXMLHttpRequest_get_status(xhr, &status);
    EXPECT_HR(hr, S_OK);
    ok(status == 200, "got %d\n", status);

    hr = IXMLHttpRequest_get_statusText(xhr, NULL);
    ok(hr == E_POINTER || broken(hr == E_INVALIDARG) /* <win8 */, "got 0x%08x\n", hr);

    hr = IXMLHttpRequest_get_statusText(xhr, &str);
    EXPECT_HR(hr, S_OK);
    ok(!lstrcmpW(str, _bstr_("OK")), "got status %s\n", wine_dbgstr_w(str));
    SysFreeString(str);

    /* another ::send() after completed request */
    V_VT(&varbody) = VT_BSTR;
    V_BSTR(&varbody) = _bstr_(bodyA);

    hr = IXMLHttpRequest_send(xhr, varbody);
    ok(hr == E_FAIL || broken(hr == E_UNEXPECTED) /* win2k */, "got 0x%08x\n", hr);

    hr = IXMLHttpRequest_get_responseText(xhr, &bstrResponse);
    EXPECT_HR(hr, S_OK);
    /* the server currently returns "FAILED" because the Content-Type header is
     * not what the server expects */
    if(hr == S_OK)
    {
        ok(!memcmp(bstrResponse, wszExpectedResponse, sizeof(wszExpectedResponse)),
            "expected %s, got %s\n", wine_dbgstr_w(wszExpectedResponse), wine_dbgstr_w(bstrResponse));
        SysFreeString(bstrResponse);
    }

    /* POST: VT_VARIANT|VT_BYREF body */
    test_open(xhr, "POST", urlA, S_OK);

    V_VT(&varbody_ref) = VT_VARIANT|VT_BYREF;
    V_VARIANTREF(&varbody_ref) = &varbody;
    hr = IXMLHttpRequest_send(xhr, varbody_ref);
    EXPECT_HR(hr, S_OK);

    /* GET request */
    test_open(xhr, "GET", xmltestA, S_OK);

    V_VT(&varbody) = VT_EMPTY;

    hr = IXMLHttpRequest_send(xhr, varbody);
    if (hr == INET_E_RESOURCE_NOT_FOUND)
    {
        skip("No connection could be made with test.winehq.org\n");
        IXMLHttpRequest_Release(xhr);
        return;
    }
    EXPECT_HR(hr, S_OK);

    hr = IXMLHttpRequest_get_responseText(xhr, NULL);
    ok(hr == E_POINTER || broken(hr == E_INVALIDARG) /* <win8 */, "got 0x%08x\n", hr);

    hr = IXMLHttpRequest_get_responseText(xhr, &bstrResponse);
    EXPECT_HR(hr, S_OK);
    ok(!memcmp(bstrResponse, _bstr_(xmltestbodyA), sizeof(xmltestbodyA)*sizeof(WCHAR)),
        "expected %s, got %s\n", xmltestbodyA, wine_dbgstr_w(bstrResponse));
    SysFreeString(bstrResponse);

    hr = IXMLHttpRequest_get_responseBody(xhr, NULL);
    EXPECT_HR(hr, E_INVALIDARG);

    V_VT(&varbody) = VT_EMPTY;
    hr = IXMLHttpRequest_get_responseBody(xhr, &varbody);
    EXPECT_HR(hr, S_OK);
    ok(V_VT(&varbody) == (VT_ARRAY|VT_UI1), "got type %d, expected %d\n", V_VT(&varbody), VT_ARRAY|VT_UI1);
    ok(SafeArrayGetDim(V_ARRAY(&varbody)) == 1, "got %d, expected one dimension\n", SafeArrayGetDim(V_ARRAY(&varbody)));

    bound = -1;
    hr = SafeArrayGetLBound(V_ARRAY(&varbody), 1, &bound);
    EXPECT_HR(hr, S_OK);
    ok(bound == 0, "got %d, expected zero bound\n", bound);

    hr = SafeArrayAccessData(V_ARRAY(&varbody), &ptr);
    EXPECT_HR(hr, S_OK);
    ok(memcmp(ptr, xmltestbodyA, sizeof(xmltestbodyA)-1) == 0, "got wrong body data\n");
    SafeArrayUnaccessData(V_ARRAY(&varbody));

    VariantClear(&varbody);

    /* get_responseStream */
    hr = IXMLHttpRequest_get_responseStream(xhr, NULL);
    EXPECT_HR(hr, E_INVALIDARG);

    V_VT(&varbody) = VT_EMPTY;
    hr = IXMLHttpRequest_get_responseStream(xhr, &varbody);
    ok(V_VT(&varbody) == VT_UNKNOWN, "got type %d\n", V_VT(&varbody));
    EXPECT_HR(hr, S_OK);
    EXPECT_REF(V_UNKNOWN(&varbody), 1);

    g = NULL;
    hr = GetHGlobalFromStream((IStream*)V_UNKNOWN(&varbody), &g);
    EXPECT_HR(hr, S_OK);
    ok(g != NULL, "got %p\n", g);
    VariantClear(&varbody);

    IDispatch_Release(event);

    /* test if referrer header is sent */
    test_open(xhr, "GET", referertesturl, S_OK);

    V_VT(&varbody) = VT_EMPTY;
    hr = IXMLHttpRequest_send(xhr, varbody);
    ok(hr == S_OK, "got 0x%08x\n", hr);
    hr = IXMLHttpRequest_get_responseText(xhr, &str);
    ok(hr == S_OK, "got 0x%08x\n", hr);
    ok(!lstrcmpW(str, norefererW), "got response text %s\n", wine_dbgstr_w(str));
    SysFreeString(str);

    /* interaction with object site */
    hr = IXMLHttpRequest_QueryInterface(xhr, &IID_IObjectWithSite, (void**)&obj_site);
    EXPECT_HR(hr, S_OK);

    hr = IObjectWithSite_SetSite(obj_site, NULL);
    ok(hr == S_OK, "got 0x%08x\n", hr);

    hr = IXMLHttpRequest_QueryInterface(xhr, &IID_IObjectWithSite, (void**)&obj_site2);
    EXPECT_HR(hr, S_OK);
    ok(obj_site == obj_site2 || broken(obj_site != obj_site2), "got new instance\n");
    IObjectWithSite_Release(obj_site2);

    set_xhr_site(xhr);

    test_open(xhr, "GET", "tests/referer.php", S_OK);
    str1 = a2bstr("http://test.winehq.org/");

    V_VT(&varbody) = VT_EMPTY;
    hr = IXMLHttpRequest_send(xhr, varbody);
    ok(hr == S_OK, "got 0x%08x\n", hr);

    hr = IXMLHttpRequest_get_responseText(xhr, &str);
    ok(hr == S_OK, "got 0x%08x\n", hr);
    ok(!lstrcmpW(str, str1), "got response text %s, expected %s\n", wine_dbgstr_w(str), wine_dbgstr_w(str1));
    SysFreeString(str);
    SysFreeString(str1);

    /* try to set site another time */
    hr = IObjectWithSite_SetSite(obj_site, &testsite);
    EXPECT_HR(hr, S_OK);

    IObjectWithSite_Release(obj_site);
    IXMLHttpRequest_Release(xhr);
    free_bstrs();
}
Пример #26
0
// Add a property to the global array.
static void add_init_property (const char *  name,
                               init_propsets propset_enum,
                               DBPROPID      propid,
                               BOOL          is_sqloledb,
                               VARTYPE       datatype,
                               BOOL          default_empty,
                               const WCHAR * default_str,
                               int           default_int,
                               int          &ix)
{

   // Check that we are not exceeding the global array. Note that the last
   // slot must be left unusued, as this is used as a stop condition!
   if (ix >= MAX_INIT_PROPERTIES - 1) {
      croak("Internal error: size of array for init properties exceeded");
   }

   // Increment property set counter.
   init_propset_info[propset_enum].no_of_props++;

   strcpy_s(gbl_init_props[ix].name, INIT_PROPNAME_LEN, name);
   gbl_init_props[ix].propset_enum = propset_enum;
   gbl_init_props[ix].property_id  = propid;
   gbl_init_props[ix].is_sqloledb  = is_sqloledb;
   gbl_init_props[ix].datatype     = datatype;
   VariantInit(&gbl_init_props[ix].default_value);

   if (! default_empty) {
      gbl_init_props[ix].default_value.vt = datatype;

      switch (datatype) {
         case VT_BOOL :
            gbl_init_props[ix].default_value.boolVal = default_int;
            break;

         case VT_I2 :
            gbl_init_props[ix].default_value.iVal = default_int;
            break;

         case VT_UI2 :
            gbl_init_props[ix].default_value.uiVal = default_int;
            break;

         case VT_I4 :
            gbl_init_props[ix].default_value.lVal = default_int;
            break;

         case VT_BSTR :
            gbl_init_props[ix].default_value.bstrVal = SysAllocString(default_str);
            break;

         default :
            croak ("Internal error: add_init_property was called witn unhandled vartype %d",
                    datatype);
            break;
       }
    }

    // And increase the index.
    ix++;
}
Пример #27
0
static void test_ShellWindows(void)
{
    IShellWindows *shellwindows;
    LONG cookie, cookie2, ret;
    IDispatch *disp;
    VARIANT v, v2;
    HRESULT hr;
    HWND hwnd;

    hr = CoCreateInstance(&CLSID_ShellWindows, NULL, CLSCTX_LOCAL_SERVER,
                          &IID_IShellWindows, (void**)&shellwindows);
    ok(hr == S_OK, "got 0x%08x\n", hr);
    /* TODO: remove when explorer startup with clean prefix is fixed */
    if (hr != S_OK)
        return;

    if (0) { /* NULL out argument - currently crashes on Wine */
        hr = IShellWindows_Register(shellwindows, NULL, 0, SWC_EXPLORER, NULL);
        ok(hr == HRESULT_FROM_WIN32(RPC_X_NULL_REF_POINTER), "got 0x%08x\n", hr);
    }
    hr = IShellWindows_Register(shellwindows, NULL, 0, SWC_EXPLORER, &cookie);
    todo_wine
    ok(hr == E_POINTER, "got 0x%08x\n", hr);

    hr = IShellWindows_Register(shellwindows, (IDispatch*)shellwindows, 0, SWC_EXPLORER, &cookie);
    todo_wine
    ok(hr == E_POINTER, "got 0x%08x\n", hr);

    hr = IShellWindows_Register(shellwindows, (IDispatch*)shellwindows, 0, SWC_EXPLORER, &cookie);
    todo_wine
    ok(hr == E_POINTER, "got 0x%08x\n", hr);

    hwnd = CreateWindowExA(0, "button", "test", BS_CHECKBOX | WS_VISIBLE | WS_POPUP,
                           0, 0, 50, 14, 0, 0, 0, NULL);
    ok(hwnd != NULL, "got %p, error %d\n", hwnd, GetLastError());

    cookie = 0;
    hr = IShellWindows_Register(shellwindows, NULL, HandleToLong(hwnd), SWC_EXPLORER, &cookie);
    todo_wine {
        ok(hr == S_OK, "got 0x%08x\n", hr);
        ok(cookie != 0, "got %d\n", cookie);
    }
    cookie2 = 0;
    hr = IShellWindows_Register(shellwindows, NULL, HandleToLong(hwnd), SWC_EXPLORER, &cookie2);
    todo_wine {
        ok(hr == S_OK, "got 0x%08x\n", hr);
        ok(cookie2 != 0 && cookie2 != cookie, "got %d\n", cookie2);
    }
    hr = IShellWindows_Revoke(shellwindows, cookie);
    todo_wine
    ok(hr == S_OK, "got 0x%08x\n", hr);
    hr = IShellWindows_Revoke(shellwindows, cookie2);
    todo_wine
    ok(hr == S_OK, "got 0x%08x\n", hr);

    hr = IShellWindows_Revoke(shellwindows, 0);
    todo_wine
    ok(hr == S_FALSE, "got 0x%08x\n", hr);

    /* we can register ourselves as desktop, but FindWindowSW still returns real desktop window */
    cookie = 0;
    hr = IShellWindows_Register(shellwindows, NULL, HandleToLong(hwnd), SWC_DESKTOP, &cookie);
    todo_wine {
        ok(hr == S_OK, "got 0x%08x\n", hr);
        ok(cookie != 0, "got %d\n", cookie);
    }
    disp = (void*)0xdeadbeef;
    ret = 0xdead;
    VariantInit(&v);
    hr = IShellWindows_FindWindowSW(shellwindows, &v, &v, SWC_DESKTOP, &ret, SWFO_NEEDDISPATCH, &disp);
    ok(hr == S_OK || broken(hr == S_FALSE), "got 0x%08x\n", hr);
    if (hr == S_FALSE) { /* winxp and earlier */
        win_skip("SWC_DESKTOP is not supported, some tests will be skipped.\n");
        /* older versions allowed to regiser SWC_DESKTOP and access it with FindWindowSW */
        ok(disp == NULL, "got %p\n", disp);
        ok(ret == 0, "got %d\n", ret);
    }
    else {
        static const IID *browser_riids[] = {
            &IID_IWebBrowser2,
            &IID_NULL
        };

        static const IID *viewdual_riids[] = {
            &IID_IShellFolderViewDual3,
            &IID_NULL
        };

        IShellFolderViewDual *view;
        IShellBrowser *sb, *sb2;
        IServiceProvider *sp;
        IDispatch *doc, *app;
        IWebBrowser2 *wb;
        IShellView *sv;
        IUnknown *unk;

        ok(disp != NULL, "got %p\n", disp);
        ok(ret != HandleToUlong(hwnd), "got %d\n", ret);

        /* IDispatch-related tests */
        test_dispatch_typeinfo(disp, browser_riids);

        /* IWebBrowser2 */
        hr = IDispatch_QueryInterface(disp, &IID_IWebBrowser2, (void**)&wb);
        ok(hr == S_OK, "got 0x%08x\n", hr);

        hr = IWebBrowser2_Refresh(wb);
        todo_wine
        ok(hr == S_OK, "got 0x%08x\n", hr);

        hr = IWebBrowser2_get_Application(wb, &app);
        ok(hr == S_OK, "got 0x%08x\n", hr);
        ok(disp == app, "got %p, %p\n", app, disp);
        IDispatch_Release(app);

        hr = IWebBrowser2_get_Document(wb, &doc);
        todo_wine
        ok(hr == S_OK, "got 0x%08x\n", hr);
        if (hr == S_OK)
            test_dispatch_typeinfo(doc, viewdual_riids);

        IWebBrowser2_Release(wb);

        /* IServiceProvider */
        hr = IDispatch_QueryInterface(disp, &IID_IShellFolderViewDual, (void**)&view);
        ok(hr == E_NOINTERFACE, "got 0x%08x\n", hr);

        hr = IDispatch_QueryInterface(disp, &IID_IServiceProvider, (void**)&sp);
        ok(hr == S_OK, "got 0x%08x\n", hr);

        hr = IServiceProvider_QueryService(sp, &SID_STopLevelBrowser, &IID_IShellBrowser, (void**)&sb);
        ok(hr == S_OK, "got 0x%08x\n", hr);

        hr = IServiceProvider_QueryService(sp, &SID_STopLevelBrowser, &IID_IShellBrowser, (void**)&sb2);
        ok(hr == S_OK, "got 0x%08x\n", hr);
        ok(sb == sb2, "got %p, %p\n", sb, sb2);

        hr = IServiceProvider_QueryService(sp, &SID_STopLevelBrowser, &IID_IOleWindow, (void**)&unk);
        ok(hr == S_OK, "got 0x%08x\n", hr);
        IUnknown_Release(unk);

        hr = IServiceProvider_QueryService(sp, &SID_STopLevelBrowser, &IID_IExplorerBrowser, (void**)&unk);
        ok(hr == E_NOINTERFACE, "got 0x%08x\n", hr);

        hr = IShellBrowser_QueryInterface(sb, &IID_IExplorerBrowser, (void**)&unk);
        ok(hr == E_NOINTERFACE, "got 0x%08x\n", hr);

        hr = IShellBrowser_QueryInterface(sb, &IID_IWebBrowser2, (void**)&unk);
        ok(hr == E_NOINTERFACE, "got 0x%08x\n", hr);

        hr = IShellBrowser_QueryInterface(sb, &IID_IDispatch, (void**)&unk);
        ok(hr == E_NOINTERFACE, "got 0x%08x\n", hr);

        hr = IShellBrowser_QueryActiveShellView(sb, &sv);
        ok(hr == S_OK, "got 0x%08x\n", hr);
        IShellView_Release(sv);

        IShellBrowser_Release(sb2);
        IShellBrowser_Release(sb);

        hr = IServiceProvider_QueryService(sp, &SID_STopLevelBrowser, &IID_IUnknown, (void**)&unk);
        ok(hr == S_OK, "got 0x%08x\n", hr);

        hr = IUnknown_QueryInterface(unk, &IID_IShellBrowser, (void**)&sb2);
        ok(hr == S_OK, "got 0x%08x\n", hr);
        IShellBrowser_Release(sb2);
        IUnknown_Release(unk);

        hr = IServiceProvider_QueryService(sp, &SID_STopLevelBrowser, &IID_IShellView, (void**)&sv);
        ok(hr == E_NOINTERFACE, "got 0x%08x\n", hr);

        IServiceProvider_Release(sp);
        IDispatch_Release(disp);
    }

    disp = (void*)0xdeadbeef;
    ret = 0xdead;
    VariantInit(&v);
    hr = IShellWindows_FindWindowSW(shellwindows, &v, &v, SWC_DESKTOP, &ret, 0, &disp);
    ok(hr == S_OK || broken(hr == S_FALSE) /* winxp */, "got 0x%08x\n", hr);
    ok(disp == NULL, "got %p\n", disp);
    ok(ret != HandleToUlong(hwnd), "got %d\n", ret);

    disp = (void*)0xdeadbeef;
    ret = 0xdead;
    V_VT(&v) = VT_I4;
    V_I4(&v) = cookie;
    VariantInit(&v2);
    hr = IShellWindows_FindWindowSW(shellwindows, &v, &v2, SWC_BROWSER, &ret, SWFO_COOKIEPASSED, &disp);
    todo_wine
    ok(hr == S_FALSE, "got 0x%08x\n", hr);
    ok(disp == NULL, "got %p\n", disp);
    ok(ret == 0, "got %d\n", ret);

    hr = IShellWindows_Revoke(shellwindows, cookie);
    todo_wine
    ok(hr == S_OK, "got 0x%08x\n", hr);
    DestroyWindow(hwnd);
    IShellWindows_Release(shellwindows);
}
Пример #28
0
zend_object_iterator *php_com_iter_get(zend_class_entry *ce, zval *object, int by_ref)
{
	php_com_dotnet_object *obj;
	struct php_com_iterator *I;
	IEnumVARIANT *iev = NULL;
	DISPPARAMS dp;
	VARIANT v;
	unsigned long n_fetched;
	zval ptr;

	if (by_ref) {
		zend_error(E_ERROR, "An iterator cannot be used with foreach by reference");
	}

	obj = CDNO_FETCH(object);

	if (V_VT(&obj->v) != VT_DISPATCH && !V_ISARRAY(&obj->v)) {
		php_error_docref(NULL, E_WARNING, "variant is not an object or array VT=%d", V_VT(&obj->v));
		return NULL;
	}

	memset(&dp, 0, sizeof(dp));
	VariantInit(&v);

	I = (struct php_com_iterator*)ecalloc(1, sizeof(*I));
	zend_iterator_init(&I->iter);
	I->iter.funcs = &com_iter_funcs;
	Z_PTR(I->iter.data) = I;
	I->code_page = obj->code_page;
	ZVAL_UNDEF(&I->zdata);
	VariantInit(&I->safe_array);
	VariantInit(&I->v);

	if (V_ISARRAY(&obj->v)) {
		LONG bound;
		UINT dims;

		dims = SafeArrayGetDim(V_ARRAY(&obj->v));

		if (dims != 1) {
			php_error_docref(NULL, E_WARNING,
				   "Can only handle single dimension variant arrays (this array has %d)", dims);
			goto fail;
		}

		/* same semantics as foreach on a PHP array;
		 * make a copy and enumerate that copy */
		VariantCopy(&I->safe_array, &obj->v);

		/* determine the key value for the array */
		SafeArrayGetLBound(V_ARRAY(&I->safe_array), 1, &bound);
		SafeArrayGetUBound(V_ARRAY(&I->safe_array), 1, &I->sa_max);

		/* pre-fetch the element */
		if (php_com_safearray_get_elem(&I->safe_array, &I->v, bound)) {
			I->key = bound;
			ZVAL_NULL(&ptr);
			php_com_zval_from_variant(&ptr, &I->v, I->code_page);
			ZVAL_COPY_VALUE(&I->zdata, &ptr);
		} else {
			I->key = (ulong)-1;
		}

	} else {
		/* can we enumerate it? */
		if (FAILED(IDispatch_Invoke(V_DISPATCH(&obj->v), DISPID_NEWENUM,
						&IID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_METHOD|DISPATCH_PROPERTYGET,
						&dp, &v, NULL, NULL))) {
			goto fail;
		}

		/* get something useful out of it */
		if (V_VT(&v) == VT_UNKNOWN) {
			IUnknown_QueryInterface(V_UNKNOWN(&v), &IID_IEnumVARIANT, (void**)&iev);
		} else if (V_VT(&v) == VT_DISPATCH) {
			IDispatch_QueryInterface(V_DISPATCH(&v), &IID_IEnumVARIANT, (void**)&iev);
		}

		VariantClear(&v);

		if (iev == NULL) {
			goto fail;
		}

		I->ev = iev;

		/* Get the first element now */
		if (SUCCEEDED(IEnumVARIANT_Next(I->ev, 1, &I->v, &n_fetched)) && n_fetched > 0) {
			/* indicate that we have element 0 */
			I->key = 0;
			ZVAL_NULL(&ptr);
			php_com_zval_from_variant(&ptr, &I->v, I->code_page);
			ZVAL_COPY_VALUE(&I->zdata, &ptr);
		} else {
			/* indicate that there are no more items */
			I->key = (ulong)-1;
		}
	}

	return &I->iter;

fail:
	if (I) {
		VariantClear(&I->safe_array);
		VariantClear(&I->v);
		efree(I);
	}
	return NULL;
}
Пример #29
0
void AppMenu::CreateMenus()
{
    CMDIFrameWnd* pMainFrame = acedGetAcadFrame();
    pMainFrame->LockWindowUpdate();

    //得到菜单栏上面的最后一个菜单
    CString sName;
    if( !GetLastMenuFromMenubar( sName ) )
        return;

    sName.Replace( _T( "&" ), _T( "" ) ); //debug

    IAcadMenuGroup* mnuGrp = NULL;
    if ( !GetAcadMenuGroup( &mnuGrp, sName ) )
        return ;

    //得到所有菜单组
    IAcadPopupMenus*   mnus = NULL;
    IAcadPopupMenu*   mnu = NULL;
    IAcadPopupMenuItem*  mnuitem = NULL;
    HRESULT hr = S_OK;
    hr = mnuGrp->get_Menus( &mnus );
    long cnt = 0l;
    hr = mnus->get_Count( &cnt );
    int i = 0;
    int j = 0;
    int k = 0;
    VARIANT index;
    VariantInit( &index );
    V_VT( &index ) = VT_I4;
    CArray<IAcadPopupMenu*, IAcadPopupMenu*> MnuAdrs;

    long lIndex = 0;
    TCHAR MenuName[256];
    for ( i = 0; i < m_menuCount; i++ )
    {
        CString tmpMenu = m_TopMenuNames[i];
        tmpMenu.Replace( _T( "&" ), _T( "" ) );
        if( IsMenuExist( mnu, lIndex, tmpMenu, mnus ) ) //处理二次加载
        {
            V_I4( &index ) = lIndex;
        }
        else
        {
            //			MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, (LPTSTR)(LPCTSTR)m_TopMenuNames[i], -1, MenuName, 256);
            _tcscpy( MenuName, m_TopMenuNames[i] );
            mnus->Add( MenuName, &mnu );
            V_I4( &index ) = cnt++;
        }

        MnuAdrs.Add( mnu );
        mnu->InsertInMenuBar( index );
    }

    IAcadPopupMenu* MenuItem = NULL;
    int subMenuNum = 0;
    CCADMenuArray* Menus;
    TCHAR szSubMenu[256];
    TCHAR szSubMenuMacro[256];
    CString MenusName;
    CString Menusorder;
    for ( j = 0; j < m_menuCount; j++ )
    {
        Menus = m_menus.GetAt( j );
        subMenuNum = Menus->GetSize();
        for ( k = 0; k < subMenuNum; k++ )
        {
            mnu = MnuAdrs.GetAt( j );
            if ( !_tcscmp( _T( "--" ), Menus->GetAt( k )->name ) )
            {
                V_I4( &index ) = k;
                mnu->AddSeparator( index, &mnuitem );
            }
            else
            {
                V_I4( &index ) = k;
                MenusName = Menus->GetAt( k )->name;
                Menusorder = Menus->GetAt( k )->order;
                _tcscpy( szSubMenu, MenusName );
                _tcscpy( szSubMenuMacro, Menusorder );
                //MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, (LPTSTR)(LPCTSTR)MenusName, -1, szSubMenu, 256);
                //MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, (LPTSTR)(LPCTSTR)Menusorder, -1, szSubMenuMacro, 256);
                if ( _tcscspn( Menus->GetAt( k )->name, _T( "*" ) ) < ( size_t )MenusName.GetLength() )
                {
                    MenusName.TrimLeft( _T( '*' ) );
                    //					MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, (LPTSTR)(LPCTSTR)MenusName, -1, szSubMenu, 256);
                    _tcscpy( szSubMenu, MenusName );
                    hr = mnu->AddSubMenu( index, szSubMenu, &MenuItem );
                }
                else if ( _tcscspn( Menus->GetAt( k )->name, _T( "$" ) ) < ( size_t )MenusName.GetLength() )
                {
                    MenusName.TrimLeft( _T( '$' ) );
                    if( MenusName.Compare( _T( "--" ) ) == 0 ) //添加子菜单的分隔符
                    {
                        hr = MenuItem->AddSeparator( index, &mnuitem );
                    }
                    else
                    {
                        //MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, (LPTSTR)(LPCTSTR)MenusName, -1, szSubMenu, 256);
                        _tcscpy( szSubMenu, MenusName );
                        hr = MenuItem->AddMenuItem( index, szSubMenu, szSubMenuMacro, &mnuitem );
                    }
                }
                else
                {
                    hr = mnu->AddMenuItem( index, szSubMenu, szSubMenuMacro, &mnuitem );
                }
            }
        }
    }

    for ( i = 0; i < MnuAdrs.GetSize(); i++ )
    {
        MnuAdrs[i]->Release();
    }
    mnuitem->Release();
    mnus->Release();
    mnuGrp->Release();
    pMainFrame->UnlockWindowUpdate();

    stcMyTopMenuNames.Copy( m_TopMenuNames ); //将顶级菜单名存入静态数组中,卸载时使用

    //return ;
}
Пример #30
0
int create_database()
{
	CoInitialize(NULL);
	hr = CoCreateInstance(CLSID_SQLSERVERCE, 0, CLSCTX_INPROC_SERVER,
		IID_IDBDataSourceAdmin, (void**)& pIDBDataSourceAdmin);

	if(FAILED(hr))
	{
		goto Exit;
	}

	//initialize property structures
	VariantInit(&dbprop[0].vValue);
	for(int i=0; i< sizeof(sscedbprop) / sizeof(sscedbprop[0]); i++)
	{
		VariantInit(&sscedbprop[i].vValue);
	}

	//specify the property with name of the database
	dbprop[0].dwPropertyID = DBPROP_INIT_DATASOURCE;
	dbprop[0].dwOptions = DBPROPOPTIONS_REQUIRED;
	dbprop[0].vValue.vt = VT_BSTR;
	dbprop[0].vValue.bstrVal = SysAllocString(L"c:\\code\\achlookup\\db.sdf");

	if(NULL == dbprop[0].vValue.bstrVal)
	{
		hr = E_OUTOFMEMORY;
		goto Exit;
	}

	//specify the encryption mode.
	sscedbprop[0].dwPropertyID = DBPROP_SSCE_ENCRYPTIONMODE;
	sscedbprop[0].dwOptions = DBPROPOPTIONS_REQUIRED;
	sscedbprop[0].vValue.vt = VT_I4;
	sscedbprop[0].vValue.intVal = DBPROPVAL_SSCE_EM_PLATFORM_DEFAULT;

	sscedbprop[1].dwPropertyID = DBPROP_SSCE_DBPASSWORD;
	sscedbprop[1].dwOptions = DBPROPOPTIONS_REQUIRED;
	sscedbprop[1].vValue.vt = VT_BSTR;
	sscedbprop[1].vValue.bstrVal = SysAllocString(L"welcome");

	if(NULL == sscedbprop[1].vValue.bstrVal)
	{
		hr = E_OUTOFMEMORY;
		goto Exit;
	}

	//set the case sensitivity to true
	sscedbprop[2].dwPropertyID = DBPROP_SSCE_DBCASESENSITIVE;
	sscedbprop[2].dwOptions = DBPROPOPTIONS_REQUIRED;
	sscedbprop[2].vValue.vt = VT_BOOL;
	sscedbprop[2].vValue.boolVal = VARIANT_TRUE;

	dbpropset[0].guidPropertySet = DBPROPSET_DBINIT;
	dbpropset[0].rgProperties = dbprop;
	dbpropset[0].cProperties = sizeof(dbprop)/sizeof(dbprop[0]);

	dbpropset[1].guidPropertySet = DBPROPSET_SSCE_DBINIT;
	dbpropset[1].rgProperties = sscedbprop;
	dbpropset[1].cProperties = sizeof(sscedbprop)/sizeof(sscedbprop[0]);

	//create and initialize the database.
	hr = pIDBDataSourceAdmin->CreateDataSource(sizeof(dbpropset)/sizeof(dbpropset[0]),
		dbpropset,NULL,IID_IUnknown, &pIUnknownSession);

	if(FAILED(hr))
	{
		goto Exit;
	}

	//at this point the database is created

Exit:
	//probably should do more cleanup
	CoUninitialize();
	return 0;

}