HRESULT QNativeSocketEnginePrivate::handleNewDatagram(IDatagramSocket *socket, IDatagramSocketMessageReceivedEventArgs *args)
{
    Q_Q(QNativeSocketEngine);
    Q_UNUSED(socket);

    WinRtDatagram datagram;
    QHostAddress returnAddress;
    ComPtr<IHostName> remoteHost;
    HRESULT hr = args->get_RemoteAddress(&remoteHost);
    RETURN_OK_IF_FAILED("Could not obtain remote host");
    HString remoteHostString;
    remoteHost->get_CanonicalName(remoteHostString.GetAddressOf());
    RETURN_OK_IF_FAILED("Could not obtain remote host's canonical name");
    returnAddress.setAddress(qt_QStringFromHString(remoteHostString));
    datagram.address = returnAddress;
    HString remotePort;
    hr = args->get_RemotePort(remotePort.GetAddressOf());
    RETURN_OK_IF_FAILED("Could not obtain remote port");
    datagram.port = qt_QStringFromHString(remotePort).toInt();

    ComPtr<IDataReader> reader;
    hr = args->GetDataReader(&reader);
    RETURN_OK_IF_FAILED("Could not obtain data reader");
    quint32 length;
    hr = reader->get_UnconsumedBufferLength(&length);
    RETURN_OK_IF_FAILED("Could not obtain unconsumed buffer length");
    datagram.data.resize(length);
    hr = reader->ReadBytes(length, reinterpret_cast<BYTE *>(datagram.data.data()));
    RETURN_OK_IF_FAILED("Could not read datagram");
    pendingDatagrams.append(datagram);
    emit q->readReady();

    return S_OK;
}
Пример #2
0
void
FrameworkView::LaunchActivated(ComPtr<ILaunchActivatedEventArgs>& aArgs, bool aStartup)
{
  if (!aArgs)
    return;
  HString data;
  AssertHRESULT(aArgs->get_Arguments(data.GetAddressOf()));
  if (WindowsIsStringEmpty(data.Get()))
    return;

  // If we're being launched from a secondary tile then we have a 2nd command line param of -url
  // and a third of the secondary tile.  We want it in sActivationURI so that browser.js will
  // load it in without showing the start UI.
  int argc;
  unsigned int length;
  LPWSTR* argv = CommandLineToArgvW(data.GetRawBuffer(&length), &argc);
  if (aStartup && argc == 2 && !wcsicmp(argv[0], L"-url")) {
    WindowsCreateString(argv[1], wcslen(argv[1]), &sActivationURI);
  } else {
    // Some other command line or this is not a startup.
    // If it is startup we process it later when XPCOM is initialilzed.
    mActivationCommandLine = data.GetRawBuffer(&length);
    if (!aStartup) {
      ProcessLaunchArguments();
    }
  }
}
Пример #3
0
HRESULT ezUwpApplication::OnActivated(ICoreApplicationView* view, IActivatedEventArgs* args)
{
  view->remove_Activated(m_activateRegistrationToken);

  ActivationKind activationKind;
  EZ_SUCCEED_OR_RETURN(args->get_Kind(&activationKind));

  if (activationKind == ActivationKind_Launch)
  {
    ComPtr<ILaunchActivatedEventArgs> launchArgs;
    EZ_SUCCEED_OR_RETURN(args->QueryInterface(launchArgs.GetAddressOf()));

    HString argHString;
    EZ_SUCCEED_OR_RETURN(launchArgs->get_Arguments(argHString.GetAddressOf()));

    ezDynamicArray<const char*> argv;
    ezCommandLineUtils::SplitCommandLineString(ezStringUtf8(argHString).GetData(), true, m_commandLineArgs, argv);

    m_application->SetCommandLineArguments(argv.GetCount(), argv.GetData());
  }

  // Activate main window together with the application!
  ComPtr<ABI::Windows::UI::Core::ICoreWindow> pCoreWindow;
  EZ_SUCCEED_OR_RETURN(view->get_CoreWindow(pCoreWindow.GetAddressOf()));
  EZ_SUCCEED_OR_RETURN(pCoreWindow->Activate());

  return S_OK;
}
Пример #4
0
HRESULT
FrameworkView::OnSearchQuerySubmitted(ISearchPane* aPane,
                                      ISearchPaneQuerySubmittedEventArgs* aArgs)
{
  LogFunction();
  HString aQuery;
  aArgs->get_QueryText(aQuery.GetAddressOf());
  PerformURILoadOrSearch(aQuery);
  return S_OK;
}
static QString deviceDescription(IDeviceInformation *device)
{
    HRESULT hr;
    HString name;
    hr = device->get_Name(name.GetAddressOf());
    Q_ASSERT_SUCCEEDED(hr);
    quint32 length;
    const wchar_t *buffer = name.GetRawBuffer(&length);
    return QString::fromWCharArray(buffer, length);
}
    HRESULT onDeviceRemoved(IDeviceWatcher *, IDeviceInformationUpdate *device)
    {
        HRESULT hr;
        HString id;
        hr = device->get_Id(id.GetAddressOf());
        Q_ASSERT_SUCCEEDED(hr);

        HString name;
        hr = device->get_Id(name.GetAddressOf());
        Q_ASSERT_SUCCEEDED(hr);
        quint32 nameLength;
        const wchar_t *nameString = name.GetRawBuffer(&nameLength);
        const int index = deviceIndex.take(QString::fromWCharArray(nameString, nameLength));
        if (index >= 0)
            devices.remove(index);

        foreach (QWinRTVideoDeviceSelectorControl *watcher, watchers)
            emit watcher->devicesChanged();

        return S_OK;
    }
QT_USE_NAMESPACE

static QString deviceName(IDeviceInformation *device)
{
    HRESULT hr;
    HString id;
    hr = device->get_Id(id.GetAddressOf());
    Q_ASSERT_SUCCEEDED(hr);
    quint32 length;
    const wchar_t *buffer = id.GetRawBuffer(&length);
    return QString::fromWCharArray(buffer, length);
}
Пример #8
0
QString QHostInfo::localHostName()
{
    ComPtr<INetworkInformationStatics> statics;
    GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_Connectivity_NetworkInformation).Get(), &statics);

    ComPtr<IVectorView<HostName *>> hostNames;
    statics->GetHostNames(&hostNames);
    if (!hostNames)
        return QString();

    unsigned int size;
    hostNames->get_Size(&size);
    if (size == 0)
        return QString();

    for (unsigned int i = 0; i < size; ++i) {
        ComPtr<IHostName> hostName;
        hostNames->GetAt(i, &hostName);
        HostNameType type;
        hostName->get_Type(&type);
        if (type != HostNameType_DomainName)
            continue;

        HString name;
        hostName->get_CanonicalName(name.GetAddressOf());
        UINT32 length;
        PCWSTR rawString = name.GetRawBuffer(&length);
        return QString::fromWCharArray(rawString, length);
    }
    ComPtr<IHostName> firstHost;
    hostNames->GetAt(0, &firstHost);

    HString name;
    firstHost->get_CanonicalName(name.GetAddressOf());
    UINT32 length;
    PCWSTR rawString = name.GetRawBuffer(&length);
    return QString::fromWCharArray(rawString, length);
}
std::wstring uri_resolve( std::wstring const&url, std::wstring const&relative ) {
  if ( url.empty() )
    return relative;
  ComPtr<IUriRuntimeClassFactory> uriFactory;
  auto hr = GetActivationFactory( HStringReference( RuntimeClass_Windows_Foundation_Uri ).Get(), &uriFactory );
  ComPtr<IUriRuntimeClass> uri, v;
  if (ok(hr))
    hr = uriFactory->CreateUri( HStringReference( url.c_str() ).Get(), uri.ReleaseAndGetAddressOf() );
  if (ok(hr))
    hr = uri->CombineUri( HStringReference( relative.c_str() ).Get(), v.ReleaseAndGetAddressOf());
  HString urx;
  if (ok(hr))
    hr = v->get_AbsoluteUri( urx.GetAddressOf() );
  return ok(hr)?std::wstring( urx.GetRawBuffer( nullptr ) ) : relative;  
}
Пример #10
0
HRESULT GetExeModulePath(LPWSTR lpstrPath,HMODULE hModule)
{
#if (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP)
	WCHAR szBuffer[MAX_PATH] = {};
	DWORD dwResult = GetModuleFileNameW(hModule,szBuffer,MAX_PATH);
	if (dwResult == 0)
		return HRESULT_FROM_WIN32(GetLastError());

	auto p = wcsrchr(szBuffer,L'\\');
	if (p)
		*p = NULL;

	wcscpy_s(lpstrPath,MAX_PATH,szBuffer);
	return S_OK;
#else
	ComPtr<ABI::Windows::ApplicationModel::IPackageStatics> pPkgMethods;
	HRESULT hr = RoGetActivationFactory(HStringReference(RuntimeClass_Windows_ApplicationModel_Package).Get(),
		IID_PPV_ARGS(pPkgMethods.GetAddressOf()));

	if (FAILED(hr))
		return hr;

	ComPtr<ABI::Windows::ApplicationModel::IPackage> pPackage;
	hr = pPkgMethods->get_Current(pPackage.GetAddressOf());
	if (FAILED(hr))
		return hr;

	ComPtr<ABI::Windows::Storage::IStorageFolder> pFolder;
	hr = pPackage->get_InstalledLocation(pFolder.GetAddressOf());
	if (FAILED(hr))
		return hr;

	ComPtr<ABI::Windows::Storage::IStorageItem> pFolderItem;
	hr = pFolder.As(&pFolderItem);
	if (FAILED(hr))
		return hr;

	HString hstrPath;
	hr = pFolderItem->get_Path(hstrPath.GetAddressOf());
	if (FAILED(hr))
		return hr;

	wcscpy_s(lpstrPath,MAX_PATH,hstrPath.GetRawBuffer(nullptr));
	return S_OK;
#endif
}
Пример #11
0
QString UrlFromFileArgs(IInspectable *args)
{
    ComPtr<IFileActivatedEventArgs> fileArgs;
    COM_ENSURE(args->QueryInterface(fileArgs.GetAddressOf()), QString());
    ComPtr<IVectorView<IStorageItem*>> files;
    COM_ENSURE(fileArgs->get_Files(&files), QString());
    ComPtr<IStorageItem> item;
    COM_ENSURE(files->GetAt(0, &item), QString());
    HString path;
    COM_ENSURE(item->get_Path(path.GetAddressOf()), QString());

    quint32 pathLen;
    const wchar_t *pathStr = path.GetRawBuffer(&pathLen);
    const QString filePath = QString::fromWCharArray(pathStr, pathLen);
    qDebug() << "file path: " << filePath;
    item->AddRef(); //ensure we can access it later. TODO: how to release?
    return QString::fromLatin1("winrt:@%1:%2").arg((qint64)(qptrdiff)item.Get()).arg(filePath);
}
Пример #12
0
void
FrameworkView::FileActivated(ComPtr<IFileActivatedEventArgs>& aArgs, bool aStartup)
{
  if (!aArgs)
    return;

  ComPtr<IVectorView<ABI::Windows::Storage::IStorageItem*>> list;
  AssertHRESULT(aArgs->get_Files(list.GetAddressOf()));
  ComPtr<ABI::Windows::Storage::IStorageItem> item;
  AssertHRESULT(list->GetAt(0, item.GetAddressOf()));
  HString filePath;
  AssertHRESULT(item->get_Path(filePath.GetAddressOf()));

  if (aStartup) {
    WindowsDuplicateString(filePath.Get(), &sActivationURI);
  } else {
    PerformURILoad(filePath);
  }
}
Пример #13
0
void
FrameworkView::ProcessActivationArgs(IActivatedEventArgs* aArgs, bool aStartup)
{
  ActivationKind kind;
  if (!aArgs || FAILED(aArgs->get_Kind(&kind)))
    return;
  ComPtr<IActivatedEventArgs> args(aArgs);
  if (kind == ActivationKind::ActivationKind_Protocol) {
    WinUtils::Log("Activation argument kind: Protocol");
    ComPtr<IProtocolActivatedEventArgs> protoArgs;
    AssertHRESULT(args.As(&protoArgs));
    ComPtr<IUriRuntimeClass> uri;
    AssertHRESULT(protoArgs->get_Uri(uri.GetAddressOf()));
    if (!uri)
      return;

    HString data;
    AssertHRESULT(uri->get_AbsoluteUri(data.GetAddressOf()));
    if (WindowsIsStringEmpty(data.Get()))
      return;

    if (aStartup) {
      WindowsDuplicateString(data.Get(), &sActivationURI);
    } else {
      PerformURILoad(data);
    }
  } else if (kind == ActivationKind::ActivationKind_Search) {
    WinUtils::Log("Activation argument kind: Search");
    ComPtr<ISearchActivatedEventArgs> searchArgs;
    args.As(&searchArgs);
    SearchActivated(searchArgs, aStartup);
  } else if (kind == ActivationKind::ActivationKind_File) {
    WinUtils::Log("Activation argument kind: File");
    ComPtr<IFileActivatedEventArgs> fileArgs;
    args.As(&fileArgs);
    FileActivated(fileArgs, aStartup);
  } else if (kind == ActivationKind::ActivationKind_Launch) {
    WinUtils::Log("Activation argument kind: Launch");
    ComPtr<ILaunchActivatedEventArgs> launchArgs;
    args.As(&launchArgs);
    LaunchActivated(launchArgs, aStartup);
  }
}
Пример #14
0
void
FrameworkView::SearchActivated(ComPtr<ISearchActivatedEventArgs>& aArgs, bool aStartup)
{
  if (!aArgs)
    return;

  HString data;
  AssertHRESULT(aArgs->get_QueryText(data.GetAddressOf()));
  if (WindowsIsStringEmpty(data.Get()))
    return;

  unsigned int length;
  WinUtils::LogW(L"SearchActivated text=%s", data.GetRawBuffer(&length));
  if (aStartup) {
    WindowsDuplicateString(data.Get(), &sActivationURI);
  } else {
    PerformURILoadOrSearch(data);
  }
}
Пример #15
0
QT_BEGIN_NAMESPACE

void QDnsLookupRunnable::query(const int requestType, const QByteArray &requestName, const QHostAddress &nameserver, QDnsLookupReply *reply)
{
    // TODO: Add nameserver support for winRT
    if (!nameserver.isNull())
        qWarning() << "Ignoring nameserver as its currently not supported on WinRT";

    // TODO: is there any way to do "proper" dns lookup?
    if (requestType != QDnsLookup::A && requestType != QDnsLookup::AAAA
            && requestType != QDnsLookup::ANY) {
        reply->error = QDnsLookup::InvalidRequestError;
        reply->errorString = QLatin1String("WinRT only supports IPv4 and IPv6 requests");
        return;
    }

    QString aceHostname = QUrl::fromAce(requestName);
    if (aceHostname.isEmpty()) {
        reply->error = QDnsLookup::InvalidRequestError;
        reply->errorString = requestName.isEmpty() ? tr("No hostname given") : tr("Invalid hostname");
        return;
    }

    ComPtr<IHostNameFactory> hostnameFactory;
    HRESULT hr = RoGetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_HostName).Get(),
                                        IID_PPV_ARGS(&hostnameFactory));
    if (FAILED(hr)) {
        reply->error = QDnsLookup::ResolverError;
        reply->errorString = QLatin1String("Could not obtain hostname factory");
        return;
    }
    ComPtr<IHostName> host;
    HStringReference hostNameRef((const wchar_t*)aceHostname.utf16());
    hostnameFactory->CreateHostName(hostNameRef.Get(), &host);

    ComPtr<IDatagramSocketStatics> datagramSocketStatics;
    GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_Sockets_DatagramSocket).Get(), &datagramSocketStatics);

    ComPtr<IAsyncOperation<IVectorView<EndpointPair *> *>> op;
    datagramSocketStatics->GetEndpointPairsAsync(host.Get(),
                                                 HString::MakeReference(L"0").Get(),
                                                 &op);

    ComPtr<IVectorView<EndpointPair *>> endpointPairs;
    hr = op->GetResults(&endpointPairs);
    int waitCount = 0;
    while (hr == E_ILLEGAL_METHOD_CALL) {
        WaitForSingleObjectEx(GetCurrentThread(), 50, FALSE);
        hr = op->GetResults(&endpointPairs);
        if (++waitCount > 1200) // Wait for 1 minute max
            return;
    }

    if (!endpointPairs)
        return;

    unsigned int size;
    endpointPairs->get_Size(&size);
    // endpoint pairs might contain duplicates so we temporarily store addresses in a QSet
    QSet<QHostAddress> addresses;
    for (unsigned int i = 0; i < size; ++i) {
        ComPtr<IEndpointPair> endpointpair;
        endpointPairs->GetAt(i, &endpointpair);
        ComPtr<IHostName> remoteHost;
        endpointpair->get_RemoteHostName(&remoteHost);
        HostNameType type;
        remoteHost->get_Type(&type);
        if (type == HostNameType_Bluetooth || type == HostNameType_DomainName
                || (requestType != QDnsLookup::ANY
                && ((type == HostNameType_Ipv4 && requestType == QDnsLookup::AAAA)
                || (type == HostNameType_Ipv6 && requestType == QDnsLookup::A))))
            continue;

        HString name;
        remoteHost->get_CanonicalName(name.GetAddressOf());
        UINT32 length;
        PCWSTR rawString = name.GetRawBuffer(&length);
        addresses.insert(QHostAddress(QString::fromWCharArray(rawString, length)));
    }
    foreach (const QHostAddress &address, addresses) {
        QDnsHostAddressRecord record;
        record.d->name = aceHostname;
        record.d->value = address;
        reply->hostAddressRecords.append(record);
    }
Пример #16
0
std::vector<AudioEngine::RendererDetail> AudioEngine::GetRendererDetails()
{
    std::vector<RendererDetail> list;

#if defined(WINAPI_FAMILY) && WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP

    LPCWSTR id = GetDefaultAudioRenderId( Default );
    if ( !id )
        return list;

    RendererDetail device;
    device.deviceId = id;
    device.description = L"Default";

    CoTaskMemFree( (LPVOID)id );

#elif defined(_XBOX_ONE)

    using namespace Microsoft::WRL;
    using namespace Microsoft::WRL::Wrappers;
    using namespace ABI::Windows::Media::Devices;

    Microsoft::WRL::ComPtr<IMediaDeviceStatics> mdStatics;
    HRESULT hr = ABI::Windows::Foundation::GetActivationFactory( HStringReference(RuntimeClass_Windows_Media_Devices_MediaDevice).Get(), &mdStatics );
    ThrowIfFailed( hr );

    HString id;
    hr = mdStatics->GetDefaultAudioRenderId( AudioDeviceRole_Default, id.GetAddressOf() );
    ThrowIfFailed( hr );

    RendererDetail device;
    device.deviceId = id.GetRawBuffer( nullptr );
    device.description = L"Default";
    list.emplace_back( device );

#elif (_WIN32_WINNT >= _WIN32_WINNT_WIN8)

#if defined(__cplusplus_winrt)

    // Enumerating with WinRT using C++/CX (Windows Store apps)
    using Windows::Devices::Enumeration::DeviceClass;
    using Windows::Devices::Enumeration::DeviceInformation;
    using Windows::Devices::Enumeration::DeviceInformationCollection;

    auto operation = DeviceInformation::FindAllAsync(DeviceClass::AudioRender);
    while (operation->Status != Windows::Foundation::AsyncStatus::Completed)
        ;

    DeviceInformationCollection^ devices = operation->GetResults();

    for (unsigned i = 0; i < devices->Size; ++i)
    {
        using Windows::Devices::Enumeration::DeviceInformation;

        DeviceInformation^ d = devices->GetAt(i);

        RendererDetail device;
        device.deviceId = d->Id->Data();
        device.description = d->Name->Data();
        list.emplace_back(device);
    }
#else

    // Enumerating with WinRT using WRL (Win32 desktop app for Windows 8.x)
    using namespace Microsoft::WRL;
    using namespace Microsoft::WRL::Wrappers;
    using namespace ABI::Windows::Foundation;
    using namespace ABI::Windows::Foundation::Collections;
    using namespace ABI::Windows::Devices::Enumeration;

    RoInitializeWrapper initialize(RO_INIT_MULTITHREADED);
    HRESULT hr = initialize;
    ThrowIfFailed( hr );

    Microsoft::WRL::ComPtr<IDeviceInformationStatics> diFactory;
    hr = ABI::Windows::Foundation::GetActivationFactory( HStringReference(RuntimeClass_Windows_Devices_Enumeration_DeviceInformation).Get(), &diFactory );
    ThrowIfFailed( hr );

    Event findCompleted( CreateEventEx( nullptr, nullptr, CREATE_EVENT_MANUAL_RESET, WRITE_OWNER | EVENT_ALL_ACCESS ) );
    if ( !findCompleted.IsValid() )
        throw std::exception( "CreateEventEx" );

    auto callback = Callback<IAsyncOperationCompletedHandler<DeviceInformationCollection*>>(
        [&findCompleted,list]( IAsyncOperation<DeviceInformationCollection*>* aDevices, AsyncStatus status ) -> HRESULT
    {
        UNREFERENCED_PARAMETER(aDevices);
        UNREFERENCED_PARAMETER(status);
        SetEvent( findCompleted.Get() );
        return S_OK;
    });

    ComPtr<IAsyncOperation<DeviceInformationCollection*>> operation;
    hr = diFactory->FindAllAsyncDeviceClass( DeviceClass_AudioRender, operation.GetAddressOf() );
    ThrowIfFailed( hr );

    operation->put_Completed( callback.Get() );

    (void)WaitForSingleObjectEx( findCompleted.Get(), INFINITE, FALSE );

    ComPtr<IVectorView<DeviceInformation*>> devices;
    operation->GetResults( devices.GetAddressOf() );

    unsigned int count = 0;
    hr = devices->get_Size( &count );
    ThrowIfFailed( hr );

    if ( !count )
        return list;

    for( unsigned int j = 0; j < count; ++j )
    {
        ComPtr<IDeviceInformation> deviceInfo;
        hr = devices->GetAt( j, deviceInfo.GetAddressOf() );
        if ( SUCCEEDED(hr) )
        {
            HString id;
            deviceInfo->get_Id( id.GetAddressOf() );

            HString name;
            deviceInfo->get_Name( name.GetAddressOf() );

            RendererDetail device;
            device.deviceId = id.GetRawBuffer( nullptr );
            device.description = name.GetRawBuffer( nullptr );
            list.emplace_back( device );
        }
    }

#endif 

#else // _WIN32_WINNT < _WIN32_WINNT_WIN8

    // Enumerating with XAudio 2.7
    ComPtr<IXAudio2> pXAudio2;

    HRESULT hr = XAudio2Create( pXAudio2.GetAddressOf() );
    if ( FAILED(hr) )
    {
        DebugTrace( "ERROR: XAudio 2.7 not found (have you called CoInitialize?)\n");
        throw std::exception( "XAudio2Create" );
    }

    UINT32 count = 0;
    hr = pXAudio2->GetDeviceCount( &count );
    ThrowIfFailed(hr);

    if ( !count )
        return list;

    list.reserve( count );

    for( UINT32 j = 0; j < count; ++j )
    {
        XAUDIO2_DEVICE_DETAILS details;
        hr = pXAudio2->GetDeviceDetails( j, &details );
        if ( SUCCEEDED(hr) )
        {
            RendererDetail device;
            device.deviceId = details.DeviceID;
            device.description = details.DisplayName;
            list.emplace_back( device );
        }
    }

#endif

    return list;
}
bool QNativeSocketEnginePrivate::fetchConnectionParameters()
{
    localPort = 0;
    localAddress.clear();
    peerPort = 0;
    peerAddress.clear();

    if (socketType == QAbstractSocket::TcpSocket) {
        ComPtr<IHostName> hostName;
        HString tmpHString;
        ComPtr<IStreamSocketInformation> info;
        if (FAILED(tcpSocket()->get_Information(&info))) {
            qWarning("QNativeSocketEnginePrivate::fetchConnectionParameters: Could not obtain socket info");
            return false;
        }
        info->get_LocalAddress(&hostName);
        if (hostName) {
            hostName->get_CanonicalName(tmpHString.GetAddressOf());
            localAddress.setAddress(qt_QStringFromHString(tmpHString));
            info->get_LocalPort(tmpHString.GetAddressOf());
            localPort = qt_QStringFromHString(tmpHString).toInt();
        }
        if (!localPort && tcpListener) {
            ComPtr<IStreamSocketListenerInformation> listenerInfo = 0;
            tcpListener->get_Information(&listenerInfo);
            listenerInfo->get_LocalPort(tmpHString.GetAddressOf());
            localPort = qt_QStringFromHString(tmpHString).toInt();
            localAddress == QHostAddress::Any;
        }
        info->get_RemoteAddress(&hostName);
        if (hostName) {
            hostName->get_CanonicalName(tmpHString.GetAddressOf());
            peerAddress.setAddress(qt_QStringFromHString(tmpHString));
            info->get_RemotePort(tmpHString.GetAddressOf());
            peerPort = qt_QStringFromHString(tmpHString).toInt();
        }
    } else if (socketType == QAbstractSocket::UdpSocket) {
        ComPtr<IHostName> hostName;
        HString tmpHString;
        ComPtr<IDatagramSocketInformation> info;
        if (FAILED(udpSocket()->get_Information(&info))) {
            qWarning("QNativeSocketEnginePrivate::fetchConnectionParameters: Could not obtain socket information");
            return false;
        }
        info->get_LocalAddress(&hostName);
        if (hostName) {
            hostName->get_CanonicalName(tmpHString.GetAddressOf());
            localAddress.setAddress(qt_QStringFromHString(tmpHString));
            info->get_LocalPort(tmpHString.GetAddressOf());
            localPort = qt_QStringFromHString(tmpHString).toInt();
        }

        info->get_RemoteAddress(&hostName);
        if (hostName) {
            hostName->get_CanonicalName(tmpHString.GetAddressOf());
            peerAddress.setAddress(qt_QStringFromHString(tmpHString));
            info->get_RemotePort(tmpHString.GetAddressOf());
            peerPort = qt_QStringFromHString(tmpHString).toInt();
        }
    }
    return true;
}
Пример #18
0
QVariant QSystemLocalePrivate::uiLanguages()
{
    if (QSysInfo::windowsVersion() >= QSysInfo::WV_VISTA) {
        typedef BOOL (WINAPI *GetUserPreferredUILanguagesFunc) (
                    DWORD dwFlags,
                    PULONG pulNumLanguages,
                    PWSTR pwszLanguagesBuffer,
                    PULONG pcchLanguagesBuffer);
        static GetUserPreferredUILanguagesFunc GetUserPreferredUILanguages_ptr = 0;
#ifndef Q_OS_WINRT
        if (!GetUserPreferredUILanguages_ptr) {
            QSystemLibrary lib(QLatin1String("kernel32"));
            if (lib.load())
                GetUserPreferredUILanguages_ptr = (GetUserPreferredUILanguagesFunc)lib.resolve("GetUserPreferredUILanguages");
        }
#endif // !Q_OS_WINRT
        if (GetUserPreferredUILanguages_ptr) {
            unsigned long cnt = 0;
            QVarLengthArray<wchar_t, 64> buf(64);
            unsigned long size = buf.size();
            if (!GetUserPreferredUILanguages_ptr(MUI_LANGUAGE_NAME, &cnt, buf.data(), &size)) {
                size = 0;
                if (GetLastError() == ERROR_INSUFFICIENT_BUFFER &&
                    GetUserPreferredUILanguages_ptr(MUI_LANGUAGE_NAME, &cnt, NULL, &size)) {
                    buf.resize(size);
                    if (!GetUserPreferredUILanguages_ptr(MUI_LANGUAGE_NAME, &cnt, buf.data(), &size))
                        return QStringList();
                }
            }
            QStringList result;
            result.reserve(cnt);
            const wchar_t *str = buf.constData();
            for (; cnt > 0; --cnt) {
                QString s = QString::fromWCharArray(str);
                if (s.isEmpty())
                    break; // something is wrong
                result.append(s);
                str += s.size()+1;
            }
            return result;
        }
    }

#ifndef Q_OS_WINRT
    // old Windows before Vista
    return QStringList(QString::fromLatin1(winLangCodeToIsoName(GetUserDefaultUILanguage())));
#else // !Q_OS_WINRT
    QStringList result;
    ComPtr<ABI::Windows::Globalization::IApplicationLanguagesStatics> appLanguagesStatics;
    if (FAILED(GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Globalization_ApplicationLanguages).Get(), &appLanguagesStatics))) {
        qWarning("Could not obtain ApplicationLanguagesStatic");
        return QStringList();
    }

    ComPtr<ABI::Windows::Foundation::Collections::IVectorView<HSTRING> > languageList;
    // Languages is a ranked list of "long names" (e.g. en-US) of preferred languages, which matches
    // languages from the manifest with languages from the user's system.
    HRESULT hr = appLanguagesStatics->get_Languages(&languageList);
    Q_ASSERT_SUCCEEDED(hr);
    unsigned int size;
    hr = languageList->get_Size(&size);
    Q_ASSERT_SUCCEEDED(hr);
    result.reserve(size);
    for (unsigned int i = 0; i < size; ++i) {
        HString language;
        hr = languageList->GetAt(i, language.GetAddressOf());
        Q_ASSERT_SUCCEEDED(hr);
        UINT32 length;
        PCWSTR rawString = language.GetRawBuffer(&length);
        result << QString::fromWCharArray(rawString, length);
    }

    // ManifestLanguages covers all languages given in the manifest and uses short names (like "en").
    hr = appLanguagesStatics->get_ManifestLanguages(&languageList);
    Q_ASSERT_SUCCEEDED(hr);
    hr = languageList->get_Size(&size);
    Q_ASSERT_SUCCEEDED(hr);
    for (unsigned int i = 0; i < size; ++i) {
        HString language;
        hr = languageList->GetAt(i, language.GetAddressOf());
        Q_ASSERT_SUCCEEDED(hr);
        UINT32 length;
        PCWSTR rawString = language.GetRawBuffer(&length);
        const QString qLanguage = QString::fromWCharArray(rawString, length);
        bool found = false;
        // Since ApplicationLanguages:::Languages uses long names, we compare the "pre-dash" part of
        // the language and filter it out, if it is already covered by a more specialized form.
        foreach (const QString &lang, result) {
            int dashIndex = lang.indexOf('-');
            // There will not be any long name after the first short name was found, so we can stop.
            if (dashIndex == -1)
                break;

            if (lang.leftRef(dashIndex) == qLanguage) {
                found = true;
                break;
            }
        }
        if (!found)
            result << qLanguage;
    }
static QList<QNetworkInterfacePrivate *> interfaceListing()
{
    QList<QNetworkInterfacePrivate *> interfaces;

    QList<HostNameInfo> hostList;

    ComPtr<INetworkInformationStatics> hostNameStatics;
    GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_Connectivity_NetworkInformation).Get(), &hostNameStatics);

    ComPtr<IVectorView<HostName *>> hostNames;
    hostNameStatics->GetHostNames(&hostNames);
    if (!hostNames)
        return interfaces;

    unsigned int hostNameCount;
    hostNames->get_Size(&hostNameCount);
    for (unsigned i = 0; i < hostNameCount; ++i) {
        HostNameInfo hostInfo;
        ComPtr<IHostName> hostName;
        hostNames->GetAt(i, &hostName);

        HostNameType type;
        hostName->get_Type(&type);
        if (type == HostNameType_DomainName)
            continue;

        ComPtr<IIPInformation> ipInformation;
        hostName->get_IPInformation(&ipInformation);
        ComPtr<INetworkAdapter> currentAdapter;
        ipInformation->get_NetworkAdapter(&currentAdapter);

        currentAdapter->get_NetworkAdapterId(&hostInfo.adapterId);

        ComPtr<IReference<unsigned char>> prefixLengthReference;
        ipInformation->get_PrefixLength(&prefixLengthReference);

        prefixLengthReference->get_Value(&hostInfo.prefixLength);

        // invalid prefixes
        if ((type == HostNameType_Ipv4 && hostInfo.prefixLength > 32)
                || (type == HostNameType_Ipv6 && hostInfo.prefixLength > 128))
            continue;

        HString name;
        hostName->get_CanonicalName(name.GetAddressOf());
        UINT32 length;
        PCWSTR rawString = name.GetRawBuffer(&length);
        hostInfo.address = QString::fromWCharArray(rawString, length);

        hostList << hostInfo;
    }

    INetworkInformationStatics *networkInfoStatics;
    GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_Connectivity_NetworkInformation).Get(), &networkInfoStatics);
    ComPtr<IVectorView<ConnectionProfile *>> connectionProfiles;
    networkInfoStatics->GetConnectionProfiles(&connectionProfiles);
    if (!connectionProfiles)
        return interfaces;

    unsigned int size;
    connectionProfiles->get_Size(&size);
    for (unsigned int i = 0; i < size; ++i) {
        QNetworkInterfacePrivate *iface = new QNetworkInterfacePrivate;
        interfaces << iface;

        ComPtr<IConnectionProfile> profile;
        connectionProfiles->GetAt(i, &profile);

        NetworkConnectivityLevel connectivityLevel;
        profile->GetNetworkConnectivityLevel(&connectivityLevel);
        if (connectivityLevel != NetworkConnectivityLevel_None)
            iface->flags = QNetworkInterface::IsUp | QNetworkInterface::IsRunning;

        ComPtr<INetworkAdapter> adapter;
        profile->get_NetworkAdapter(&adapter);
        UINT32 type;
        adapter->get_IanaInterfaceType(&type);
        if (type == 23)
            iface->flags |= QNetworkInterface::IsPointToPoint;
        GUID id;
        adapter->get_NetworkAdapterId(&id);
        OLECHAR adapterName[39]={0};
        StringFromGUID2(id, adapterName, 39);
        iface->name = QString::fromWCharArray(adapterName);

        // According to http://stackoverflow.com/questions/12936193/how-unique-is-the-ethernet-network-adapter-id-in-winrt-it-is-derived-from-the-m
        // obtaining the MAC address using WinRT API is impossible
        // iface->hardwareAddress = ?

        for (int i = 0; i < hostList.length(); ++i) {
            const HostNameInfo hostInfo = hostList.at(i);
            if (id != hostInfo.adapterId)
                continue;

            QNetworkAddressEntry entry;
            entry.setIp(QHostAddress(hostInfo.address));
            entry.setPrefixLength(hostInfo.prefixLength);
            iface->addressEntries << entry;

            hostList.takeAt(i);
            --i;
        }
    }
    return interfaces;
}
Пример #20
0
QT_BEGIN_NAMESPACE

//#define QHOSTINFO_DEBUG

QHostInfo QHostInfoAgent::fromName(const QString &hostName)
{
    QHostInfo results;

    QHostAddress address;
    if (address.setAddress(hostName)) {
        // Reverse lookup
        // TODO: is there a replacement for getnameinfo for winrt?
        Q_UNIMPLEMENTED();
        return results;
    }

    QByteArray aceHostname = QUrl::toAce(hostName);
    results.setHostName(hostName);
    if (aceHostname.isEmpty()) {
        results.setError(QHostInfo::HostNotFound);
        results.setErrorString(hostName.isEmpty() ? tr("No host name given") : tr("Invalid hostname"));
        return results;
    }

    ComPtr<IHostNameFactory> hostnameFactory;
    HRESULT hr = RoGetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_HostName).Get(),
                                        IID_PPV_ARGS(&hostnameFactory));
    Q_ASSERT_X(SUCCEEDED(hr), Q_FUNC_INFO, qPrintable(qt_error_string(hr)));

    ComPtr<IHostName> host;
    HStringReference hostNameRef((const wchar_t*)hostName.utf16());
    hostnameFactory->CreateHostName(hostNameRef.Get(), &host);

    ComPtr<IDatagramSocketStatics> datagramSocketStatics;
    GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_Sockets_DatagramSocket).Get(), &datagramSocketStatics);

    ComPtr<IAsyncOperation<IVectorView<EndpointPair *> *>> op;
    datagramSocketStatics->GetEndpointPairsAsync(host.Get(),
                                                 HString::MakeReference(L"0").Get(),
                                                 &op);

    ComPtr<IVectorView<EndpointPair *>> endpointPairs;
    hr = op->GetResults(&endpointPairs);
    int waitCount = 0;
    while (hr == E_ILLEGAL_METHOD_CALL) {
        WaitForSingleObjectEx(GetCurrentThread(), 50, FALSE);
        hr = op->GetResults(&endpointPairs);
        if (++waitCount > 1200) // Wait for 1 minute max
            return results;
    }

    if (!endpointPairs)
        return results;

    unsigned int size;
    endpointPairs->get_Size(&size);
    QList<QHostAddress> addresses;
    for (unsigned int i = 0; i < size; ++i) {
        ComPtr<IEndpointPair> endpointpair;
        endpointPairs->GetAt(i, &endpointpair);
        ComPtr<IHostName> remoteHost;
        endpointpair->get_RemoteHostName(&remoteHost);
        if (!remoteHost)
            continue;
        HostNameType type;
        remoteHost->get_Type(&type);
        if (type == HostNameType_DomainName)
            continue;

        HString name;
        remoteHost->get_CanonicalName(name.GetAddressOf());
        UINT32 length;
        PCWSTR rawString = name.GetRawBuffer(&length);
        QHostAddress addr;
        addr.setAddress(QString::fromWCharArray(rawString, length));
        if (!addresses.contains(addr))
            addresses.append(addr);
    }
    results.setAddresses(addresses);

    return results;
}
Пример #21
0
HRESULT
FrameworkView::OnDataShareRequested(IDataTransferManager* aDTM,
                                    IDataRequestedEventArgs* aArg)
{
  // Only share pages that contain a title and a URI
  nsCOMPtr<nsIMetroUIUtils> metroUIUtils = do_CreateInstance("@mozilla.org/metro-ui-utils;1");
  if (!metroUIUtils)
      return E_FAIL;

  nsString url, title;
  nsresult rv = metroUIUtils->GetCurrentPageURI(url);
  nsresult rv2 = metroUIUtils->GetCurrentPageTitle(title);
  if (NS_FAILED(rv) || NS_FAILED(rv2)) {
    return E_FAIL;
  }

  // Get the package to share
  HRESULT hr;
  ComPtr<IDataRequest> request;
  AssertRetHRESULT(hr = aArg->get_Request(request.GetAddressOf()), hr);
  ComPtr<IDataPackage> dataPackage;
  AssertRetHRESULT(hr = request->get_Data(dataPackage.GetAddressOf()), hr);
  ComPtr<IDataPackagePropertySet> props;
  AssertRetHRESULT(hr = dataPackage->get_Properties(props.GetAddressOf()), hr);

  // Only add a URI to the package when there is no selected content.
  // This is because most programs treat URIs as highest priority to generate
  // their own preview, but we only want the selected content to show up.
  bool hasSelectedContent = false;
  metroUIUtils->GetHasSelectedContent(&hasSelectedContent);
  if (!hasSelectedContent) {
    ComPtr<IUriRuntimeClass> uri;
    AssertRetHRESULT(hr = MetroUtils::CreateUri(HStringReference(url.BeginReading()).Get(), uri), hr);

    // If there is no selection, then we don't support sharing for sites that
    // are not HTTP, HTTPS, FTP, and FILE.
    HString schemeHString;
    uri->get_SchemeName(schemeHString.GetAddressOf());
    unsigned int length;
    LPCWSTR scheme = schemeHString.GetRawBuffer(&length);
    if (!scheme || wcscmp(scheme, L"http") && wcscmp(scheme, L"https") &&
        wcscmp(scheme, L"ftp") && wcscmp(scheme, L"file")) {
      return S_OK;
    }

    AssertRetHRESULT(hr = dataPackage->SetUri(uri.Get()), hr);
  }

  // Add whatever content metroUIUtils wants us to for the text sharing
  nsString shareText;
  if (NS_SUCCEEDED(metroUIUtils->GetShareText(shareText)) && shareText.Length()) {
    AssertRetHRESULT(hr = dataPackage->SetText(HStringReference(shareText.BeginReading()).Get()) ,hr);
  }

  // Add whatever content metroUIUtils wants us to for the HTML sharing
  nsString shareHTML;
  if (NS_SUCCEEDED(metroUIUtils->GetShareHTML(shareHTML)) && shareHTML.Length()) {
    // The sharing format needs some special headers, so pass it through Windows
    ComPtr<IHtmlFormatHelperStatics> htmlFormatHelper;
    hr = GetActivationFactory(HStringReference(RuntimeClass_Windows_ApplicationModel_DataTransfer_HtmlFormatHelper).Get(),
                              htmlFormatHelper.GetAddressOf());
    AssertRetHRESULT(hr, hr);
    HSTRING fixedHTML;
    htmlFormatHelper->CreateHtmlFormat(HStringReference(shareHTML.BeginReading()).Get(), &fixedHTML);

    // And now add the fixed HTML to the data package
    AssertRetHRESULT(hr = dataPackage->SetHtmlFormat(fixedHTML), hr);
  }

  // Obtain the brand name
  nsCOMPtr<nsIStringBundleService> bundleService = 
    do_GetService(NS_STRINGBUNDLE_CONTRACTID);
  NS_ENSURE_TRUE(bundleService, E_FAIL);
  nsCOMPtr<nsIStringBundle> brandBundle;
  nsString brandName;
  bundleService->CreateBundle("chrome://branding/locale/brand.properties",
    getter_AddRefs(brandBundle));
  NS_ENSURE_TRUE(brandBundle, E_FAIL);
  if(brandBundle) {
    brandBundle->GetStringFromName(MOZ_UTF16("brandFullName"),
                                   getter_Copies(brandName));
  }

  // Set these properties at the end.  Otherwise users can get a
  // "There was a problem with the data package" error when there
  // is simply nothing to share.
  props->put_ApplicationName(HStringReference(brandName.BeginReading()).Get());
  if (title.Length()) {
    props->put_Title(HStringReference(title.BeginReading()).Get());
  } else {
    props->put_Title(HStringReference(brandName.BeginReading()).Get());
  }
  props->put_Description(HStringReference(url.BeginReading()).Get());

  return S_OK;
}
Пример #22
0
// Draws the scene.
void Game::Render()
{
    // Don't try to render anything before the first Update.
    if (m_timer.GetFrameCount() == 0)
    {
        return;
    }

    // Prepare the command list to render a new frame.
    m_deviceResources->Prepare();
    Clear();

    auto commandList = m_deviceResources->GetCommandList();
    PIXBeginEvent(commandList, PIX_COLOR_DEFAULT, L"Render");

    // Set the descriptor heaps
    ID3D12DescriptorHeap* heaps[] = { m_resourceDescriptors->Heap(), m_states->Heap() };
    commandList->SetDescriptorHeaps(_countof(heaps), heaps);

    auto t = static_cast<float>(m_timer.GetTotalSeconds());

    // Cube 1
    XMMATRIX world = XMMatrixRotationY(t) * XMMatrixTranslation(1.5f, -2.1f, (dist / 2.f) + dist * sin(t));
    m_effect->SetWorld(world);
    m_effect->SetTexture(m_resourceDescriptors->GetGpuHandle(Descriptors::Earth), m_states->LinearClamp());
    m_effect->Apply(commandList);
    m_cube->Draw(commandList);

    // Cube 2
    world = XMMatrixRotationY(-t) * XMMatrixTranslation(1.5f, 0, (dist / 2.f) + dist * sin(t));
    m_effect->SetWorld(world);
    m_effect->SetTexture(m_resourceDescriptors->GetGpuHandle(Descriptors::Windows95_sRGB), m_states->LinearClamp());
    m_effect->Apply(commandList);
    m_cube->Draw(commandList);

    // Cube 3
    world = XMMatrixRotationY(t) * XMMatrixTranslation(1.5f, 2.1f, (dist / 2.f) + dist * sin(t));
    m_effect->SetWorld(world);
    m_effect->SetTexture(m_resourceDescriptors->GetGpuHandle(Descriptors::Windows95), m_states->LinearClamp());
    m_effect->Apply(commandList);
    m_cube->Draw(commandList);

    // Cube 4
    world = XMMatrixRotationY(-t) * XMMatrixTranslation(-1.5f, -2.1f, (dist / 2.f) + dist * sin(t));
    m_effect->SetWorld(world);
    m_effect->SetTexture(m_resourceDescriptors->GetGpuHandle(Descriptors::Earth_Imm), m_states->LinearClamp());
    m_effect->Apply(commandList);
    m_cube->Draw(commandList);

    // Cube 5
    world = XMMatrixRotationY(t) * XMMatrixTranslation(-1.5f, 0, (dist / 2.f) + dist * sin(t));
    m_effect->SetWorld(world);
    m_effect->SetTexture(m_resourceDescriptors->GetGpuHandle(Descriptors::DirectXLogo_BC1), m_states->LinearClamp());
    m_effect->Apply(commandList);
    m_cube->Draw(commandList);

    // Cube 6
    world = XMMatrixRotationY(-t) * XMMatrixTranslation(-1.5f, 2.1f, (dist / 2.f) + dist * sin(t));
    m_effect->SetWorld(world);
    m_effect->SetTexture(m_resourceDescriptors->GetGpuHandle(Descriptors::DirectXLogo), m_states->LinearClamp());
    m_effect->Apply(commandList);
    m_cube->Draw(commandList);

    PIXEndEvent(commandList);

    if (m_frame == 10)
    {
        m_screenshot = m_deviceResources->GetRenderTarget();
    }

    // Show the new frame.
    PIXBeginEvent(m_deviceResources->GetCommandQueue(), PIX_COLOR_DEFAULT, L"Present");
    m_deviceResources->Present();
    m_graphicsMemory->Commit(m_deviceResources->GetCommandQueue());
    PIXEndEvent(m_deviceResources->GetCommandQueue());

    if (m_screenshot)
    {
        // We take the shot here to cope with lost device

        OutputDebugStringA("******** SCREENSHOT TEST BEGIN *************\n");

        bool success = true;

#if defined(_XBOX_ONE) && defined(_TITLE)
        const wchar_t sspath[MAX_PATH] = L"T:\\";
#elif defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
        wchar_t sspath[MAX_PATH] = {};

        using namespace Microsoft::WRL;
        using namespace Microsoft::WRL::Wrappers;
        using namespace ABI::Windows::Foundation;

        ComPtr<ABI::Windows::Storage::IApplicationDataStatics> appStatics;
        DX::ThrowIfFailed(GetActivationFactory(HStringReference(RuntimeClass_Windows_Storage_ApplicationData).Get(), appStatics.GetAddressOf()));

        ComPtr<ABI::Windows::Storage::IApplicationData> appData;
        DX::ThrowIfFailed(appStatics->get_Current(appData.GetAddressOf()));

        // Temporary folder
        {
            ComPtr<ABI::Windows::Storage::IStorageFolder> folder;
            DX::ThrowIfFailed(appData->get_TemporaryFolder(folder.GetAddressOf()));

            ComPtr<ABI::Windows::Storage::IStorageItem> item;
            DX::ThrowIfFailed(folder.As(&item));

            HString folderName;
            DX::ThrowIfFailed(item->get_Path(folderName.GetAddressOf()));

            unsigned int len;
            PCWSTR szPath = folderName.GetRawBuffer(&len);
            if (wcscpy_s(sspath, MAX_PATH, szPath) > 0
                || wcscat_s(sspath, L"\\") > 0)
            {
                throw std::exception("TemporaryFolder");
            }
        }
#else
        const wchar_t sspath[MAX_PATH] = L".";
#endif

        OutputDebugStringA("Output path: ");
        OutputDebugStringW(sspath);
        OutputDebugStringA("\n");

        wchar_t sspng[MAX_PATH] = {};
        wchar_t ssjpg[MAX_PATH] = {};
        wchar_t ssbmp[MAX_PATH] = {};
        wchar_t sstif[MAX_PATH] = {};
        wchar_t ssdds[MAX_PATH] = {};

        swprintf_s(sspng, L"%ls\\SCREENSHOT.PNG", sspath);
        swprintf_s(ssjpg, L"%ls\\SCREENSHOT.JPG", sspath);
        swprintf_s(ssbmp, L"%ls\\SCREENSHOT.BMP", sspath);
        swprintf_s(sstif, L"%ls\\SCREENSHOT.TIF", sspath);
        swprintf_s(ssdds, L"%ls\\SCREENSHOT.DDS", sspath);

        DeleteFileW(sspng);
        DeleteFileW(ssjpg);
        DeleteFileW(ssbmp);
        DeleteFileW(sstif);
        DeleteFileW(ssdds);

        HRESULT hr = SaveWICTextureToFile(m_deviceResources->GetCommandQueue(), m_screenshot.Get(),
            GUID_ContainerFormatPng, sspng,
            D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_PRESENT, &GUID_WICPixelFormat32bppBGRA);

        if (FAILED(hr))
        {
            char buff[128] = {};
            sprintf_s(buff, "ERROR: SaveWICTextureToFile (PNG) failed %08X\n", hr);
            OutputDebugStringA(buff);
            success = false;
        }
        else if (GetFileAttributesW(sspng) != INVALID_FILE_ATTRIBUTES)
        {
            OutputDebugStringA("Wrote SCREENSHOT.PNG\n");
        }
        else
        {
            OutputDebugStringA("ERROR: Missing SCREENSHOT.PNG!\n");
            success = false;
        }

        hr = SaveWICTextureToFile(m_deviceResources->GetCommandQueue(), m_screenshot.Get(),
            GUID_ContainerFormatJpeg, ssjpg,
            D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_PRESENT);

        if (FAILED(hr))
        {
            char buff[128] = {};
            sprintf_s(buff, "ERROR: SaveWICTextureToFile (JPG) failed %08X\n", hr);
            OutputDebugStringA(buff);
            success = false;
        }
        else if (GetFileAttributesW(ssjpg) != INVALID_FILE_ATTRIBUTES)
        {
            OutputDebugStringA("Wrote SCREENSHOT.JPG\n");
        }
        else
        {
            OutputDebugStringA("ERROR: Missing SCREENSHOT.JPG!\n");
            success = false;
        }

        hr = SaveWICTextureToFile(m_deviceResources->GetCommandQueue(), m_screenshot.Get(),
            GUID_ContainerFormatBmp, ssbmp,
            D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_PRESENT,
            &GUID_WICPixelFormat16bppBGR565);

        if (FAILED(hr))
        {
            char buff[128] = {};
            sprintf_s(buff, "ERROR: SaveWICTextureToFile (BMP) failed %08X\n", hr);
            OutputDebugStringA(buff);
            success = false;
        }
        else if (GetFileAttributesW(ssbmp) != INVALID_FILE_ATTRIBUTES)
        {
            OutputDebugStringA("Wrote SCREENSHOT.BMP\n");
        }
        else
        {
            OutputDebugStringA("ERROR: Missing SCREENSHOT.BMP!\n");
            success = false;
        }

        hr = SaveWICTextureToFile(m_deviceResources->GetCommandQueue(), m_screenshot.Get(),
            GUID_ContainerFormatTiff, sstif,
            D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_PRESENT,
            nullptr,
            [&](IPropertyBag2* props)
        {
            PROPBAG2 options[2] = { 0, 0 };
            options[0].pstrName = const_cast<wchar_t*>(L"CompressionQuality");
            options[1].pstrName = const_cast<wchar_t*>(L"TiffCompressionMethod");

            VARIANT varValues[2];
            varValues[0].vt = VT_R4;
            varValues[0].fltVal = 0.75f;

            varValues[1].vt = VT_UI1;
            varValues[1].bVal = WICTiffCompressionNone;

            (void)props->Write(2, options, varValues);
        });

        if (FAILED(hr))
        {
            char buff[128] = {};
            sprintf_s(buff, "ERROR: SaveWICTextureToFile (TIFF) failed %08X\n", hr);
            OutputDebugStringA(buff);
            success = false;
        }
        else if (GetFileAttributesW(sstif) != INVALID_FILE_ATTRIBUTES)
        {
            OutputDebugStringA("Wrote SCREENSHOT.TIF\n");
        }
        else
        {
            OutputDebugStringA("ERROR: Missing SCREENSHOT.TIF!\n");
            success = false;
        }

        hr = SaveDDSTextureToFile(m_deviceResources->GetCommandQueue(), m_screenshot.Get(), ssdds,
            D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_PRESENT);

        if (FAILED(hr))
        {
            char buff[128] = {};
            sprintf_s(buff, "ERROR: SaveWICTextureToFile (DDS) failed %08X\n", hr);
            OutputDebugStringA(buff);
            success = false;
        }
        else if (GetFileAttributesW(ssdds) != INVALID_FILE_ATTRIBUTES)
        {
            OutputDebugStringA("Wrote SCREENSHOT.DDS\n");
        }
        else
        {
            OutputDebugStringA("ERROR: Missing SCREENSHOT.DDS!\n");
            success = false;
        }

        // TODO - pass in D3D12_HEAP_TYPE_READBACK resource

        // ScreenGrab of an MSAA resource is tested elsewhere

        OutputDebugStringA(success ? "Passed\n" : "Failed\n");
        OutputDebugStringA("********* SCREENSHOT TEST END **************\n");
        m_screenshot.Reset();
    }
}