コード例 #1
0
ファイル: BrowserFactory.cpp プロジェクト: Eric-Shi/selenium
bool BrowserFactory::AttachToBrowser(ProcessWindowInfo* process_window_info,
                                     std::string* error_message) {
  LOG(TRACE) << "Entering BrowserFactory::AttachToBrowser";
  clock_t end = clock() + (this->browser_attach_timeout_ / 1000 * CLOCKS_PER_SEC);
  while (process_window_info->hwndBrowser == NULL) {
    if (this->browser_attach_timeout_ > 0 && (clock() > end)) {
      break;
    }
    ::EnumWindows(&BrowserFactory::FindBrowserWindow,
                  reinterpret_cast<LPARAM>(process_window_info));
    if (process_window_info->hwndBrowser == NULL) {
      ::Sleep(250);
    }
  }

  if (process_window_info->hwndBrowser == NULL) {
    *error_message = StringUtilities::Format(ATTACH_TIMEOUT_ERROR_MESSAGE,
                                             process_window_info->dwProcessId,
                                             this->browser_attach_timeout_);
    return false;
  }

  CComPtr<IHTMLDocument2> document;
  if (this->GetDocumentFromWindowHandle(process_window_info->hwndBrowser,
                                        &document)) {
    CComPtr<IHTMLWindow2> window;
    HRESULT hr = document->get_parentWindow(&window);

    // Test for zoom level = 100%
    int zoom_level = 100;
    LOG(DEBUG) << "Ignoring zoom setting: " << this->ignore_zoom_setting_;
    if (!this->ignore_zoom_setting_) {
      zoom_level = this->GetZoomLevel(document, window);
    }
    if (zoom_level != 100) {
      *error_message = StringUtilities::Format(ZOOM_SETTING_ERROR_MESSAGE,
                                               zoom_level);
      return false;
    }
    if (SUCCEEDED(hr)) {
      // http://support.microsoft.com/kb/257717
      CComPtr<IServiceProvider> provider;
      window->QueryInterface<IServiceProvider>(&provider);
      if (provider) {
        CComPtr<IServiceProvider> child_provider;
        hr = provider->QueryService(SID_STopLevelBrowser,
                                    IID_IServiceProvider,
                                    reinterpret_cast<void**>(&child_provider));
        if (SUCCEEDED(hr)) {
          IWebBrowser2* browser;
          hr = child_provider->QueryService(SID_SWebBrowserApp,
                                            IID_IWebBrowser2,
                                            reinterpret_cast<void**>(&browser));
          if (SUCCEEDED(hr)) {
            process_window_info->pBrowser = browser;
            return true;
          } else {
            LOGHR(WARN, hr) << "IServiceProvider::QueryService for SID_SWebBrowserApp failed";
          }
        } else {
          LOGHR(WARN, hr) << "IServiceProvider::QueryService for SID_STopLevelBrowser failed";
        }
      } else {
        LOG(WARN) << "QueryInterface for IServiceProvider failed";
      }
    } else {
      LOGHR(WARN, hr) << "Call to IHTMLDocument2::get_parentWindow failed";
    }
  } else {
    *error_message = "Could not get document from window handle";
  }
  return false;
}
コード例 #2
0
ファイル: BrowserFactory.cpp プロジェクト: Eric-Shi/selenium
int BrowserFactory::GetZoomLevel(IHTMLDocument2* document, IHTMLWindow2* window) {
  LOG(TRACE) << "Entering BrowserFactory::GetZoomLevel";
  int zoom = 100;  // Chances are the zoom level hasn't been modified....
  HRESULT hr = S_OK;
  if (this->ie_major_version_ == 7) {
    CComPtr<IHTMLElement> body;
    hr = document->get_body(&body);
    if (FAILED(hr)) {
      LOGHR(WARN, hr) << "Call to IHTMLDocument2::get_body failed";
      return zoom;
    }

    long offset_width = 0;
    hr = body->get_offsetWidth(&offset_width);
    if (FAILED(hr)) {
      LOGHR(WARN, hr) << "Call to IHTMLElement::get_offsetWidth failed";
      return zoom;
    }

    CComPtr<IHTMLElement2> body2;
    hr = body.QueryInterface<IHTMLElement2>(&body2);
    if (FAILED(hr)) {
      LOGHR(WARN, hr) << "Attempt to QueryInterface for IHTMLElement2 failed";
      return zoom;
    }

    CComPtr<IHTMLRect> rect;
    hr = body2->getBoundingClientRect(&rect);
    if (FAILED(hr)) {
      LOGHR(WARN, hr) << "Call to IHTMLElement2::getBoundingClientRect failed";
      return zoom;
    }

    long left = 0, right = 0;
    hr = rect->get_left(&left);
    if (FAILED(hr)) {
      LOGHR(WARN, hr) << "Call to IHTMLRect::get_left failed";
      return zoom;
    }

    hr = rect->get_right(&right);
    if (FAILED(hr)) {
      LOGHR(WARN, hr) << "Call to IHTMLRect::get_right failed";
      return zoom;
    }

    zoom = static_cast<int>((static_cast<double>(right - left) / offset_width) * 100.0);
  } else if (this->ie_major_version_ >= 8) {
    CComPtr<IHTMLScreen> screen;
    hr = window->get_screen(&screen);
    if (FAILED(hr)) {
      LOGHR(WARN, hr) << "Call to IHTMLWindow2::get_screen failed";
      return zoom;
    }

    CComPtr<IHTMLScreen2> screen2;
    hr = screen.QueryInterface<IHTMLScreen2>(&screen2);
    if (FAILED(hr)) {
      LOGHR(WARN, hr) << "Attempt to QueryInterface for IHTMLScreen2 failed";
      return zoom;
    }

    long device_xdpi=0, logical_xdpi = 0;
    hr = screen2->get_deviceXDPI(&device_xdpi);
    if (FAILED(hr)) {
      LOGHR(WARN, hr) << "Call to IHTMLScreen2::get_deviceXDPI failed";
      return zoom;
    }

    hr = screen2->get_logicalXDPI(&logical_xdpi);
    if (FAILED(hr)) {
      LOGHR(WARN, hr) << "Call to IHTMLScreen2::get_logicalXDPI failed";
      return zoom;
    }

    zoom = static_cast<int>((static_cast<double>(device_xdpi) / logical_xdpi) * 100.0);
  } else {
    // IE6 case
    zoom = 100;
  }

  LOG(DEBUG) << "Browser zoom level is " << zoom << "%";
  return zoom;
}
コード例 #3
0
ファイル: dshowutil.cpp プロジェクト: shilinxu/iprojects
HRESULT FindOtherSplitterPin(IPin *pPinIn, GUID guid, int nStream, IPin **ppSplitPin)
{
    if (!ppSplitPin)
        return E_POINTER;

    CComPtr< IPin > pPinOut;
    pPinOut = pPinIn;

    while(pPinOut)
    {
        PIN_INFO ThisPinInfo;
        pPinOut->QueryPinInfo(&ThisPinInfo);
        if(ThisPinInfo.pFilter) ThisPinInfo.pFilter->Release();

        pPinOut = NULL;
        CComPtr< IEnumPins > pEnumPins;
        ThisPinInfo.pFilter->EnumPins(&pEnumPins);
        if(!pEnumPins)
        {
            return NULL;
        }

        // look at every pin on the current filter...
        //
        ULONG Fetched = 0;
        while(1)
        {
            CComPtr< IPin > pPin;
            Fetched = 0;
            _ASSERT(!pPin); // is it out of scope?
            pEnumPins->Next(1, &pPin, &Fetched);
            if(!Fetched)
            {
                break;
            }

            PIN_INFO pi;
            pPin->QueryPinInfo(&pi);
            if(pi.pFilter) pi.pFilter->Release();

            // if it's an input pin...
            //
            if(pi.dir == PINDIR_INPUT)
            {
                // continue searching upstream from this pin
                //
                pPin->ConnectedTo(&pPinOut);

                // a pin that supports the required media type is the
                // splitter pin we are looking for!  We are done
                //
            }
            else
            {
                CComPtr< IEnumMediaTypes > pMediaEnum;
                pPin->EnumMediaTypes(&pMediaEnum);
                if(pMediaEnum)
                {
                    Fetched = 0;
                    AM_MEDIA_TYPE *pMediaType;
                    pMediaEnum->Next(1, &pMediaType, &Fetched);
                    if(Fetched)
                    {
                        if(pMediaType->majortype == guid)
                        {
                            if(nStream-- == 0)
                            {
                                DeleteMediaType(pMediaType);
                                *ppSplitPin = pPin;
                                (*ppSplitPin)->AddRef();
                                return S_OK;
                            }
                        }
                        DeleteMediaType(pMediaType);
                    }
                }
            }

            // go try the next pin

        } // while
    }
    _ASSERT(FALSE);
    return E_FAIL;
}
コード例 #4
0
ファイル: Receive.cpp プロジェクト: leg0/WinLIRC
int Receive::init(int devNum, unsigned minRepeat)
{	
	m_minRepeat = minRepeat;
	deinit();

	int devCount=0;

	// create system device enumerator
	CComPtr <ICreateDevEnum>	pSysDevEnum = nullptr;	
	HRESULT hr = pSysDevEnum.CoCreateInstance(CLSID_SystemDeviceEnum);
	if (hr == S_OK)
	{
		// create a class enumerator for the desired category defined by classGuid.
		CComPtr <IEnumMoniker> pEnumCat = nullptr;	//moniker enumerator for filter categories
		hr = pSysDevEnum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory, &pEnumCat, 0);
		if (hr == S_OK)
		{
			// reset the enumeration
			pEnumCat->Reset();

			// now iterate through enumeration
			ULONG cFetched = 0;
			CComPtr <IMoniker> pMoniker = nullptr;

			// get a pointer to each moniker
			while(pEnumCat->Next(1, &pMoniker, &cFetched) == S_OK)
			{
				CComPtr <IBaseFilter> pFilter = nullptr;
				// create an instance of the filter
				hr = pMoniker->BindToObject(0, 0, IID_IBaseFilter, (void**)&pFilter);
				if (hr == S_OK)
				{							
					m_pKsVCPropSet = nullptr;
					// query for interface
					hr = pFilter->QueryInterface(IID_IKsPropertySet, (void **)&m_pKsVCPropSet);
					if (m_pKsVCPropSet)
					{
						DWORD type_support;
						hr = m_pKsVCPropSet->QuerySupported(KSPROPSETID_CustomIRCaptureProperties,
							KSPROPERTY_IRCAPTURE_COMMAND,
							&type_support);
						if ( SUCCEEDED(hr) && (type_support & KSPROPERTY_SUPPORT_SET) )
							if (devCount == devNum)
								break;
					}
				}
				pMoniker.Release();
			}
		}
	}

	if ( FAILED(hr) || !m_pKsVCPropSet )
		return 0;

	KSPROPERTY_IRCAPTURE_COMMAND_S ir_cmd;
	ir_cmd.CommandCode = IRCAPTURE_COMMAND_START;

	// make call into driver
	hr = m_pKsVCPropSet->Set(KSPROPSETID_CustomIRCaptureProperties,
		KSPROPERTY_IRCAPTURE_COMMAND,
		&ir_cmd, sizeof(ir_cmd),
		&ir_cmd, sizeof(ir_cmd));

	if FAILED(hr) return 0;

	threadHandle = CreateThread(nullptr,0,IRReader,(void *)this,0,nullptr);
	return threadHandle!=nullptr;
}
コード例 #5
0
// Enumerates all Contacts Services, displaying the associated device of each service.
void EumerateContactsServices(CAtlArray<PWSTR>& ContactsServicePnpIDs)
{
    HRESULT                                 hr              = S_OK;
    DWORD                                   cPnpDeviceIDs   = 0;
    PWSTR*                                  pPnpDeviceIDs   = NULL;
    CComPtr<IPortableDeviceManager>         pPortableDeviceManager;
    CComPtr<IPortableDeviceServiceManager>  pServiceManager;

    // CoCreate the IPortableDeviceManager interface to enumerate
    // portable devices and to get information about them.
    hr = CoCreateInstance(CLSID_PortableDeviceManager,
                          NULL,
                          CLSCTX_INPROC_SERVER,
                          IID_PPV_ARGS(&pPortableDeviceManager));

    if (FAILED(hr))
    {
        printf("! Failed to CoCreateInstance CLSID_PortableDeviceManager, hr = 0x%lx\n",hr);
    }        

    // Retrieve the IPortableDeviceServiceManager interface to enumerate device services.
    if (SUCCEEDED(hr))
    {
        hr = pPortableDeviceManager->QueryInterface(IID_PPV_ARGS(&pServiceManager));
        if (FAILED(hr))
        {
            printf("! Failed to QueryInterface IID_IPortableDeviceServiceManager, hr = 0x%lx\n",hr);
        }
    }

    if (SUCCEEDED(hr))
    {
        // First, pass NULL as the PWSTR array pointer to get the total number
        // of devices found on the system.
        hr = pPortableDeviceManager->GetDevices(NULL, &cPnpDeviceIDs);

        if (FAILED(hr))
        {
            printf("! Failed to get number of devices on the system, hr = 0x%lx\n",hr);
        }

        if (SUCCEEDED(hr) && (cPnpDeviceIDs > 0))
        {
            // Second, allocate an array to hold the PnPDeviceID strings returned from
            // the IPortableDeviceManager::GetDevices method
            pPnpDeviceIDs = new (std::nothrow) PWSTR[cPnpDeviceIDs];

            if (pPnpDeviceIDs != NULL)
            {
                DWORD dwIndex = 0;

                hr = pPortableDeviceManager->GetDevices(pPnpDeviceIDs, &cPnpDeviceIDs);
                if (SUCCEEDED(hr))
                {   
					//<SnippetOpenService1>
                    // For each device found, find the contacts service
                    for (dwIndex = 0; dwIndex < cPnpDeviceIDs; dwIndex++)
                    {
                        DWORD   cPnpServiceIDs = 0;
                        PWSTR   pPnpServiceID  = NULL;

                        // First, pass NULL as the PWSTR array pointer to get the total number
                        // of contacts services (SERVICE_Contacts) found on the device.
                        // To find the total number of all services on the device, use GUID_DEVINTERFACE_WPD_SERVICE.
                        hr = pServiceManager->GetDeviceServices(pPnpDeviceIDs[dwIndex], SERVICE_Contacts, NULL, &cPnpServiceIDs);
                        
                        if (SUCCEEDED(hr) && (cPnpServiceIDs > 0))
                        {                               
                            // For simplicity, we are only using the first contacts service on each device
                            cPnpServiceIDs = 1;
                            hr = pServiceManager->GetDeviceServices(pPnpDeviceIDs[dwIndex], SERVICE_Contacts, &pPnpServiceID, &cPnpServiceIDs);

                            if (SUCCEEDED(hr))
                            {
                                // We've found the service, display it and save its PnP Identifier
                                ContactsServicePnpIDs.Add(pPnpServiceID);

                                printf("[%d] ", static_cast<DWORD>(ContactsServicePnpIDs.GetCount()-1));

                                // Display information about the device that contains this service.
                                DisplayDeviceInformation(pServiceManager, pPnpServiceID);

                                // ContactsServicePnpIDs now owns the memory for this string
                                pPnpServiceID = NULL;
                            }
                            else
                            {
                                printf("! Failed to get the first contacts service from '%ws, hr = 0x%lx\n",pPnpDeviceIDs[dwIndex],hr);
                            }
                        }
                    }
					//</SnippetOpenService1>
                }

                // Free all returned PnPDeviceID strings
                FreePortableDevicePnPIDs(pPnpDeviceIDs, cPnpDeviceIDs);

                // Delete the array of PWSTR pointers
                delete [] pPnpDeviceIDs;
                pPnpDeviceIDs = NULL;

            }
            else
            {
                printf("! Failed to allocate memory for PWSTR array\n");
            }            
        }
    }
    
    printf("\n%d Contacts Device Service(s) found on the system\n\n", static_cast<DWORD>(ContactsServicePnpIDs.GetCount()));
}
コード例 #6
0
// Calls EnumerateDeviceServices() function to display device services on the system
// and to obtain the total number of device services found.  If 1 or more device services
// are found, this function prompts the user to choose a device service using
// a zero-based index.
void ChooseDeviceService(IPortableDeviceService** ppService)
{
    HRESULT                         hr                  = S_OK;
    UINT                            uiCurrentService    = 0;
    CHAR                            szSelection[81]     = {0};

    CComPtr<IPortableDeviceValues>  pClientInformation;
    CAtlArray<PWSTR>                ContactsServicesArray;

    if (ppService == NULL)
    {
        printf("! A NULL IPortableDeviceService interface pointer was received\n");
        return;
    }

    if (*ppService != NULL)
    {
        // To avoid operating on potiential bad pointers, reject any non-null
        // IPortableDeviceService interface pointers.  This will force the caller
        // to properly release the interface before obtaining a new one.
        printf("! A non-NULL IPortableDeviceService interface pointer was received, please release this interface before obtaining a new one.\n");
        return;
    }

    // Fill out information about your application, so the device knows
    // who they are speaking to.

    GetClientInformation(&pClientInformation);

    // Enumerate and display all Contacts services
    EumerateContactsServices(ContactsServicesArray);

    DWORD cServicePnPIDs = static_cast<DWORD>(ContactsServicesArray.GetCount());
    
    if (cServicePnPIDs > 0)
    {
        CComPtr<IPortableDeviceService> pService;

        // Prompt user to enter an index for the device they want to choose.
        printf("Enter the index of the Contacts device service you wish to use.\n>");
        hr = StringCbGetsA(szSelection,sizeof(szSelection));
        if (SUCCEEDED(hr))
        {
            uiCurrentService = (UINT) atoi(szSelection);
            if (uiCurrentService >= cServicePnPIDs)
            {
                printf("An invalid Contacts device service index was specified, defaulting to the first in the list.\n");
                uiCurrentService = 0;
            }
        }
        else
        {
            printf("An invalid Contacts device service index was specified, defaulting to the first in the list.\n");
            uiCurrentService = 0;
        }

        // CoCreate the IPortableDeviceService interface and call Open() with
        // the chosen PnPServiceID string.
		//<SnippetOpenService2>
        hr = CoCreateInstance(CLSID_PortableDeviceServiceFTM,
                              NULL,
                              CLSCTX_INPROC_SERVER,
                              IID_PPV_ARGS(&pService));
        if (SUCCEEDED(hr))
        {
            hr = pService->Open(ContactsServicesArray[uiCurrentService], pClientInformation);
            if (FAILED(hr))
            {
                if (hr == E_ACCESSDENIED)
                {
                    printf("Failed to Open the service for Read Write access, will open it for Read-only access instead\n");

                    pClientInformation->SetUnsignedIntegerValue(WPD_CLIENT_DESIRED_ACCESS, GENERIC_READ);

                    hr = pService->Open(ContactsServicesArray[uiCurrentService], pClientInformation);

                    if (FAILED(hr))
                    {
                        printf("! Failed to Open the service for Read access, hr = 0x%lx\n",hr);
                    }
                }
                else
                {
                    printf("! Failed to Open the service, hr = 0x%lx\n",hr);
                }
            }
			//</SnippetOpenService2>
            if (SUCCEEDED(hr))
            {
                printf("Successfully opened the selected Contacts service\n");

                // Successfully opened a service, set the result
                *ppService = pService.Detach();
            }
            
        }
        else
        {
            printf("! Failed to CoCreateInstance CLSID_PortableDeviceServiceFTM, hr = 0x%lx\n",hr);
        }

        // Release the service PnP IDs allocated by EumerateContactsServices
        FreeServicePnPIDs(ContactsServicesArray);
    }

    // If no devices with the Contacts service were found on the system, just exit this function.
}
コード例 #7
0
ファイル: ImageHandler.cpp プロジェクト: MussaratAziz/console
void ImageHandler::LoadDesktopWallpaperWin8(MonitorEnumData* pEnumData)
{
	CComPtr<IDesktopWallpaper> desktopWallpaper;
	HRESULT hr = desktopWallpaper.CoCreateInstance(CLSID_DesktopWallpaper, nullptr, CLSCTX_ALL);
	if(FAILED(hr)) return;

	UINT count;
	hr = desktopWallpaper->GetMonitorDevicePathCount(&count);
	if(FAILED(hr)) return;

	for(UINT i = 0; i < count; i++)
	{
		// Get the device path for the monitor.
		CComHeapPtr<wchar_t> spszId;
		hr = desktopWallpaper->GetMonitorDevicePathAt(i, &spszId);
		if(FAILED(hr)) continue;

		// Get the monitor location.
		CRect rectMonitor;
		hr = desktopWallpaper->GetMonitorRECT(spszId, (LPRECT)rectMonitor);
		if(FAILED(hr)) continue;

		// Get the wallpaper on that monitor.
		CComHeapPtr<wchar_t> spszWallpaper;
		hr = desktopWallpaper->GetWallpaper(spszId, &spszWallpaper);
		if(FAILED(hr)) continue;

		TRACE(
			L"wallpaper picture on '%s' (%ix%i)-(%ix%i) is '%s'\n",
			static_cast<wchar_t*>(spszId),
			rectMonitor.left, rectMonitor.top,
			rectMonitor.right, rectMonitor.bottom,
			static_cast<wchar_t*>(spszWallpaper));

		std::shared_ptr<BackgroundImage> bkImage;

		if(spszWallpaper.m_pData && *spszWallpaper.m_pData)
		{
			bkImage.reset(new BackgroundImage (pEnumData->bkImage->imageData));
			bkImage->imageData.strFilename = spszWallpaper.m_pData;
			bkImage->bWallpaper = true;
			ImageHandler::LoadImageW(bkImage);
		}
		else
		{
			bkImage = pEnumData->bkImage;
		}

		if( bkImage->originalImage.get() )
		{
			// create template image
			CDC     dcTemplate;
			CBitmap	bmpTemplate;
			dcTemplate.CreateCompatibleDC(NULL);

			DWORD dwNewWidth = rectMonitor.Width();
			DWORD dwNewHeight = rectMonitor.Height();
			ImageHandler::PaintRelativeImage(pEnumData->dcTemplate, bmpTemplate, bkImage, dwNewWidth, dwNewHeight);

			dcTemplate.SelectBitmap(bmpTemplate);

			ImageHandler::PaintTemplateImage(
				dcTemplate,
				rectMonitor.left - ::GetSystemMetrics(SM_XVIRTUALSCREEN),
				rectMonitor.top - ::GetSystemMetrics(SM_YVIRTUALSCREEN),
				dwNewWidth,
				dwNewHeight,
				rectMonitor.Width(),
				rectMonitor.Height(),
				pEnumData->bkImage);
		}
	}
}
コード例 #8
0
ファイル: ImageHandler.cpp プロジェクト: MussaratAziz/console
bool ImageHandler::GetDesktopImageData(ImageData& imageData)
{
	CRegKey keyColors;

	if (keyColors.Open(HKEY_CURRENT_USER, L"Control Panel\\Colors", KEY_READ) != ERROR_SUCCESS) return false;

	CString	strBackground;
	DWORD	dwDataSize = 32;

	if (keyColors.QueryStringValue(L"Background", strBackground.GetBuffer(dwDataSize), &dwDataSize) != ERROR_SUCCESS)
	{
		strBackground.ReleaseBuffer();
		return false;
	}
	strBackground.ReleaseBuffer();

	wstringstream	streamBk(wstring(strBackground.operator LPCTSTR()));
	DWORD			r = 0;
	DWORD			g = 0;
	DWORD			b = 0;

	streamBk >> r;
	streamBk >> g;
	streamBk >> b;

	CRegKey keyDesktop;
	if (keyDesktop.Open(HKEY_CURRENT_USER, L"Control Panel\\Desktop", KEY_READ) != ERROR_SUCCESS) return false;

	DWORD	dwChars = 0;
	CString	strWallpaperFile;
	CString	strWallpaperStyle;
	CString	strWallpaperTile;

	dwChars = 32;
	keyDesktop.QueryStringValue(L"WallpaperStyle", strWallpaperStyle.GetBuffer(dwChars), &dwChars);
	dwChars = 32;
	keyDesktop.QueryStringValue(L"TileWallpaper", strWallpaperTile.GetBuffer(dwChars), &dwChars);
	dwChars = MAX_PATH;
	keyDesktop.QueryStringValue(L"Wallpaper", strWallpaperFile.GetBuffer(dwChars), &dwChars);

	strWallpaperStyle.ReleaseBuffer();
	strWallpaperFile.ReleaseBuffer();
	strWallpaperTile.ReleaseBuffer();

	// set background data
	imageData.strFilename	= strWallpaperFile;
	imageData.bRelative		= true;
	imageData.bExtend		= false;
	imageData.crBackground	= RGB(static_cast<BYTE>(r), static_cast<BYTE>(g), static_cast<BYTE>(b));

	if (strWallpaperTile == L"1")
	{
		imageData.imagePosition= imagePositionTile;
	}
	else
	{
		if (strWallpaperStyle == L"0")
		{
			imageData.imagePosition= imagePositionCenter;
		}
		else if (strWallpaperStyle == L"6")
		{
			imageData.imagePosition= imagePositionFit;
		}
		else if (strWallpaperStyle == L"10")
		{
			imageData.imagePosition= imagePositionFill;
		}
		else if (strWallpaperStyle == L"22")
		{
			imageData.imagePosition= imagePositionFill;
			imageData.bExtend = true;
		}
		else
		{
			imageData.imagePosition= imagePositionStretch;
		}
	}

#if _WIN32_WINNT >= 0x0602
	if( ImageHandler::IsWin8() )
	{
		CComPtr<IDesktopWallpaper> desktopWallpaper;
		HRESULT hr = desktopWallpaper.CoCreateInstance(CLSID_DesktopWallpaper, nullptr, CLSCTX_ALL);
		if( SUCCEEDED(hr) )
		{
			DESKTOP_WALLPAPER_POSITION position;
			hr = desktopWallpaper->GetPosition(&position);

			UINT count = 0;
			hr = desktopWallpaper->GetMonitorDevicePathCount(&count);
			if( hr == S_OK && position == DWPOS_SPAN && count > 1 )
			{
				CComHeapPtr<wchar_t> spszWallpaper;
				hr = desktopWallpaper->GetWallpaper(NULL, &spszWallpaper);
				if( hr == S_OK )
					imageData.bExtend = true;
			}
		}
	}
#endif

	return true;
}
コード例 #9
0
ファイル: LoopbackRecord.cpp プロジェクト: nmap/npcap
BOOL EnumerateComponents(CComPtr<INetCfg>& pINetCfg, const GUID* pguidClass)
{
	TRACE_ENTER();

	/*	cout << "\n\nEnumerating " << GUID2Str(pguidClass) << " class:\n" << endl;*/

	// IEnumNetCfgComponent provides methods that enumerate the INetCfgComponent interfaces 
	// for network components of a particular type installed on the operating system. 
	// Types of network components include network cards, protocols, services, and clients.
	CComPtr<IEnumNetCfgComponent> pIEnumNetCfgComponent;

	// get enumeration containing network components of the provided class (GUID)
	HRESULT hr = pINetCfg->EnumComponents(pguidClass, &pIEnumNetCfgComponent);

	if(!SUCCEEDED(hr))
	{
		TRACE_PRINT1("INetCfg::EnumComponents: error, errCode = 0x%08x.", hr);
		throw 1;
	} 

	// INetCfgComponent interface provides methods that control and retrieve 
	// information about a network component.
	CComPtr<INetCfgComponent> pINetCfgComponent;

	unsigned int nIndex = 1;
	BOOL bFound = FALSE;
	BOOL bFailed = FALSE;
	// retrieve the next specified number of INetCfgComponent interfaces in the enumeration sequence.
	while(pIEnumNetCfgComponent->Next(1, &pINetCfgComponent, 0) == S_OK)
	{
		/*		cout << GUID2Desc(pguidClass) << " "<< nIndex++ << ":\n";*/

// 		LPWSTR pszDisplayName = NULL;
// 		pINetCfgComponent->GetDisplayName(&pszDisplayName);
// 		wcout << L"\tDisplay name: " << wstring(pszDisplayName) << L'\n';
// 		CoTaskMemFree(pszDisplayName);

		LPWSTR pszBindName = NULL;
		pINetCfgComponent->GetBindName(&pszBindName);
//		wcout << L"\tBind name: " << wstring(pszBindName) << L'\n';

// 		DWORD dwCharacteristics = 0;
// 		pINetCfgComponent->GetCharacteristics(&dwCharacteristics);
// 		cout << "\tCharacteristics: " << dwCharacteristics << '\n';
// 
// 		GUID guid;  
// 		pINetCfgComponent->GetClassGuid(&guid);
// 		cout << "\tClass GUID: " << guid.Data1 << '-' << guid.Data2 << '-'
// 			<< guid.Data3 << '-' << (unsigned int) guid.Data4 << '\n';
// 
// 		ULONG ulDeviceStatus = 0;
// 		pINetCfgComponent->GetDeviceStatus(&ulDeviceStatus);
// 		cout << "\tDevice Status: " << ulDeviceStatus << '\n';
// 
// 		LPWSTR pszHelpText = NULL;
// 		pINetCfgComponent->GetHelpText(&pszHelpText);
// 		wcout << L"\tHelp Text: " << wstring(pszHelpText) << L'\n';
// 		CoTaskMemFree(pszHelpText);
// 
// 		LPWSTR pszID = NULL;
// 		pINetCfgComponent->GetId(&pszID);
// 		wcout << L"\tID: " << wstring(pszID) << L'\n';
// 		CoTaskMemFree(pszID);
// 
// 		pINetCfgComponent->GetInstanceGuid(&guid);
// 		cout << "\tInstance GUID: " << guid.Data1 << '-' << guid.Data2 << '-'
// 			<< guid.Data3 << '-' << (unsigned int) guid.Data4 << '\n';

		LPWSTR pszPndDevNodeId = NULL;
		hr = pINetCfgComponent->GetPnpDevNodeId(&pszPndDevNodeId);
		if (!SUCCEEDED(hr))
		{
			TRACE_PRINT1("GetPnpDevNodeId failed: %#x", hr);
			TRACE_EXIT();
			return FALSE;
		}
//		wcout << L"\tPNP Device Node ID: " << wstring(pszPndDevNodeId) << L'\n';

		int iDevID = getIntDevID(pszPndDevNodeId);
		TRACE_PRINT4("INetCfgComponent::GetPnpDevNodeId: executing, pszPndDevNodeId = %s, iDevID = %d, g_NpcapAdapterID = %d, pszBindName = %ws.",
			pszPndDevNodeId, iDevID, g_NpcapAdapterID, pszBindName);
		if (g_NpcapAdapterID == iDevID)
		{
			bFound = TRUE;

			TRACE_PRINT2("INetCfgComponent::SetDisplayName: executing, g_NpcapAdapterID = iDevID = %d, pszBindName = %ws.", g_NpcapAdapterID, pszBindName);
			hr = pINetCfgComponent->SetDisplayName(NPCAP_LOOPBACK_ADAPTER_NAME);

			if (hr != S_OK)
			{
				TRACE_PRINT1("INetCfgComponent::SetDisplayName: error, errCode = 0x%08x.", hr);
				bFailed = TRUE;
			}

			if (!AddFlagToRegistry(pszBindName))
			{
				TRACE_PRINT1("AddFlagToRegistry: error, pszBindName = %ws.", pszBindName);
				bFailed = TRUE;
			}

 			if (!AddFlagToRegistry_Service(pszBindName))
 			{
				TRACE_PRINT1("AddFlagToRegistry_Service: error, pszBindName = %ws.", pszBindName);
 				bFailed = TRUE;
 			}

			if (!RenameLoopbackNetwork(pszBindName))
			{
				TRACE_PRINT1("RenameLoopbackNetwork: error, pszBindName = %ws.", pszBindName);
				bFailed = TRUE;
			}
		}

		CoTaskMemFree(pszBindName);
		CoTaskMemFree(pszPndDevNodeId);
		pINetCfgComponent.Release();

		if (bFound)
		{
			TRACE_EXIT();
			return !bFailed;
		}
	}

	TRACE_EXIT();
	return FALSE;
}
コード例 #10
0
ファイル: shlfolder.cpp プロジェクト: reactos/reactos
HRESULT SHELL32_GetFSItemAttributes(IShellFolder * psf, LPCITEMIDLIST pidl, LPDWORD pdwAttributes)
{
    DWORD dwFileAttributes, dwShellAttributes;

    if (!_ILIsFolder(pidl) && !_ILIsValue(pidl))
    {
        ERR("Got wrong type of pidl!\n");
        *pdwAttributes &= SFGAO_CANLINK;
        return S_OK;
    }

    if (*pdwAttributes & ~dwSupportedAttr)
    {
        WARN ("attributes 0x%08x not implemented\n", (*pdwAttributes & ~dwSupportedAttr));
        *pdwAttributes &= dwSupportedAttr;
    }

    dwFileAttributes = _ILGetFileAttributes(pidl, NULL, 0);

    /* Set common attributes */
    dwShellAttributes = *pdwAttributes;
    dwShellAttributes |= SFGAO_FILESYSTEM | SFGAO_DROPTARGET | SFGAO_HASPROPSHEET | SFGAO_CANDELETE |
                         SFGAO_CANRENAME | SFGAO_CANLINK | SFGAO_CANMOVE | SFGAO_CANCOPY;

    if (dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
    {
        dwShellAttributes |=  (SFGAO_FOLDER | SFGAO_HASSUBFOLDER | SFGAO_FILESYSANCESTOR);
    }
    else
        dwShellAttributes &= ~(SFGAO_FOLDER | SFGAO_HASSUBFOLDER | SFGAO_FILESYSANCESTOR);

    if (dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
        dwShellAttributes |=  SFGAO_HIDDEN;
    else
        dwShellAttributes &= ~SFGAO_HIDDEN;

    if (dwFileAttributes & FILE_ATTRIBUTE_READONLY)
        dwShellAttributes |=  SFGAO_READONLY;
    else
        dwShellAttributes &= ~SFGAO_READONLY;

    if (SFGAO_LINK & *pdwAttributes)
    {
        char ext[MAX_PATH];

        if (!_ILGetExtension(pidl, ext, MAX_PATH) || lstrcmpiA(ext, "lnk"))
        dwShellAttributes &= ~SFGAO_LINK;
    }

    if (SFGAO_HASSUBFOLDER & *pdwAttributes)
    {
        CComPtr<IShellFolder> psf2;
        if (SUCCEEDED(psf->BindToObject(pidl, 0, IID_PPV_ARG(IShellFolder, &psf2))))
        {
            CComPtr<IEnumIDList> pEnumIL;
            if (SUCCEEDED(psf2->EnumObjects(0, SHCONTF_FOLDERS, &pEnumIL)))
            {
                if (pEnumIL->Skip(1) != S_OK)
                    dwShellAttributes &= ~SFGAO_HASSUBFOLDER;
            }
        }
    }

    *pdwAttributes &= dwShellAttributes;

    TRACE ("-- 0x%08x\n", *pdwAttributes);
    return S_OK;
}
コード例 #11
0
ファイル: detool.cpp プロジェクト: sanyaade-mobiledev/rhodes
BOOL FindDevice(const CComBSTR& deviceIdentifier, IDeviceEmulatorManagerVMID** pDeviceVMID)
{
    HRESULT hr;

    CComPtr<IDeviceEmulatorManager> pDeviceEmulatorManager;
    hr = pDeviceEmulatorManager.CoCreateInstance(__uuidof(DeviceEmulatorManager));
    if (FAILED(hr)) {
        wprintf(L"Error: Unable to instantiate DeviceEmulatorManager. ErrorCode=0x%08X\n", hr);
        return FALSE;
    }

    for (; SUCCEEDED(hr); (hr = pDeviceEmulatorManager->MoveNext()))
    {
        CComPtr<IEnumManagerSDKs> pSDKEnumerator;

		hr = pDeviceEmulatorManager->EnumerateSDKs(&pSDKEnumerator);
        if (FAILED(hr)) {
            continue;
        }

		for (; SUCCEEDED(hr); (hr = pSDKEnumerator->MoveNext())) {
            CComPtr<IEnumVMIDs> pDeviceEnumerator;
            hr = pSDKEnumerator->EnumerateVMIDs(&pDeviceEnumerator);
            if (FAILED(hr)) {
                continue;
            }

            for (; SUCCEEDED(hr); (hr = pDeviceEnumerator->MoveNext())) {
                CComBSTR deviceName;
                CComBSTR deviceVMID;
                CComPtr<IDeviceEmulatorManagerVMID> pDevice;

                hr = pDeviceEnumerator->GetVMID(&pDevice);
                if (FAILED(hr)) {
                    continue;
                }

                hr = pDevice->get_Name(&deviceName);
                if (FAILED(hr)){
                    continue;
                }

                hr = pDevice->get_VMID(&deviceVMID);
                if (FAILED(hr)){
                    continue;
                }

                if (deviceIdentifier == deviceName || deviceIdentifier == deviceVMID){
                    *pDeviceVMID = pDevice;
                    (*pDeviceVMID)->AddRef();
                    return TRUE;
                }
            }
        }
    }

    wprintf(L"Error: Unable to locate the device '%s'", deviceIdentifier);
    return FALSE;
}
コード例 #12
0
ファイル: main.cpp プロジェクト: K4W2-Book/K4W2-Book
 ~KinectApp()
 {
     if ( kinect != nullptr ){
         kinect->Close();
     }
 }
コード例 #13
0
HRESULT CPixelShaderCompiler::InternalCompile(
    LPCSTR pSrcData,
    SIZE_T SrcDataSize,
    LPCSTR pSourceName,
    LPCSTR pEntrypoint,
    LPCSTR pProfile,
    DWORD Flags,
    IDirect3DPixelShader9** ppPixelShader,
    CString* pDisasm,
    CString* pErrMsg)
{
    if (!m_pD3DCompile) {
        return E_FAIL;
    }

    if (pDisasm && !m_pD3DDisassemble) {
        return E_FAIL;
    }

    if (ppPixelShader && !m_pD3DDev) {
        return E_FAIL;
    }

    LPCSTR pSelProfile = pProfile;
    if (!pSelProfile || *pSelProfile == '\0') {
        D3DCAPS9 caps;
        if (m_pD3DDev && m_pD3DDev->GetDeviceCaps(&caps) == D3D_OK) {
            switch (D3DSHADER_VERSION_MAJOR(caps.PixelShaderVersion)) {
                case 2:
                    if (caps.PS20Caps.NumInstructionSlots < 512) {
                        pSelProfile = "ps_2_0";
                    } else if (caps.PS20Caps.Caps > 0) {
                        pSelProfile = "ps_2_a";
                    } else {
                        pSelProfile = "ps_2_b";
                    }
                    break;
                case 3:
                    pSelProfile = "ps_3_0";
                    break;
            }
        } else {
            ASSERT(FALSE);
        }
    }

    if (!pSelProfile || *pSelProfile == '\0') {
        return E_FAIL;
    }

    LPCSTR defProfile = "MPC_HC_SHADER_PROFILE";
    LPCSTR defProfileVal;
    if (!strcmp(pSelProfile, "ps_2_0")) {
        defProfileVal = "0";
    } else if (!strcmp(pSelProfile, "ps_2_b")) {
        defProfileVal = "1";
    } else if (!strcmp(pSelProfile, "ps_2_a") || !strcmp(pSelProfile, "ps_2_sw")) {
        defProfileVal = "2";
    } else if (!strcmp(pSelProfile, "ps_3_0") || !strcmp(pSelProfile, "ps_3_sw")) {
        defProfileVal = "3";
    } else {
        defProfileVal = "-1";
    }
    D3D_SHADER_MACRO macros[] = { { defProfile, defProfileVal }, { 0 } };

    CComPtr<ID3DBlob> pShaderBlob, pErrorBlob;
    HRESULT hr = m_pD3DCompile(pSrcData, SrcDataSize, pSourceName, macros, nullptr, pEntrypoint,
                               pSelProfile, Flags, 0, &pShaderBlob, &pErrorBlob);

    if (pErrMsg) {
        CStringA msg;
        if (pErrorBlob) {
            auto len = pErrorBlob->GetBufferSize();
            VERIFY(memcpy_s(msg.GetBufferSetLength((int)len), len, pErrorBlob->GetBufferPointer(), len) == 0);
            msg.ReleaseBuffer((int)len);
        }
        *pErrMsg = msg;
    }

    if (FAILED(hr)) {
        return hr;
    }

    if (ppPixelShader) {
        hr = m_pD3DDev->CreatePixelShader((DWORD*)pShaderBlob->GetBufferPointer(), ppPixelShader);
        if (FAILED(hr)) {
            return hr;
        }
    }

    if (pDisasm) {
        CComPtr<ID3DBlob> pDisasmBlob;
        CStringA defs;
        for (auto pMacro = macros; pMacro && pMacro->Name && pMacro->Definition; pMacro++) {
            defs.Append("// #define ");
            defs.Append(pMacro->Name);
            defs.Append(" ");
            defs.Append(pMacro->Definition);
            defs.Append("\n");
        }
        hr = m_pD3DDisassemble(pShaderBlob->GetBufferPointer(), pShaderBlob->GetBufferSize(),
                               0, defs, &pDisasmBlob);
        if (SUCCEEDED(hr)) {
            CStringA disasm;
            auto len = pDisasmBlob->GetBufferSize();
            VERIFY(memcpy_s(disasm.GetBufferSetLength((int)len), len, pDisasmBlob->GetBufferPointer(), len) == 0);
            disasm.ReleaseBuffer((int)len);
            *pDisasm = disasm;
        }
    }

    return S_OK;
}
コード例 #14
0
HRESULT CAVIVideoPin::Deliver(IMediaSample *pSample)
{
     CComPtr<IMediaSample> pSampleDeliver = pSample;
    if (pSample->IsDiscontinuity() == S_OK)
    {
        if (m_seqHParser.isInited())
        {
             BYTE* pBuffer = NULL;
            pSample->GetPointer(&pBuffer);
            long len = pSample->GetActualDataLength();
            if (!m_seqHParser.ParseFrame(pBuffer, len))
            {
                // get it from the first sample
                const INDEXENTRY& entry = (*m_pIndex)[0];
                BYTE* pTempData = new BYTE[entry.dwChunkLength];
                 CAVIScanner* scanner = m_pSplitter->GetAVIScanner();
                scanner->ReadData(entry.chunkOffset, entry.dwChunkLength, pTempData); 
                BYTE* pDecoderConfig = NULL;
                int decoderConfigLen = 0;
                if (m_seqHParser.ParseFrame(pTempData, entry.dwChunkLength))
                {
                    decoderConfigLen = m_seqHParser.VisualObjSeq().obj_len+m_seqHParser.Pic_Parameter_Set().obj_len;
                    pDecoderConfig = new BYTE[decoderConfigLen];
                    memcpy(pDecoderConfig, m_seqHParser.VisualObjSeq().obj, m_seqHParser.VisualObjSeq().obj_len);
                    if (m_seqHParser.Pic_Parameter_Set().obj_len)
                        memcpy(pDecoderConfig+m_seqHParser.VisualObjSeq().obj_len, m_seqHParser.Pic_Parameter_Set().obj, m_seqHParser.Pic_Parameter_Set().obj_len);

                     long newsampleLen = decoderConfigLen+len;
                    CComPtr<IMediaSample> pNewSample;
                    HRESULT hr = GetNewSample(&pNewSample, newsampleLen);
                    ASSERT(hr == S_OK);
                    if (SUCCEEDED(hr))
                    {
                        CComPtr<IMediaSample2> pSmp = NULL;
                        pSample->QueryInterface(&pSmp);
                        AM_SAMPLE2_PROPERTIES props_in = {0};
                        hr = pSmp->GetProperties(sizeof( AM_SAMPLE2_PROPERTIES ), (BYTE*)&props_in);

                        CComPtr<IMediaSample2> pSmp2 = NULL;
                        pNewSample->QueryInterface(&pSmp2);

                        AM_SAMPLE2_PROPERTIES props_out = {0};
                        hr = pSmp2->GetProperties(sizeof( AM_SAMPLE2_PROPERTIES ), (BYTE*)&props_out);
                      
                      
                        props_out.dwTypeSpecificFlags = props_in.dwTypeSpecificFlags;
                        props_out.dwSampleFlags = props_in.dwSampleFlags;
                        props_out.lActual = decoderConfigLen+len;
                        props_out.tStart = props_in.tStart;
                        props_out.tStop = props_in.tStop;
                        props_out.dwStreamId = props_in.dwStreamId;
                        if (props_in.pMediaType)
                            props_out.pMediaType = CreateMediaType(props_in.pMediaType);

                        memcpy(props_out.pbBuffer, pDecoderConfig, decoderConfigLen);
                        memcpy(props_out.pbBuffer+decoderConfigLen, pBuffer, len);
                        hr = pSmp2->SetProperties(sizeof( AM_SAMPLE2_PROPERTIES ), (BYTE*)&props_out);
                        pSampleDeliver = pNewSample; 
                    }

                    delete pDecoderConfig;

                }
                delete pTempData;

            }

        }      
    }
    return CAVIOutputPin::Deliver(pSampleDeliver);
}
コード例 #15
0
ファイル: ExcelDnaLoader.cpp プロジェクト: namin/excel4vivi
bool XlLibraryInitialize(XlAddInExportInfo* pExportInfo)
{
	HRESULT hr;
	CComPtr<ICorRuntimeHost> pHost;

	hr = LoadClr20(&pHost);
	if (FAILED(hr) || pHost == NULL)
	{
		// LoadClr20 shows diagnostic MessageBoxes if needed.
		// Perhaps remember that we are not loaded?
		return 0;
	}

	// If all is fine now, also start the CLR (always safe to do again.
	hr = pHost->Start();
	if (FAILED(hr))
	{
		ShowMessage(IDS_MSG_HEADER_NEEDCLR20, 
					IDS_MSG_BODY_HOSTSTART,
					IDS_MSG_FOOTER_UNEXPECTED,
					hr);
		return 0;
	}

	CString addInFullPath = AddInFullPath();

	CPath xllDirectory(addInFullPath);
	xllDirectory.RemoveFileSpec();

	CComPtr<IUnknown> pAppDomainSetupUnk;
	hr = pHost->CreateDomainSetup(&pAppDomainSetupUnk);
	if (FAILED(hr) || pAppDomainSetupUnk == NULL)
	{
		ShowMessage(IDS_MSG_HEADER_APPDOMAIN, 
					IDS_MSG_BODY_APPDOMAINSETUP, 
					IDS_MSG_FOOTER_UNEXPECTED,
					hr);
		return 0;
	}

	CComQIPtr<IAppDomainSetup> pAppDomainSetup = pAppDomainSetupUnk;

	hr = pAppDomainSetup->put_ApplicationBase(CComBSTR(xllDirectory));
	if (FAILED(hr))
	{
		ShowMessage(IDS_MSG_HEADER_APPDOMAIN, 
					IDS_MSG_BODY_APPLICATIONBASE, 
					IDS_MSG_FOOTER_UNEXPECTED,
					hr);
		return 0;
	}
	
	CComBSTR configFileName = addInFullPath;
	configFileName.Append(L".config");
	pAppDomainSetup->put_ConfigurationFile(configFileName);

	CComBSTR appDomainName = L"ExcelDna: ";
	appDomainName.Append(addInFullPath);
	pAppDomainSetup->put_ApplicationName(appDomainName);

	IUnknown *pAppDomainUnk = NULL;
	hr = pHost->CreateDomainEx(appDomainName, pAppDomainSetupUnk, 0, &pAppDomainUnk);
	if (FAILED(hr) || pAppDomainUnk == NULL)
	{
		ShowMessage(IDS_MSG_HEADER_APPDOMAIN, 
					IDS_MSG_BODY_APPDOMAIN, 
					IDS_MSG_FOOTER_UNEXPECTED,
					hr);
		return 0;
	}

	CComQIPtr<_AppDomain> pAppDomain(pAppDomainUnk);

	// Load plan for ExcelDna.Loader:
	// Try AppDomain.Load with the name ExcelDna.Loader.
	// Then if it does not work, we will try to load from a known resource in the .xll.

	CComPtr<_Assembly> pExcelDnaLoaderAssembly;
	hr = pAppDomain->Load_2(CComBSTR(L"ExcelDna.Loader"), &pExcelDnaLoaderAssembly);
	if (FAILED(hr) || pExcelDnaLoaderAssembly == NULL)
	{
		HRSRC hResInfoLoader = FindResource(hModuleCurrent, L"EXCELDNA_LOADER", L"ASSEMBLY");
		if (hResInfoLoader == NULL)
		{
			ShowMessage(IDS_MSG_HEADER_APPDOMAIN, 
						IDS_MSG_BODY_MISSINGEXCELDNALOADER, 
						IDS_MSG_FOOTER_UNEXPECTED,
						hr);
			return 0;
		}
		HGLOBAL hLoader = LoadResource(hModuleCurrent, hResInfoLoader);
		void* pLoader = LockResource(hLoader);
		ULONG sizeLoader = (ULONG)SizeofResource(hModuleCurrent, hResInfoLoader);
		
		CComSafeArray<BYTE> bytesLoader;
		bytesLoader.Add(sizeLoader, (byte*)pLoader);

		hr = pAppDomain->Load_3(bytesLoader, &pExcelDnaLoaderAssembly);
		if (FAILED(hr))
		{
			ShowMessage(IDS_MSG_HEADER_APPDOMAIN, 
						IDS_MSG_BODY_EXCELDNALOADER, 
						IDS_MSG_FOOTER_UNEXPECTED,
						hr);
			return 0;
		}

		CComBSTR pFullName;
		hr = pExcelDnaLoaderAssembly->get_FullName(&pFullName);
		if (FAILED(hr))
		{
			ShowMessage(IDS_MSG_HEADER_APPDOMAIN, 
						IDS_MSG_BODY_EXCELDNALOADERNAME, 
						IDS_MSG_FOOTER_UNEXPECTED,
						hr);
			return 0;
		}
	}
	
	CComPtr<_Type> pXlAddInType;
	hr = pExcelDnaLoaderAssembly->GetType_2(CComBSTR(L"ExcelDna.Loader.XlAddIn"), &pXlAddInType);
	if (FAILED(hr) || pXlAddInType == NULL)
	{
		ShowMessage(IDS_MSG_HEADER_APPDOMAIN, 
					IDS_MSG_BODY_XLADDIN, 
					IDS_MSG_FOOTER_UNEXPECTED,
					hr);
		return 0;
	}

	CComSafeArray<VARIANT> initArgs;
	initArgs.Add(CComVariant((INT32)pExportInfo));
	initArgs.Add(CComVariant((INT32)hModuleCurrent));
	initArgs.Add(CComVariant(addInFullPath.AllocSysString()));
	CComVariant initRetVal;
	CComVariant target;
	hr = pXlAddInType->InvokeMember_3(CComBSTR("Initialize"), (BindingFlags)(BindingFlags_Static | BindingFlags_Public | BindingFlags_InvokeMethod), NULL, target, initArgs, &initRetVal);
	if (FAILED(hr))
	{
		ShowMessage(IDS_MSG_HEADER_APPDOMAIN, 
					IDS_MSG_BODY_XLADDININIT, 
					IDS_MSG_FOOTER_UNEXPECTED,
					hr);
		return 0;
	}

	pHost_ForUnload = pHost.Detach();
	pAppDomain_ForUnload = (IUnknown*)pAppDomain.Detach();

	return initRetVal.boolVal == 0 ? false : true;
}
コード例 #16
0
ファイル: VideoDecoder.cpp プロジェクト: WuChengLin/gecko-dev
HRESULT
VideoDecoder::SampleToVideoFrame(IMFSample* aSample,
                                 int32_t aWidth,
                                 int32_t aHeight,
                                 int32_t aStride,
                                 GMPVideoi420Frame* aVideoFrame)
{
  ENSURE(aSample != nullptr, E_POINTER);
  ENSURE(aVideoFrame != nullptr, E_POINTER);

  HRESULT hr;
  CComPtr<IMFMediaBuffer> mediaBuffer;

  // Must convert to contiguous mediaBuffer to use IMD2DBuffer interface.
  hr = aSample->ConvertToContiguousBuffer(&mediaBuffer);
  ENSURE(SUCCEEDED(hr), hr);

  // Try and use the IMF2DBuffer interface if available, otherwise fallback
  // to the IMFMediaBuffer interface. Apparently IMF2DBuffer is more efficient,
  // but only some systems (Windows 8?) support it.
  BYTE* data = nullptr;
  LONG stride = 0;
  CComPtr<IMF2DBuffer> twoDBuffer;
  hr = mediaBuffer->QueryInterface(static_cast<IMF2DBuffer**>(&twoDBuffer));
  if (SUCCEEDED(hr)) {
    hr = twoDBuffer->Lock2D(&data, &stride);
    ENSURE(SUCCEEDED(hr), hr);
  } else {
    hr = mediaBuffer->Lock(&data, NULL, NULL);
    ENSURE(SUCCEEDED(hr), hr);
    stride = aStride;
  }

  // The V and U planes are stored 16-row-aligned, so we need to add padding
  // to the row heights to ensure the Y'CbCr planes are referenced properly.
  // YV12, planar format: [YYYY....][VVVV....][UUUU....]
  // i.e., Y, then V, then U.
  uint32_t padding = 0;
  if (aHeight % 16 != 0) {
    padding = 16 - (aHeight % 16);
  }
  int32_t y_size = stride * (aHeight + padding);
  int32_t v_size = stride * (aHeight + padding) / 4;
  int32_t halfStride = (stride + 1) / 2;
  int32_t halfHeight = (aHeight + 1) / 2;

  auto err = aVideoFrame->CreateEmptyFrame(stride, aHeight, stride, halfStride, halfStride);
  ENSURE(GMP_SUCCEEDED(err), E_FAIL);

  err = aVideoFrame->SetWidth(aWidth);
  ENSURE(GMP_SUCCEEDED(err), E_FAIL);
  err = aVideoFrame->SetHeight(aHeight);
  ENSURE(GMP_SUCCEEDED(err), E_FAIL);

  uint8_t* outBuffer = aVideoFrame->Buffer(kGMPYPlane);
  ENSURE(outBuffer != nullptr, E_FAIL);
  assert(aVideoFrame->AllocatedSize(kGMPYPlane) >= stride*aHeight);
  memcpy(outBuffer, data, stride*aHeight);

  outBuffer = aVideoFrame->Buffer(kGMPUPlane);
  ENSURE(outBuffer != nullptr, E_FAIL);
  assert(aVideoFrame->AllocatedSize(kGMPUPlane) >= halfStride*halfHeight);
  memcpy(outBuffer, data+y_size, halfStride*halfHeight);

  outBuffer = aVideoFrame->Buffer(kGMPVPlane);
  ENSURE(outBuffer != nullptr, E_FAIL);
  assert(aVideoFrame->AllocatedSize(kGMPVPlane) >= halfStride*halfHeight);
  memcpy(outBuffer, data + y_size + v_size, halfStride*halfHeight);

  if (twoDBuffer) {
    twoDBuffer->Unlock2D();
  } else {
    mediaBuffer->Unlock();
  }

  LONGLONG hns = 0;
  hr = aSample->GetSampleTime(&hns);
  ENSURE(SUCCEEDED(hr), hr);
  aVideoFrame->SetTimestamp(HNsToUsecs(hns));

  hr = aSample->GetSampleDuration(&hns);
  ENSURE(SUCCEEDED(hr), hr);
  aVideoFrame->SetDuration(HNsToUsecs(hns));

  return S_OK;
}
コード例 #17
0
DWORD CAVIOutputPin::ThreadProc()
{
    CAVIScanner* scanner = m_pSplitter->GetAVIScanner();
    bool bFirst = true;
    REFERENCE_TIME tStart = 0;
    REFERENCE_TIME tStop = 0;
    REFERENCE_TIME duration = 0;
    bool bDeliverEOS = true;
    DWORD req = 0;
    HRESULT hr = S_OK;
    REFERENCE_TIME tSeekStart = 0;
    REFERENCE_TIME tSeekStop = 0;

     double dRate;
    m_pSplitter->GetSeekingParams(&tSeekStart, &tSeekStop, &dRate);
    DeliverNewSegment(tSeekStart, tSeekStop, dRate);
    int startPos = GetIndexStartPosEntry(tSeekStart);
    for (int i = startPos; i < m_pIndex->size(); i++)
    {
        const INDEXENTRY& entry = (*m_pIndex)[i];
        if (!entry.dwChunkLength)
            continue;
        CComPtr<IMediaSample> pSample;
        hr = GetNewSample(&pSample, entry.dwChunkLength);
        
        // Break out without calling EndOfStream if we're asked to
	    // do something different
	    if (CheckRequest(&req)) 
        {
            bDeliverEOS = false;          
            break;
        }


        if (bFirst)
        {
            bFirst = false;
            pSample->SetDiscontinuity(TRUE);
           

        }
        if (entry.dwFlags & AVIIF_INDEX)
            pSample->SetSyncPoint(TRUE);
        tStart = GetCurTime(i) - tSeekStart;
        tStop = GetCurTime(i+1)- tSeekStart;
       
        pSample->SetTime(&tStart,&tStop);
        if (tStart < 0 && tStop <= 0)
            pSample->SetPreroll(TRUE);

        BYTE* pbData = 0;
        pSample->GetPointer(&pbData);
        scanner->ReadData(entry.chunkOffset, entry.dwChunkLength, pbData);   
        hr = Deliver(pSample);
        if (FAILED(hr) || hr == S_FALSE)
        {
            while(true)
            {
                if (CheckRequest(&req)) 
                {
                    bDeliverEOS = false;          
                    break;
                }
                Sleep(100);
            }           
        }
    }
    if (bDeliverEOS)
        DeliverEndOfStream();

    req =GetRequest();
    Reply(S_OK);
    return 0;
}
コード例 #18
0
HRESULT AudioDeviceService::SetDefaultAudioDevice(LPWSTR deviceId)
{
    CComPtr<IPolicyConfig> policyConfig;
    FAST_FAIL(CoCreateInstance(__uuidof(CPolicyConfigClient), nullptr, CLSCTX_INPROC, IID_PPV_ARGS(&policyConfig)));
    return policyConfig->SetDefaultEndpoint(deviceId, ERole::eMultimedia);
}
コード例 #19
0
LRESULT CEditGradientDlg::OnLButtonDown(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
// Create default gradient
	if (m_viewGroup)
	{
		CComPtr<IEXMLDocument> eXMLDocument;
		m_viewGroup->get_eXMLDocument(&eXMLDocument);

		CComQIPtr<IEDocument> eDocument = eXMLDocument;

		CComPtr<ILDOMDocument> document;
		eXMLDocument->get_DOMDocument(&document);

//		CSVGFilterOptionsDlg dlg;
//		dlg.m_document = document;

//		if (dlg.DoModal(GetMainHwnd()) == IDOK)
		{
			CComPtr<IOleUndoManager> undoManager;
			eDocument->get_undoManager(&undoManager);

			CComObject<CUndoParent>* pParentUndo;
			CComObject<CUndoParent>::CreateInstance(&pParentUndo);
			if (pParentUndo)
			{
				pParentUndo->AddRef();	// ???
				undoManager->Open(pParentUndo);

				CComPtr<ILSVGElement> svgDefsElement;
				eXMLDocument->FindOrCreateSVGDefs(&svgDefsElement);

				if (svgDefsElement)
				{
					CComPtr<ILSVGElement> svgElement;
					document->createElementNS(L"http://www.w3.org/2000/svg", L"linearGradient", (ILDOMElement**)&svgElement);

					if (svgElement)
					{
						// TODO, create unique ID

						CComBSTR id = L"gradient";

						svgElement->setAttribute(L"id", id);
						svgElement->setAttribute(L"gradientUnits", L"userSpaceOnUse");
						svgElement->setAttribute(L"x1", L"0%");
						svgElement->setAttribute(L"y1", L"0%");
						svgElement->setAttribute(L"x2", L"100%");
						svgElement->setAttribute(L"y2", L"0%");

						// black
						{
							CComPtr<ILDOMElement> stop;
							document->createElementNS(L"http://www.w3.org/2000/svg", L"stop", &stop);
							stop->setAttribute(L"offset", L"0");
							stop->setAttribute(L"style", L"stop-color:#000000");

							svgElement->appendChild(stop, NULL);
						}

						// white
						{
							CComPtr<ILDOMElement> stop;
							document->createElementNS(L"http://www.w3.org/2000/svg", L"stop", &stop);
							stop->setAttribute(L"offset", L"1");
							stop->setAttribute(L"style", L"stop-color:#ffffff");

							svgElement->appendChild(stop, NULL);
						}

						CComObject<CWEUndoNewElement>* pUndo;
						CComObject<CWEUndoNewElement>::CreateInstance(&pUndo);
						if (pUndo)
						{
						//	pUndo->AddRef();
							pUndo->m_pDocument = static_cast<CEXMLDocument*>(eXMLDocument.p);

							pUndo->DoInitial(undoManager, svgElement, svgDefsElement, NULL);

							// TODO: do this here?
							CComPtr<IEXMLViewGroup> viewGroup;
							eXMLDocument->GetActiveViewGroup(&viewGroup);
							if (viewGroup)
							{
								//CWebXMLViewGroup* pViewGroup = static_cast<CWebXMLViewGroup*>(viewGroup.p);

								CComPtr<IEElement> pElement;
								eXMLDocument->GetEElementFromDOMElement(svgElement, &pElement);

								CComBSTR gradient;
								gradient = L"url(#";
								gradient += id;
								gradient += L")";

								if (SelectionCanHavePaint(viewGroup))
								{
#if 0
									CComPtr<ILCSSStyleDeclaration> style;
									viewGroup->GetCurrentSelectionCSSStyle(&style);
#endif

									ATLASSERT(0);
#if 0
									style->setProperty(gApp->m_strokeOrFill == 0? L"stroke": L"fill", gradient, NULL);
#endif

#if 0
									viewGroup->ApplyCurrentSelectionCSSStyle();
#endif
								}

							//
								static_cast<CEXMLDocument*>(eXMLDocument.p)->m_lastGradient = gradient;
							//

								viewGroup->ActivateElement(pElement, 0, NULL);
							}
						}
					}
				}

				undoManager->Close(pParentUndo, TRUE/*commit*/);
			}
		}
	}

	return 0;
}
コード例 #20
0
ファイル: Browser.cpp プロジェクト: Hemkumar/selenium
bool Browser::IsDocumentNavigating(IHTMLDocument2* doc) {
	bool is_navigating = true;
	// Starting WaitForDocumentComplete()
	is_navigating = this->is_navigation_started_;
	CComBSTR ready_state;
	HRESULT hr = doc->get_readyState(&ready_state);
	if (FAILED(hr) || is_navigating || _wcsicmp(ready_state, L"complete") != 0) {
		//std::cout << "readyState is not complete\r\n";
		return true;
	} else {
		is_navigating = false;
	}

	// document.readyState == complete
	is_navigating = this->is_navigation_started_;
	CComPtr<IHTMLFramesCollection2> frames;
	hr = doc->get_frames(&frames);
	if (is_navigating || FAILED(hr)) {
		//std::cout << "could not get frames\r\n";
		return true;
	}

	if (frames != NULL) {
		long frame_count = 0;
		hr = frames->get_length(&frame_count);

		CComVariant index;
		index.vt = VT_I4;
		for (long i = 0; i < frame_count; ++i) {
			// Waiting on each frame
			index.lVal = i;
			CComVariant result;
			hr = frames->item(&index, &result);
			if (FAILED(hr)) {
				return true;
			}

			CComQIPtr<IHTMLWindow2> window(result.pdispVal);
			if (!window) {
				// Frame is not an HTML frame.
				continue;
			}

			CComPtr<IHTMLDocument2> frame_document;
			bool is_valid_frame_document = this->GetDocumentFromWindow(window, &frame_document);

			is_navigating = this->is_navigation_started_;
			if (is_navigating) {
				break;
			}

			// Recursively call to wait for the frame document to complete
			if (is_valid_frame_document) {
				is_navigating = this->IsDocumentNavigating(frame_document);
				if (is_navigating) {
					break;
			}
			}
		}
	}
	return is_navigating;
}
コード例 #21
0
STDMETHODIMP CNativeRibbonApp::UpdateProperty(UINT32 commandId, REFPROPERTYKEY key, const PROPVARIANT* /*currentValue*/, PROPVARIANT* newValue)
{
	if (key == UI_PKEY_TooltipTitle)
	{
		CString str;
		if (!str.LoadString(commandId))
			return S_FALSE;

		int nIndex = str.Find(L'\n');
		if (nIndex <= 0)
			return S_FALSE;

		str = str.Mid(nIndex + 1);

		CString strLabel;

		if (m_pFrame != NULL && (CKeyboardManager::FindDefaultAccelerator(commandId, strLabel, m_pFrame, TRUE) ||
			CKeyboardManager::FindDefaultAccelerator(commandId, strLabel, m_pFrame->GetActiveFrame(), FALSE)))
		{
			str += _T(" (");
			str += strLabel;
			str += _T(')');
		}

		return UIInitPropertyFromString(UI_PKEY_TooltipTitle, str, newValue);
	}
	else if (key == UI_PKEY_TooltipDescription)
	{
		CString str;
		if (!str.LoadString(commandId))
			return S_FALSE;

		int nIndex = str.Find(L'\n');
		if (nIndex <= 0)
			return S_FALSE;

		str = str.Left(nIndex);

		return UIInitPropertyFromString(UI_PKEY_TooltipDescription, str, newValue);
	}
	else if (key == UI_PKEY_Enabled)
	{
		CRibbonCmdUI ui(commandId);
		ui.DoUpdate(m_pFrame, TRUE);

		return UIInitPropertyFromBoolean(UI_PKEY_Enabled, ui.m_bOn, newValue);
	}
	else if (key == UI_PKEY_BooleanValue)
	{
		CRibbonCmdUI ui(commandId);
		ui.DoUpdate(m_pFrame, TRUE);

		return UIInitPropertyFromBoolean(UI_PKEY_BooleanValue, ui.m_nCheck, newValue);
	}
	else if (key == UI_PKEY_SelectedItem)
	{
		CComPtr<IUICollection> items = GetUICommandItemsSource(commandId);
		if (!items)
			return E_FAIL;

		UINT32 count;
		items->GetCount(&count);
		for (UINT32 idx = 0; idx < count; idx++)
		{
			CComPtr<IUnknown> item;
			items->GetItem(idx, &item);

			CComQIPtr<IUISimplePropertySet> simplePropertySet(item);
			if (simplePropertySet)
			{
				PROPVARIANT var = { 0 };
				UINT32 uiVal;
				simplePropertySet->GetValue(UI_PKEY_CommandId, &var);
				UIPropertyToUInt32(UI_PKEY_CommandId, var, &uiVal);

				CRibbonCmdUI ui(uiVal);
				ui.DoUpdate(m_pFrame, TRUE);

				if (ui.m_nCheck)
				{
					UIInitPropertyFromUInt32(UI_PKEY_SelectedItem, idx, newValue);
					return S_OK;
				}
			}
		}

		// No selected item.
		UIInitPropertyFromUInt32(UI_PKEY_SelectedItem, static_cast<UINT>(-1), newValue);

		return S_OK;
	}

	return E_NOTIMPL;
}
コード例 #22
0
ファイル: useful.cpp プロジェクト: DrJWCain/DIA-SDK
std::wstring locationType(CComPtr<IDiaSymbol> sym)
{
  DWORD loc;
  checkResult(sym->get_locationType(&loc));
  return szLocationTypes[loc];
}
コード例 #23
0
ファイル: useful.cpp プロジェクト: DrJWCain/DIA-SDK
std::wstring expandType(CComPtr<IDiaSymbol> type, const std::wstring& name)
{
  std::wstring ret;
  if(!type)
  {
    return ret;
  }

  BOOL vol;
  checkResult(type->get_volatileType(&vol));
  if(vol)
  {
    ret += L"volatile ";
  }
  BOOL con;
  checkResult(type->get_constType(&con));
  if(con)
  {
    ret += L"const ";
  }

  DWORD tag;
  checkResult(type->get_symTag(&tag));
  if(SymTagBaseType == tag)
  {
    DWORD baseType;
    checkResult(type->get_baseType(&baseType));
    ret += getBasicTypeString(baseType);
    return ret;
  }
  if(SymTagPointerType == tag)
  {
    CComPtr<IDiaSymbol> pointee;
    checkResult(type->get_type(&pointee));

    DWORD pointeeTag;
    checkResult(pointee->get_symTag(&pointeeTag));
    if(SymTagFunctionType == pointeeTag)//function pointer!
    {
      CComPtr<IDiaSymbol> returnType;
      checkResult(pointee->get_type(&returnType));
      ret += expandType(returnType);

      ret += L" (*" + name + L")(";

      CComPtr<IDiaEnumSymbols> pIDiaEnumSymbols;
      checkResult(pointee->findChildren(SymTagFunctionArgType, NULL,
        nsNone,&pIDiaEnumSymbols));

      if(!!pIDiaEnumSymbols)
      {
        LONG count;
        checkResult(pIDiaEnumSymbols->get_Count(&count));
        for(int i = 0; i < count; ++i)
        {
          if(i)ret += L", ";
          CComPtr<IDiaSymbol> pIDiaSymbol;
          checkResult(pIDiaEnumSymbols->Item(i,&pIDiaSymbol));

          CComPtr<IDiaSymbol> funcArg;
          checkResult(pIDiaSymbol->get_type(&funcArg));
          ret += expandType(funcArg);
        }
      }
      ret += L")";
      return ret;
    }

    ret += expandType(pointee);

    BOOL ref;
    checkResult(type->get_reference(&ref));
    if(ref)
    {
      ret += L"&";
    }
    else
    {
      ret += L"*";
    }

    return ret;
  }
  else if(SymTagArrayType == tag)
  {
    CComPtr<IDiaSymbol> arrayBase;
    checkResult(type->get_type(&arrayBase));

    ULONGLONG total;
    checkResult(type->get_length(&total));

    ULONGLONG len;
    checkResult(arrayBase->get_length(&len));

    ret += expandType(arrayBase);
    ret += L"[" + toString((int)(total/len)) + L"]";//sometimes seems to be inaccurate

    return ret;
  }
  else if(SymTagUDT == tag)
  {
    UDT udt(type);
    ret = udt.getKind() + L" " + udt.getName();
    return ret;
  }
  else if(SymTagEnum == tag)
  {
    ret = L"enum " + getName(type);
    return ret;
  }
  else 
  {
    __asm int 3;//JC to do
  }

  return getName(type);
}
コード例 #24
0
ファイル: useful.cpp プロジェクト: DrJWCain/DIA-SDK
std::wstring dataKind(CComPtr<IDiaSymbol> sym)
{
  DWORD kind;
  checkResult(sym->get_dataKind(&kind));
  return szDataKinds[kind];
}
コード例 #25
0
HRESULT CMpeg2DataParser::ParseSDT(ULONG ulFreq)
{
    HRESULT hr;
    CComPtr<ISectionList> pSectionList;
    DWORD dwLength;
    PSECTION data;
    WORD wTSID;
    WORD wONID;
    WORD wSectionLength;

    CheckNoLog(m_pData->GetSection(PID_SDT, SI_SDT, &m_Filter, 5000, &pSectionList));
    CheckNoLog(pSectionList->GetSectionData(0, &dwLength, &data));

    CGolombBuffer gb((BYTE*)data, dwLength);

    // service_description_section()
    CheckNoLog(ParseSIHeader(gb, SI_SDT, wSectionLength, wTSID));

    wONID = (WORD)gb.BitRead(16);                               // original_network_id
    gb.BitRead(8);                                              // reserved_future_use

    while (gb.GetSize() - gb.GetPos() > 4) {
        CDVBChannel Channel;
        Channel.SetFrequency(ulFreq);
        Channel.SetTSID(wTSID);
        Channel.SetONID(wONID);
        Channel.SetSID((ULONG)gb.BitRead(16));                  // service_id   uimsbf
        gb.BitRead(6);                                          // reserved_future_use   bslbf
        gb.BitRead(1);                                          // EIT_schedule_flag   bslbf
        Channel.SetNowNextFlag(!!gb.BitRead(1));                // EIT_present_following_flag   bslbf
        gb.BitRead(3);                                          // running_status   uimsbf
        Channel.SetEncrypted(!!gb.BitRead(1));                  // free_CA_mode   bslbf

        // Descriptors:
        BeginEnumDescriptors(gb, nType, nLength) {
            switch (nType) {
                case DT_SERVICE:
                    gb.BitRead(8);                              // service_type
                    nLength = (WORD)gb.BitRead(8);              // service_provider_name_length
                    gb.ReadBuffer(DescBuffer, nLength);         // service_provider_name

                    nLength = (WORD)gb.BitRead(8);              // service_name_length
                    gb.ReadBuffer(DescBuffer, nLength);         // service_name
                    DescBuffer[nLength] = 0;
                    Channel.SetName(ConvertString(DescBuffer, nLength));
                    TRACE(_T("%15S %d\n"), Channel.GetName(), Channel.GetSID());
                    break;
                default:
                    SkipDescriptor(gb, nType, nLength);         // descriptor()
                    break;
            }
        }
        EndEnumDescriptors;


        if (!Channels.Lookup(Channel.GetSID())) {
            Channels [Channel.GetSID()] = Channel;
        }
    }

    return S_OK;
}
コード例 #26
0
ファイル: NNTP.cpp プロジェクト: China-ls/virtuoso-opensource
HRESULT CNNTP::OnPost(IMessage * Msg, CdoEventStatus * EventStatus)
{
    HRESULT res;
    RETCODE rc;
    long global_read = 0;
    int to_inx = 0;
    SDWORD cbRet = SQL_DATA_AT_EXEC;
    if (EventStatus == NULL)
	return E_POINTER;

//    _Module.LogEvent ("Message");
    CComBSTR bStrTo, bStrBody, bStrFrom, bStrSubj, bStrCC, bStrBCC, bStrSentDate;
    CComPtr<_Stream> st;
    VARIANT sent_date;
    ::VariantInit (&sent_date);
    sent_date.vt = VT_DATE;

//    _Module.LogEvent ("After Subj");
    if (S_OK != (res = Msg->GetStream (&st)))
        return res;

//    _Module.LogEvent ("After Stream");

    CDBConnection *conn = _ppool->getConnection();
//    _Module.LogEvent ("After conn");
//    _Module.LogEvent ("From: %s, To: %s, CC: %s, BCC: %s, Subject: %s, SentOn :%s", 
//	szStrFrom, szStrTo, szStrCC, szStrBCC, szStrSubj, szStrSent);
    HSTMT hstmt = SQL_NULL_HSTMT;
    try 
    {
	int read, reconnect_count = 0;
	char szBuffer[4096];
again:
	hstmt = SQL_NULL_HSTMT;
	if (SQL_SUCCESS != SQLAllocStmt (conn->hdbc, &hstmt)) 
	    throw _T("SQLAllocStmt error");

//	SQLSetStmtOption (conn->hstmt, SQL_QUERY_TIMEOUT, 10);
	SQLSetParam (hstmt, 1, SQL_C_CHAR, SQL_LONGVARCHAR, 0, 0, (SQLPOINTER)2, &cbRet);
//        _Module.LogEvent ("After setparam");
	rc = SQLExecDirect (hstmt, (SQLCHAR *)"NS_POST (?)", SQL_NTS);
	if (rc != SQL_NEED_DATA && !reconnect_count)
	{
	    conn->ReportODBCError (hstmt, "Retry SQLExec error");
	    SQLFreeStmt (hstmt, SQL_DROP);
	    hstmt = SQL_NULL_HSTMT;
	    _Module.LogEvent ("Reconnecting ...");
	    reconnect_count = 1;
	    delete conn;
	    conn = new CDBConnection ();
	    goto again;
	}
	else if (rc != SQL_NEED_DATA)
	{
	    throw _T("SQLExec Error");
	}


  //      _Module.LogEvent ("After Exec");
	rc = SQLParamData (hstmt, NULL);
	if (rc != SQL_NEED_DATA)
	    throw _T("SQLParamData error");
//        _Module.LogEvent ("After ParamData");
	while (1) 
	{
	    st->ReadText (4096, &bStrBody);
	    read = wcslen (bStrBody);
	    global_read += read;
//	    _Module.LogEvent ("After ReadText");
	    if (!read)
		break;
	    ::WideCharToMultiByte (CP_ACP, 0, bStrBody, -1, szBuffer, sizeof (szBuffer), NULL, NULL);
	    rc = SQLPutData (hstmt, szBuffer, SQL_NTS);
//	    _Module.LogEvent ("After PutData");
	    if (rc != SQL_SUCCESS)
		throw _T("SQLPutData error");
	}
	rc = SQLParamData (hstmt, NULL);
//	_Module.LogEvent ("After ParamData");
	if (rc != SQL_SUCCESS)
	    throw _T("SQLParamData error");
	SQLFreeStmt (hstmt, SQL_DROP);
//	SQLFreeStmt (conn->hstmt, SQL_RESET_PARAMS);
	_Module.LogEvent ("NNTP Message (%ld chars) routed", global_read);
    }
    catch (TCHAR *ch)
    {
	conn->ReportODBCError (hstmt, ch);
	SQLFreeStmt (hstmt, SQL_DROP);
//	SQLFreeStmt (conn->hstmt, SQL_RESET_PARAMS);
	_ppool->releaseConnection(conn);
	return E_POINTER;
    }
    _ppool->releaseConnection(conn);
    return S_OK;
}
コード例 #27
0
STDMETHODIMP CVMR9AllocatorPresenter::PresentImage(DWORD_PTR dwUserID, VMR9PresentationInfo* lpPresInfo)
{
	SetThreadName((DWORD)-1, "CVMR9AllocatorPresenter");
	CheckPointer(m_pIVMRSurfAllocNotify, E_UNEXPECTED);

	if (m_rtTimePerFrame == 0 || m_bNeedCheckSample) {
		m_bNeedCheckSample		= false;
		CComPtr<IBaseFilter>	pVMR9;
		CComPtr<IPin>			pPin;
		CMediaType				mt;

		if (SUCCEEDED (m_pIVMRSurfAllocNotify->QueryInterface (__uuidof(IBaseFilter), (void**)&pVMR9)) &&
				SUCCEEDED (pVMR9->FindPin(L"VMR Input0", &pPin)) &&
				SUCCEEDED (pPin->ConnectionMediaType(&mt)) ) {
			ExtractAvgTimePerFrame (&mt, m_rtTimePerFrame);

			CSize NativeVideoSize = m_NativeVideoSize;
			CSize AspectRatio = m_AspectRatio;
			if (mt.formattype==FORMAT_VideoInfo || mt.formattype==FORMAT_MPEGVideo) {
				VIDEOINFOHEADER *vh = (VIDEOINFOHEADER*)mt.pbFormat;

				NativeVideoSize = CSize(vh->bmiHeader.biWidth, abs(vh->bmiHeader.biHeight));
				if (vh->rcTarget.right - vh->rcTarget.left > 0) {
					NativeVideoSize.cx = vh->rcTarget.right - vh->rcTarget.left;
				} else if (vh->rcSource.right - vh->rcSource.left > 0) {
					NativeVideoSize.cx = vh->rcSource.right - vh->rcSource.left;
				}

				if (vh->rcTarget.bottom - vh->rcTarget.top > 0) {
					NativeVideoSize.cy = vh->rcTarget.bottom - vh->rcTarget.top;
				} else if (vh->rcSource.bottom - vh->rcSource.top > 0) {
					NativeVideoSize.cy = vh->rcSource.bottom - vh->rcSource.top;
				}
			} else if (mt.formattype==FORMAT_VideoInfo2 || mt.formattype==FORMAT_MPEG2Video) {
				VIDEOINFOHEADER2 *vh = (VIDEOINFOHEADER2*)mt.pbFormat;

				if (vh->dwPictAspectRatioX && vh->dwPictAspectRatioY) {
					AspectRatio = CSize(vh->dwPictAspectRatioX, vh->dwPictAspectRatioY);
				}

				NativeVideoSize = CSize(vh->bmiHeader.biWidth, abs(vh->bmiHeader.biHeight));
				if (vh->rcTarget.right - vh->rcTarget.left > 0) {
					NativeVideoSize.cx = vh->rcTarget.right - vh->rcTarget.left;
				} else if (vh->rcSource.right - vh->rcSource.left > 0) {
					NativeVideoSize.cx = vh->rcSource.right - vh->rcSource.left;
				}

				if (vh->rcTarget.bottom - vh->rcTarget.top > 0) {
					NativeVideoSize.cy = vh->rcTarget.bottom - vh->rcTarget.top;
				} else if (vh->rcSource.bottom - vh->rcSource.top > 0) {
					NativeVideoSize.cy = vh->rcSource.bottom - vh->rcSource.top;
				}
			}
			if (m_NativeVideoSize != NativeVideoSize || m_AspectRatio != AspectRatio) {
				m_NativeVideoSize = NativeVideoSize;
				m_AspectRatio = AspectRatio;
				AfxGetApp()->m_pMainWnd->PostMessage(WM_REARRANGERENDERLESS);
			}
		}
		// If framerate not set by Video Decoder choose 23.97...
		if (m_rtTimePerFrame == 0) {
			m_rtTimePerFrame = 417166;
		}

		m_fps = 10000000.0 / m_rtTimePerFrame;
	}

	HRESULT hr;

	if (!lpPresInfo || !lpPresInfo->lpSurf) {
		return E_POINTER;
	}

	CAutoLock cAutoLock(this);
	CAutoLock cRenderLock(&m_RenderLock);

	if (lpPresInfo->rtEnd > lpPresInfo->rtStart) {
		if (m_pSubPicQueue) {
			m_pSubPicQueue->SetFPS(m_fps);

			if (m_fUseInternalTimer && !g_bExternalSubtitleTime) {
				__super::SetTime(g_tSegmentStart + g_tSampleStart);
			}
		}
	}

	CSize VideoSize = GetVisibleVideoSize();
	int arx = lpPresInfo->szAspectRatio.cx;
	int ary = lpPresInfo->szAspectRatio.cy;
	if (arx > 0 && ary > 0) {
		arx = arx / ((float) m_NativeVideoSize.cx / VideoSize.cx);
		ary = ary / ((float) m_NativeVideoSize.cy / VideoSize.cy);
		VideoSize.cx = VideoSize.cy*arx/ary;
	}
	if (VideoSize != GetVideoSize()) {
		m_AspectRatio.SetSize(arx, ary);
		AfxGetApp()->m_pMainWnd->PostMessage(WM_REARRANGERENDERLESS);
	}

	if (!m_bPendingResetDevice) {
		CComPtr<IDirect3DTexture9> pTexture;
		lpPresInfo->lpSurf->GetContainer(IID_IDirect3DTexture9, (void**)&pTexture);

		if (pTexture) {
			m_pVideoSurface[m_nCurSurface] = lpPresInfo->lpSurf;
			if (m_pVideoTexture[m_nCurSurface]) {
				m_pVideoTexture[m_nCurSurface] = pTexture;
			}
		} else {
			hr = m_pD3DDev->StretchRect(lpPresInfo->lpSurf, NULL, m_pVideoSurface[m_nCurSurface], NULL, D3DTEXF_NONE);
		}

		// Tear test bars
		if (GetRenderersData()->m_fTearingTest) {
			RECT		rcTearing;

			rcTearing.left		= m_nTearingPos;
			rcTearing.top		= 0;
			rcTearing.right		= rcTearing.left + 4;
			rcTearing.bottom	= m_NativeVideoSize.cy;
			m_pD3DDev->ColorFill (m_pVideoSurface[m_nCurSurface], &rcTearing, D3DCOLOR_ARGB (255,255,0,0));

			rcTearing.left	= (rcTearing.right + 15) % m_NativeVideoSize.cx;
			rcTearing.right	= rcTearing.left + 4;
			m_pD3DDev->ColorFill (m_pVideoSurface[m_nCurSurface], &rcTearing, D3DCOLOR_ARGB (255,255,0,0));

			m_nTearingPos = (m_nTearingPos + 7) % m_NativeVideoSize.cx;
		}
	}

	Paint(true);

	return S_OK;
}
コード例 #28
0
void __stdcall CEditGradientDlg::OnViewGroupSelectionChanged()
{
	/*
	CComPtr<IWebXMLDocument> eDocument;
	m_viewGroup->get_document(&eDocument);

	_bstr_t defaultGradient = static_cast<CEXMLDocument*>(eDocument.p)->m_defaultGradient;
	if (defaultGradient.length() && wcscmp(defaultGradient, L"none"))
	{
		_bstr_t url = ExtractUrl(defaultGradient);

		BSTR uri = &((BSTR)url)[1];

		CComPtr<ILDOMDocument> xmldocument;
		eDocument->get_DOMDocument(&xmldocument);

		CComPtr<ILDOMElement> uriElement;
		xmldocument->getElementById(uri, &uriElement);
		if (uriElement)
		{
			// TODO check if linearGradient or radialGradient

			m_GradCtl->SetSVGElement(uriElement);

			{
				CComPtr<ILCSSStyleDeclaration> style;
				m_viewGroup->GetCurrentSelectionCSSStyle(&style);

				CComPtr<ILSVGPaint> paint;
				style->getPropertyCSSValue((gApp->m_strokeOrFill==0)? L"stroke": L"fill", (ILCSSValue**)&paint);

				if (paint)
				{
					CComBSTR cssTextPaint;
					paint->get_cssText(&cssTextPaint);

					if (!wcscmp(defaultGradient, cssTextPaint))
					{
						m_GradCtl->put_canEditStops(VARIANT_TRUE);
					}
					else
					{
						m_GradCtl->put_canEditStops(VARIANT_FALSE);
					}
				}
				else
				{
					m_GradCtl->put_canEditStops(VARIANT_FALSE);
				}
			}
		}
		else
		{
			m_GradCtl->SetSVGElement(NULL);
		}
	}
	*/

	CComPtr<IESelectedElement> selectedElement;
	m_viewGroup->GetActiveSelectedElement(&selectedElement);
	if (selectedElement)
	{
		CComPtr<IEElement> element;
		selectedElement->get_eElement(&element);

		CComPtr<ILDOMElement> domElement;
		element->get_domElement(&domElement);

		m_GradCtl->SetSVGElement(domElement);
	}
}
コード例 #29
0
ファイル: Device.cpp プロジェクト: Realhram/wdk81
/////////////////////////////////////////////////////////////////////////
//
//  CMyDevice::Initialize
//
//  This method initializes the device callback object and creates the
//  partner device object.
//
//  Parameters:
//      pDriver     - pointer to an IWDFDriver interface
//      pDeviceInit - pointer to an interface used to intialize the device
//
//  Return Values:
//      status
//
/////////////////////////////////////////////////////////////////////////
HRESULT CMyDevice::Initialize(
    _In_  IWDFDriver*              pDriver,
    _In_  IWDFDeviceInitialize*    pDeviceInit
    )
{
    FuncEntry();
    
    CComPtr<IUnknown> spCallback;
    CComPtr<IWDFDevice> spIWDFDevice;
    CComPtr<IWDFDevice3> spIWDFDevice3;
    HRESULT hr;
    
    // Prepare device parameters
    pDeviceInit->SetLockingConstraint(None); 
    pDeviceInit->SetPowerPolicyOwnership(TRUE);

    hr = QueryInterface(IID_PPV_ARGS(&spCallback));

    if (SUCCEEDED(hr))
    {
        // Create the IWDFDevice object
        hr = pDriver->CreateDevice(pDeviceInit, spCallback, &spIWDFDevice);

        if (FAILED(hr))
        {
            Trace(
                TRACE_LEVEL_ERROR,
                "Failed to create the IWDFDevice object, %!HRESULT!",
                hr);
        }

        if (SUCCEEDED(hr))
        {   
            // Assign context
            hr = spIWDFDevice->AssignContext(nullptr, (void*)this);

            if (FAILED(hr))
            {
                Trace(
                    TRACE_LEVEL_ERROR,
                    "Failed to assign context, %!HRESULT!",
                    hr);
            }
        }
    }
        
    if (SUCCEEDED(hr))
    {
        WUDF_DEVICE_POWER_POLICY_IDLE_SETTINGS idleSettings;
        WUDF_DEVICE_POWER_POLICY_IDLE_SETTINGS_INIT(
            &idleSettings,
            IdleCannotWakeFromS0
            );

        // Set delay timeout value. This specifies the time
        // delay between WDF detecting the device is idle
        // and WDF requesting a Dx power transition on the 
        // device's behalf.
        idleSettings.IdleTimeout = 100;
        
        // Opt-in to D3Cold to allow the platform to remove 
        // power when the device is idle and enters D3.
        idleSettings.ExcludeD3Cold = WdfFalse;

        // Get a pointer to the IWDFDevice3 interface and
        // assign the idle settings.
        hr = spIWDFDevice->QueryInterface(IID_PPV_ARGS(&spIWDFDevice3));

        if (SUCCEEDED(hr)) 
        {
            hr = spIWDFDevice3->AssignS0IdleSettingsEx(&idleSettings);
        }
    }
        
    if (SUCCEEDED(hr))
    {
        // Ensure device is disable-able
        spIWDFDevice->SetPnpState(WdfPnpStateNotDisableable, WdfFalse);
        spIWDFDevice->CommitPnpState();

        // Store the IWDFDevice pointer
        m_spWdfDevice = spIWDFDevice;
    }

    FuncExit();

    return hr;
}
コード例 #30
-1
HRESULT AudioDeviceService::RefreshAudioDevices()
{
    CleanUpAudioDevices();

    CComPtr<IMMDeviceEnumerator> deviceEnumerator;
    FAST_FAIL(CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_INPROC, IID_PPV_ARGS(&deviceEnumerator)));

    CComPtr<IMMDeviceCollection> deviceCollection;
    FAST_FAIL(deviceEnumerator->EnumAudioEndpoints(EDataFlow::eRender, ERole::eMultimedia, &deviceCollection));

    CComPtr<IMMDevice> defaultDevice;
    FAST_FAIL(deviceEnumerator->GetDefaultAudioEndpoint(EDataFlow::eRender, ERole::eMultimedia, &defaultDevice));

    CComHeapPtr<wchar_t> defaultDeviceId;
    FAST_FAIL(defaultDevice->GetId(&defaultDeviceId));

    UINT numDevices;
    FAST_FAIL(deviceCollection->GetCount(&numDevices));

    for (UINT i = 0; i < numDevices; i++)
    {
        CComPtr<IMMDevice> device;
        if (FAILED(deviceCollection->Item(i, &device)))
        {
            continue;
        }

        CComHeapPtr<wchar_t> deviceId;
        FAST_FAIL(device->GetId(&deviceId));

        CComPtr<IPropertyStore> propertyStore;
        FAST_FAIL(device->OpenPropertyStore(STGM_READ, &propertyStore));

        PROPVARIANT friendlyName;
        PropVariantInit(&friendlyName);
        FAST_FAIL(propertyStore->GetValue(PKEY_Device_FriendlyName, &friendlyName));
        
        CComPtr<IAudioEndpointVolume> audioEndpointVol;
        FAST_FAIL(device->Activate(__uuidof(IAudioEndpointVolume), CLSCTX_INPROC, nullptr, reinterpret_cast<void**>(&audioEndpointVol)));

        BOOL isMuted;
        FAST_FAIL(audioEndpointVol->GetMute(&isMuted));

        EarTrumpetAudioDevice audioDevice = {};
        FAST_FAIL(SHStrDup(friendlyName.pwszVal, &audioDevice.DisplayName));
        FAST_FAIL(SHStrDup(deviceId, &audioDevice.Id));
        audioDevice.IsDefault = (wcscmp(defaultDeviceId, deviceId) == 0);
        audioDevice.IsMuted = !!isMuted;
        _devices.push_back(audioDevice);

        PropVariantClear(&friendlyName);
    }

    return S_OK;
}