Windows: centralize how we handle error messages

Currently QtBase contains multiple implementation of how to get the Win32
and COM error messages, and they are almost exactly the same, what's worse,
Qt already has a private QSystemError class to do such things, so we are
re-inventing the wheel in many places. This patch removes all other custom
error message implementations besides the QSystemError one. And since there
are a lot of places need the COM error message, move the implementation to
QSystemError so that it can handle both Win32 error and COM error.

Since I'm touching these lines anyway, break them into short lines if they
are above the length limit.

Change-Id: I1067c874011800303f0f114b5cb8830ac6810fc0
Reviewed-by: Mårten Nordheim <marten.nordheim@qt.io>
This commit is contained in:
Yuhang Zhao 2022-10-26 13:34:35 +08:00
parent e2f895db2e
commit bd7fa4a537
12 changed files with 151 additions and 228 deletions

View File

@ -9,6 +9,7 @@
#ifdef Q_OS_WIN
# include <qt_windows.h>
# include <private/qsystemerror_p.h>
#else
# include <sys/types.h>
# include <sys/stat.h>
@ -212,23 +213,6 @@ QString IoUtils::shellQuoteWin(const QString &arg)
#if defined(PROEVALUATOR_FULL)
# if defined(Q_OS_WIN)
static QString windowsErrorCode()
{
wchar_t *string = nullptr;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPWSTR)&string,
0,
NULL);
QString ret = QString::fromWCharArray(string);
LocalFree((HLOCAL)string);
return ret.trimmed();
}
# endif
bool IoUtils::touchFile(const QString &targetFileName, const QString &referenceFileName, QString *errorString)
{
# ifdef Q_OS_UNIX
@ -255,7 +239,8 @@ bool IoUtils::touchFile(const QString &targetFileName, const QString &referenceF
GENERIC_READ, FILE_SHARE_READ,
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (rHand == INVALID_HANDLE_VALUE) {
*errorString = fL1S("Cannot open reference file %1: %2").arg(referenceFileName, windowsErrorCode());
*errorString = fL1S("Cannot open reference file %1: %2")
.arg(referenceFileName, QSystemError::windowsString());
return false;
}
FILETIME ft;
@ -265,7 +250,8 @@ bool IoUtils::touchFile(const QString &targetFileName, const QString &referenceF
GENERIC_WRITE, FILE_SHARE_READ,
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (wHand == INVALID_HANDLE_VALUE) {
*errorString = fL1S("Cannot open %1: %2").arg(targetFileName, windowsErrorCode());
*errorString = fL1S("Cannot open %1: %2")
.arg(targetFileName, QSystemError::windowsString());
return false;
}
SetFileTime(wHand, NULL, NULL, &ft);

View File

@ -9,6 +9,7 @@
#endif
#ifdef Q_OS_WIN
# include <qt_windows.h>
# include <comdef.h>
#endif
#ifndef QT_BOOTSTRAPPED
# include <qcoreapplication.h>
@ -46,7 +47,7 @@ static QString windowsErrorString(int errorCode)
{
QString ret;
wchar_t *string = nullptr;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
errorCode,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
@ -133,6 +134,15 @@ QString QSystemError::windowsString(int errorCode)
return windowsErrorString(errorCode == -1 ? GetLastError() : errorCode);
}
QString QSystemError::windowsComString(HRESULT hr)
{
const _com_error comError(hr);
QString result = "COM error 0x"_L1 + QString::number(ulong(hr), 16);
if (const wchar_t *msg = comError.ErrorMessage())
result += ": "_L1 + QString::fromWCharArray(msg);
return result;
}
QString qt_error_string(int code)
{
return windowsErrorString(code == -1 ? GetLastError() : code);

View File

@ -44,6 +44,8 @@ public:
static Q_CORE_EXPORT QString stdString(int errorCode = -1);
#ifdef Q_OS_WIN
static Q_CORE_EXPORT QString windowsString(int errorCode = -1);
using HRESULT = long;
static Q_CORE_EXPORT QString windowsComString(HRESULT hr);
#endif
// data members

View File

@ -9,9 +9,9 @@
#include <qmath.h>
#include <private/qsystemlibrary_p.h>
#include <QtCore/qcryptographichash.h>
#include <QtCore/private/qsystemerror_p.h>
#include <d3dcompiler.h>
#include <comdef.h>
QT_BEGIN_NAMESPACE
@ -123,15 +123,6 @@ QRhiD3D11::QRhiD3D11(QRhiD3D11InitParams *params, QRhiD3D11NativeHandles *import
}
}
static QString comErrorMessage(HRESULT hr)
{
const _com_error comError(hr);
QString result = "Error 0x"_L1 + QString::number(ulong(hr), 16);
if (const wchar_t *msg = comError.ErrorMessage())
result += ": "_L1 + QString::fromWCharArray(msg);
return result;
}
template <class Int>
inline Int aligned(Int v, Int byteAlign)
{
@ -143,7 +134,8 @@ static IDXGIFactory1 *createDXGIFactory2()
IDXGIFactory1 *result = nullptr;
const HRESULT hr = CreateDXGIFactory2(0, __uuidof(IDXGIFactory2), reinterpret_cast<void **>(&result));
if (FAILED(hr)) {
qWarning("CreateDXGIFactory2() failed to create DXGI factory: %s", qPrintable(comErrorMessage(hr)));
qWarning("CreateDXGIFactory2() failed to create DXGI factory: %s",
qPrintable(QSystemError::windowsComString(hr)));
result = nullptr;
}
return result;
@ -271,7 +263,8 @@ bool QRhiD3D11::create(QRhi::Flags flags)
&dev, &featureLevel, &ctx);
}
if (FAILED(hr)) {
qWarning("Failed to create D3D11 device and context: %s", qPrintable(comErrorMessage(hr)));
qWarning("Failed to create D3D11 device and context: %s",
qPrintable(QSystemError::windowsComString(hr)));
return false;
}
@ -1318,7 +1311,8 @@ QRhi::FrameOpResult QRhiD3D11::endFrame(QRhiSwapChain *swapChain, QRhi::EndFrame
deviceLost = true;
return QRhi::FrameOpDeviceLost;
} else if (FAILED(hr)) {
qWarning("Failed to present: %s", qPrintable(comErrorMessage(hr)));
qWarning("Failed to present: %s",
qPrintable(QSystemError::windowsComString(hr)));
return QRhi::FrameOpError;
}
@ -1648,7 +1642,8 @@ void QRhiD3D11::enqueueResourceUpdates(QRhiCommandBuffer *cb, QRhiResourceUpdate
desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
HRESULT hr = dev->CreateBuffer(&desc, nullptr, &readback.stagingBuf);
if (FAILED(hr)) {
qWarning("Failed to create buffer: %s", qPrintable(comErrorMessage(hr)));
qWarning("Failed to create buffer: %s",
qPrintable(QSystemError::windowsComString(hr)));
continue;
}
@ -1778,7 +1773,8 @@ void QRhiD3D11::enqueueResourceUpdates(QRhiCommandBuffer *cb, QRhiResourceUpdate
ID3D11Texture2D *stagingTex;
HRESULT hr = dev->CreateTexture2D(&desc, nullptr, &stagingTex);
if (FAILED(hr)) {
qWarning("Failed to create readback staging texture: %s", qPrintable(comErrorMessage(hr)));
qWarning("Failed to create readback staging texture: %s",
qPrintable(QSystemError::windowsComString(hr)));
return;
}
@ -1845,7 +1841,8 @@ void QRhiD3D11::finishActiveReadbacks()
}
context->Unmap(readback.stagingTex, 0);
} else {
qWarning("Failed to map readback staging texture: %s", qPrintable(comErrorMessage(hr)));
qWarning("Failed to map readback staging texture: %s",
qPrintable(QSystemError::windowsComString(hr)));
}
readback.stagingTex->Release();
@ -1866,7 +1863,8 @@ void QRhiD3D11::finishActiveReadbacks()
memcpy(readback.result->data.data(), mp.pData, readback.byteSize);
context->Unmap(readback.stagingBuf, 0);
} else {
qWarning("Failed to map readback staging texture: %s", qPrintable(comErrorMessage(hr)));
qWarning("Failed to map readback staging texture: %s",
qPrintable(QSystemError::windowsComString(hr)));
}
readback.stagingBuf->Release();
@ -2390,7 +2388,8 @@ void QRhiD3D11::executeBufferHostWrites(QD3D11Buffer *bufD)
memcpy(mp.pData, bufD->dynBuf, bufD->m_size);
context->Unmap(bufD->buffer, 0);
} else {
qWarning("Failed to map buffer: %s", qPrintable(comErrorMessage(hr)));
qWarning("Failed to map buffer: %s",
qPrintable(QSystemError::windowsComString(hr)));
}
}
@ -2861,7 +2860,8 @@ bool QD3D11Buffer::create()
QRHI_RES_RHI(QRhiD3D11);
HRESULT hr = rhiD->dev->CreateBuffer(&desc, nullptr, &buffer);
if (FAILED(hr)) {
qWarning("Failed to create buffer: %s", qPrintable(comErrorMessage(hr)));
qWarning("Failed to create buffer: %s",
qPrintable(QSystemError::windowsComString(hr)));
return false;
}
@ -2900,7 +2900,8 @@ char *QD3D11Buffer::beginFullDynamicBufferUpdateForCurrentFrame()
QRHI_RES_RHI(QRhiD3D11);
HRESULT hr = rhiD->context->Map(buffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mp);
if (FAILED(hr)) {
qWarning("Failed to map buffer: %s", qPrintable(comErrorMessage(hr)));
qWarning("Failed to map buffer: %s",
qPrintable(QSystemError::windowsComString(hr)));
return nullptr;
}
return static_cast<char *>(mp.pData);
@ -2928,7 +2929,8 @@ ID3D11UnorderedAccessView *QD3D11Buffer::unorderedAccessView()
QRHI_RES_RHI(QRhiD3D11);
HRESULT hr = rhiD->dev->CreateUnorderedAccessView(buffer, &desc, &uav);
if (FAILED(hr)) {
qWarning("Failed to create UAV: %s", qPrintable(comErrorMessage(hr)));
qWarning("Failed to create UAV: %s",
qPrintable(QSystemError::windowsComString(hr)));
return nullptr;
}
@ -2996,7 +2998,8 @@ bool QD3D11RenderBuffer::create()
desc.BindFlags = D3D11_BIND_RENDER_TARGET;
HRESULT hr = rhiD->dev->CreateTexture2D(&desc, nullptr, &tex);
if (FAILED(hr)) {
qWarning("Failed to create color renderbuffer: %s", qPrintable(comErrorMessage(hr)));
qWarning("Failed to create color renderbuffer: %s",
qPrintable(QSystemError::windowsComString(hr)));
return false;
}
D3D11_RENDER_TARGET_VIEW_DESC rtvDesc = {};
@ -3005,7 +3008,8 @@ bool QD3D11RenderBuffer::create()
: D3D11_RTV_DIMENSION_TEXTURE2D;
hr = rhiD->dev->CreateRenderTargetView(tex, &rtvDesc, &rtv);
if (FAILED(hr)) {
qWarning("Failed to create rtv: %s", qPrintable(comErrorMessage(hr)));
qWarning("Failed to create rtv: %s",
qPrintable(QSystemError::windowsComString(hr)));
return false;
}
} else if (m_type == DepthStencil) {
@ -3014,7 +3018,8 @@ bool QD3D11RenderBuffer::create()
desc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
HRESULT hr = rhiD->dev->CreateTexture2D(&desc, nullptr, &tex);
if (FAILED(hr)) {
qWarning("Failed to create depth-stencil buffer: %s", qPrintable(comErrorMessage(hr)));
qWarning("Failed to create depth-stencil buffer: %s",
qPrintable(QSystemError::windowsComString(hr)));
return false;
}
D3D11_DEPTH_STENCIL_VIEW_DESC dsvDesc = {};
@ -3023,7 +3028,8 @@ bool QD3D11RenderBuffer::create()
: D3D11_DSV_DIMENSION_TEXTURE2D;
hr = rhiD->dev->CreateDepthStencilView(tex, &dsvDesc, &dsv);
if (FAILED(hr)) {
qWarning("Failed to create dsv: %s", qPrintable(comErrorMessage(hr)));
qWarning("Failed to create dsv: %s",
qPrintable(QSystemError::windowsComString(hr)));
return false;
}
} else {
@ -3268,7 +3274,8 @@ bool QD3D11Texture::finishCreate()
HRESULT hr = rhiD->dev->CreateShaderResourceView(textureResource(), &srvDesc, &srv);
if (FAILED(hr)) {
qWarning("Failed to create srv: %s", qPrintable(comErrorMessage(hr)));
qWarning("Failed to create srv: %s",
qPrintable(QSystemError::windowsComString(hr)));
return false;
}
@ -3320,7 +3327,8 @@ bool QD3D11Texture::create()
HRESULT hr = rhiD->dev->CreateTexture1D(&desc, nullptr, &tex1D);
if (FAILED(hr)) {
qWarning("Failed to create 1D texture: %s", qPrintable(comErrorMessage(hr)));
qWarning("Failed to create 1D texture: %s",
qPrintable(QSystemError::windowsComString(hr)));
return false;
}
if (!m_objectName.isEmpty())
@ -3340,7 +3348,8 @@ bool QD3D11Texture::create()
HRESULT hr = rhiD->dev->CreateTexture2D(&desc, nullptr, &tex);
if (FAILED(hr)) {
qWarning("Failed to create 2D texture: %s", qPrintable(comErrorMessage(hr)));
qWarning("Failed to create 2D texture: %s",
qPrintable(QSystemError::windowsComString(hr)));
return false;
}
if (!m_objectName.isEmpty())
@ -3358,7 +3367,8 @@ bool QD3D11Texture::create()
HRESULT hr = rhiD->dev->CreateTexture3D(&desc, nullptr, &tex3D);
if (FAILED(hr)) {
qWarning("Failed to create 3D texture: %s", qPrintable(comErrorMessage(hr)));
qWarning("Failed to create 3D texture: %s",
qPrintable(QSystemError::windowsComString(hr)));
return false;
}
if (!m_objectName.isEmpty())
@ -3434,7 +3444,8 @@ ID3D11UnorderedAccessView *QD3D11Texture::unorderedAccessViewForLevel(int level)
ID3D11UnorderedAccessView *uav = nullptr;
HRESULT hr = rhiD->dev->CreateUnorderedAccessView(textureResource(), &desc, &uav);
if (FAILED(hr)) {
qWarning("Failed to create UAV: %s", qPrintable(comErrorMessage(hr)));
qWarning("Failed to create UAV: %s",
qPrintable(QSystemError::windowsComString(hr)));
return nullptr;
}
@ -3557,7 +3568,8 @@ bool QD3D11Sampler::create()
QRHI_RES_RHI(QRhiD3D11);
HRESULT hr = rhiD->dev->CreateSamplerState(&desc, &samplerState);
if (FAILED(hr)) {
qWarning("Failed to create sampler state: %s", qPrintable(comErrorMessage(hr)));
qWarning("Failed to create sampler state: %s",
qPrintable(QSystemError::windowsComString(hr)));
return false;
}
@ -3740,7 +3752,8 @@ bool QD3D11TextureRenderTarget::create()
}
HRESULT hr = rhiD->dev->CreateRenderTargetView(texD->textureResource(), &rtvDesc, &rtv[attIndex]);
if (FAILED(hr)) {
qWarning("Failed to create rtv: %s", qPrintable(comErrorMessage(hr)));
qWarning("Failed to create rtv: %s",
qPrintable(QSystemError::windowsComString(hr)));
return false;
}
ownsRtv[attIndex] = true;
@ -3770,7 +3783,8 @@ bool QD3D11TextureRenderTarget::create()
: D3D11_DSV_DIMENSION_TEXTURE2D;
HRESULT hr = rhiD->dev->CreateDepthStencilView(depthTexD->tex, &dsvDesc, &dsv);
if (FAILED(hr)) {
qWarning("Failed to create dsv: %s", qPrintable(comErrorMessage(hr)));
qWarning("Failed to create dsv: %s",
qPrintable(QSystemError::windowsComString(hr)));
return false;
}
if (d.colorAttCount == 0) {
@ -4299,7 +4313,8 @@ bool QD3D11GraphicsPipeline::create()
rastDesc.MultisampleEnable = rhiD->effectiveSampleCount(m_sampleCount).Count > 1;
HRESULT hr = rhiD->dev->CreateRasterizerState(&rastDesc, &rastState);
if (FAILED(hr)) {
qWarning("Failed to create rasterizer state: %s", qPrintable(comErrorMessage(hr)));
qWarning("Failed to create rasterizer state: %s",
qPrintable(QSystemError::windowsComString(hr)));
return false;
}
@ -4322,7 +4337,8 @@ bool QD3D11GraphicsPipeline::create()
}
hr = rhiD->dev->CreateDepthStencilState(&dsDesc, &dsState);
if (FAILED(hr)) {
qWarning("Failed to create depth-stencil state: %s", qPrintable(comErrorMessage(hr)));
qWarning("Failed to create depth-stencil state: %s",
qPrintable(QSystemError::windowsComString(hr)));
return false;
}
@ -4348,7 +4364,8 @@ bool QD3D11GraphicsPipeline::create()
}
hr = rhiD->dev->CreateBlendState(&blendDesc, &blendState);
if (FAILED(hr)) {
qWarning("Failed to create blend state: %s", qPrintable(comErrorMessage(hr)));
qWarning("Failed to create blend state: %s",
qPrintable(QSystemError::windowsComString(hr)));
return false;
}
@ -4409,7 +4426,8 @@ bool QD3D11GraphicsPipeline::create()
case QRhiShaderStage::Vertex:
hr = rhiD->dev->CreateVertexShader(bytecode.constData(), SIZE_T(bytecode.size()), nullptr, &vs.shader);
if (FAILED(hr)) {
qWarning("Failed to create vertex shader: %s", qPrintable(comErrorMessage(hr)));
qWarning("Failed to create vertex shader: %s",
qPrintable(QSystemError::windowsComString(hr)));
return false;
}
vsByteCode = bytecode;
@ -4420,7 +4438,8 @@ bool QD3D11GraphicsPipeline::create()
case QRhiShaderStage::TessellationControl:
hr = rhiD->dev->CreateHullShader(bytecode.constData(), SIZE_T(bytecode.size()), nullptr, &hs.shader);
if (FAILED(hr)) {
qWarning("Failed to create hull shader: %s", qPrintable(comErrorMessage(hr)));
qWarning("Failed to create hull shader: %s",
qPrintable(QSystemError::windowsComString(hr)));
return false;
}
hs.nativeResourceBindingMap = shaderStage.shader().nativeResourceBindingMap(shaderKey);
@ -4430,7 +4449,8 @@ bool QD3D11GraphicsPipeline::create()
case QRhiShaderStage::TessellationEvaluation:
hr = rhiD->dev->CreateDomainShader(bytecode.constData(), SIZE_T(bytecode.size()), nullptr, &ds.shader);
if (FAILED(hr)) {
qWarning("Failed to create domain shader: %s", qPrintable(comErrorMessage(hr)));
qWarning("Failed to create domain shader: %s",
qPrintable(QSystemError::windowsComString(hr)));
return false;
}
ds.nativeResourceBindingMap = shaderStage.shader().nativeResourceBindingMap(shaderKey);
@ -4440,7 +4460,8 @@ bool QD3D11GraphicsPipeline::create()
case QRhiShaderStage::Geometry:
hr = rhiD->dev->CreateGeometryShader(bytecode.constData(), SIZE_T(bytecode.size()), nullptr, &gs.shader);
if (FAILED(hr)) {
qWarning("Failed to create geometry shader: %s", qPrintable(comErrorMessage(hr)));
qWarning("Failed to create geometry shader: %s",
qPrintable(QSystemError::windowsComString(hr)));
return false;
}
gs.nativeResourceBindingMap = shaderStage.shader().nativeResourceBindingMap(shaderKey);
@ -4450,7 +4471,8 @@ bool QD3D11GraphicsPipeline::create()
case QRhiShaderStage::Fragment:
hr = rhiD->dev->CreatePixelShader(bytecode.constData(), SIZE_T(bytecode.size()), nullptr, &fs.shader);
if (FAILED(hr)) {
qWarning("Failed to create pixel shader: %s", qPrintable(comErrorMessage(hr)));
qWarning("Failed to create pixel shader: %s",
qPrintable(QSystemError::windowsComString(hr)));
return false;
}
fs.nativeResourceBindingMap = shaderStage.shader().nativeResourceBindingMap(shaderKey);
@ -4504,7 +4526,8 @@ bool QD3D11GraphicsPipeline::create()
hr = rhiD->dev->CreateInputLayout(inputDescs.constData(), UINT(inputDescs.count()),
vsByteCode, SIZE_T(vsByteCode.size()), &inputLayout);
if (FAILED(hr)) {
qWarning("Failed to create input layout: %s", qPrintable(comErrorMessage(hr)));
qWarning("Failed to create input layout: %s",
qPrintable(QSystemError::windowsComString(hr)));
return false;
}
} // else leave inputLayout set to nullptr; that's valid and it avoids a debug layer warning about an input layout with 0 elements
@ -4568,7 +4591,8 @@ bool QD3D11ComputePipeline::create()
HRESULT hr = rhiD->dev->CreateComputeShader(bytecode.constData(), SIZE_T(bytecode.size()), nullptr, &cs.shader);
if (FAILED(hr)) {
qWarning("Failed to create compute shader: %s", qPrintable(comErrorMessage(hr)));
qWarning("Failed to create compute shader: %s",
qPrintable(QSystemError::windowsComString(hr)));
return false;
}
@ -4796,7 +4820,8 @@ bool QD3D11SwapChain::newColorBuffer(const QSize &size, DXGI_FORMAT format, DXGI
QRHI_RES_RHI(QRhiD3D11);
HRESULT hr = rhiD->dev->CreateTexture2D(&desc, nullptr, tex);
if (FAILED(hr)) {
qWarning("Failed to create color buffer texture: %s", qPrintable(comErrorMessage(hr)));
qWarning("Failed to create color buffer texture: %s",
qPrintable(QSystemError::windowsComString(hr)));
return false;
}
@ -4805,7 +4830,8 @@ bool QD3D11SwapChain::newColorBuffer(const QSize &size, DXGI_FORMAT format, DXGI
rtvDesc.ViewDimension = sampleDesc.Count > 1 ? D3D11_RTV_DIMENSION_TEXTURE2DMS : D3D11_RTV_DIMENSION_TEXTURE2D;
hr = rhiD->dev->CreateRenderTargetView(*tex, &rtvDesc, rtv);
if (FAILED(hr)) {
qWarning("Failed to create color buffer rtv: %s", qPrintable(comErrorMessage(hr)));
qWarning("Failed to create color buffer rtv: %s",
qPrintable(QSystemError::windowsComString(hr)));
(*tex)->Release();
*tex = nullptr;
return false;
@ -4826,7 +4852,8 @@ bool QRhiD3D11::ensureDirectCompositionDevice()
HRESULT hr = DCompositionCreateDevice(nullptr, __uuidof(IDCompositionDevice), reinterpret_cast<void **>(&dcompDevice));
if (FAILED(hr)) {
qWarning("Failed to Direct Composition device: %s", qPrintable(comErrorMessage(hr)));
qWarning("Failed to Direct Composition device: %s",
qPrintable(QSystemError::windowsComString(hr)));
return false;
}
@ -4863,14 +4890,14 @@ bool QD3D11SwapChain::createOrResize()
hr = rhiD->dcompDevice->CreateTargetForHwnd(hwnd, true, &dcompTarget);
if (FAILED(hr)) {
qWarning("Failed to create Direct Compsition target for the window: %s",
qPrintable(comErrorMessage(hr)));
qPrintable(QSystemError::windowsComString(hr)));
}
}
if (dcompTarget && !dcompVisual) {
hr = rhiD->dcompDevice->CreateVisual(&dcompVisual);
if (FAILED(hr)) {
qWarning("Failed to create DirectComposition visual: %s",
qPrintable(comErrorMessage(hr)));
qPrintable(QSystemError::windowsComString(hr)));
}
}
}
@ -4979,7 +5006,8 @@ bool QD3D11SwapChain::createOrResize()
if (SUCCEEDED(sc1->QueryInterface(__uuidof(IDXGISwapChain3), reinterpret_cast<void **>(&sc3)))) {
hr = sc3->SetColorSpace1(hdrColorSpace);
if (FAILED(hr))
qWarning("Failed to set color space on swapchain: %s", qPrintable(comErrorMessage(hr)));
qWarning("Failed to set color space on swapchain: %s",
qPrintable(QSystemError::windowsComString(hr)));
sc3->Release();
} else {
qWarning("IDXGISwapChain3 not available, HDR swapchain will not work as expected");
@ -4991,16 +5019,17 @@ bool QD3D11SwapChain::createOrResize()
hr = dcompTarget->SetRoot(dcompVisual);
if (FAILED(hr)) {
qWarning("Failed to associate Direct Composition visual with the target: %s",
qPrintable(comErrorMessage(hr)));
qPrintable(QSystemError::windowsComString(hr)));
}
} else {
qWarning("Failed to set content for Direct Composition visual: %s",
qPrintable(comErrorMessage(hr)));
qPrintable(QSystemError::windowsComString(hr)));
}
}
}
if (FAILED(hr)) {
qWarning("Failed to create D3D11 swapchain: %s", qPrintable(comErrorMessage(hr)));
qWarning("Failed to create D3D11 swapchain: %s",
qPrintable(QSystemError::windowsComString(hr)));
return false;
}
rhiD->dxgiFactory->MakeWindowAssociation(hwnd, DXGI_MWA_NO_WINDOW_CHANGES);
@ -5014,7 +5043,8 @@ bool QD3D11SwapChain::createOrResize()
rhiD->deviceLost = true;
return false;
} else if (FAILED(hr)) {
qWarning("Failed to resize D3D11 swapchain: %s", qPrintable(comErrorMessage(hr)));
qWarning("Failed to resize D3D11 swapchain: %s",
qPrintable(QSystemError::windowsComString(hr)));
return false;
}
}
@ -5035,7 +5065,8 @@ bool QD3D11SwapChain::createOrResize()
// So just query index 0 once (per resize) and be done with it.
hr = swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void **>(&backBufferTex));
if (FAILED(hr)) {
qWarning("Failed to query swapchain backbuffer: %s", qPrintable(comErrorMessage(hr)));
qWarning("Failed to query swapchain backbuffer: %s",
qPrintable(QSystemError::windowsComString(hr)));
return false;
}
D3D11_RENDER_TARGET_VIEW_DESC rtvDesc = {};
@ -5043,7 +5074,8 @@ bool QD3D11SwapChain::createOrResize()
rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
hr = rhiD->dev->CreateRenderTargetView(backBufferTex, &rtvDesc, &backBufferRtv);
if (FAILED(hr)) {
qWarning("Failed to create rtv for swapchain backbuffer: %s", qPrintable(comErrorMessage(hr)));
qWarning("Failed to create rtv for swapchain backbuffer: %s",
qPrintable(QSystemError::windowsComString(hr)));
return false;
}
@ -5092,7 +5124,8 @@ bool QD3D11SwapChain::createOrResize()
queryDesc.Query = D3D11_QUERY_TIMESTAMP_DISJOINT;
hr = rhiD->dev->CreateQuery(&queryDesc, &timestampDisjointQuery[i]);
if (FAILED(hr)) {
qWarning("Failed to create timestamp disjoint query: %s", qPrintable(comErrorMessage(hr)));
qWarning("Failed to create timestamp disjoint query: %s",
qPrintable(QSystemError::windowsComString(hr)));
break;
}
}
@ -5102,7 +5135,8 @@ bool QD3D11SwapChain::createOrResize()
if (!timestampQuery[idx]) {
hr = rhiD->dev->CreateQuery(&queryDesc, &timestampQuery[idx]);
if (FAILED(hr)) {
qWarning("Failed to create timestamp query: %s", qPrintable(comErrorMessage(hr)));
qWarning("Failed to create timestamp query: %s",
qPrintable(QSystemError::windowsComString(hr)));
break;
}
}
@ -5123,7 +5157,8 @@ void QRhiD3D11::DeviceCurse::initResources()
HRESULT hr = q->dev->CreateComputeShader(g_killDeviceByTimingOut, sizeof(g_killDeviceByTimingOut), nullptr, &cs);
if (FAILED(hr)) {
qWarning("Failed to create compute shader: %s", qPrintable(comErrorMessage(hr)));
qWarning("Failed to create compute shader: %s",
qPrintable(QSystemError::windowsComString(hr)));
return;
}
}

View File

@ -9,6 +9,7 @@
#include <QtCore/qmetaobject.h>
#include <QtCore/private/qfunctions_win_p.h>
#include <QtCore/private/qsystemerror_p.h>
#include <QtNetwork/qnetworkinterface.h>
@ -16,7 +17,6 @@
#include <netlistmgr.h>
#include <wrl/client.h>
#include <wrl/wrappers/corewrappers.h>
#include <comdef.h>
#include <iphlpapi.h>
#include <algorithm>
@ -28,12 +28,6 @@ QT_BEGIN_NAMESPACE
Q_LOGGING_CATEGORY(lcNetMon, "qt.network.monitor");
namespace {
QString errorStringFromHResult(HRESULT hr)
{
_com_error error(hr);
return QString::fromWCharArray(error.ErrorMessage());
}
template<typename T>
bool QueryInterfaceImpl(IUnknown *from, REFIID riid, void **ppvObject)
{
@ -150,7 +144,7 @@ QNetworkConnectionEvents::QNetworkConnectionEvents(QNetworkConnectionMonitorPriv
IID_INetworkListManager, &networkListManager);
if (FAILED(hr)) {
qCDebug(lcNetMon) << "Could not get a NetworkListManager instance:"
<< errorStringFromHResult(hr);
<< QSystemError::windowsComString(hr);
return;
}
@ -162,7 +156,7 @@ QNetworkConnectionEvents::QNetworkConnectionEvents(QNetworkConnectionMonitorPriv
}
if (FAILED(hr)) {
qCDebug(lcNetMon) << "Failed to get connection point for network events:"
<< errorStringFromHResult(hr);
<< QSystemError::windowsComString(hr);
}
}
@ -177,7 +171,7 @@ ComPtr<INetworkConnection> QNetworkConnectionEvents::getNetworkConnectionFromAda
auto hr = networkListManager->GetNetworkConnections(connections.GetAddressOf());
if (FAILED(hr)) {
qCDebug(lcNetMon) << "Failed to enumerate network connections:"
<< errorStringFromHResult(hr);
<< QSystemError::windowsComString(hr);
return nullptr;
}
ComPtr<INetworkConnection> connection = nullptr;
@ -185,7 +179,7 @@ ComPtr<INetworkConnection> QNetworkConnectionEvents::getNetworkConnectionFromAda
hr = connections->Next(1, connection.GetAddressOf(), nullptr);
if (FAILED(hr)) {
qCDebug(lcNetMon) << "Failed to get next network connection in enumeration:"
<< errorStringFromHResult(hr);
<< QSystemError::windowsComString(hr);
break;
}
if (connection) {
@ -193,7 +187,7 @@ ComPtr<INetworkConnection> QNetworkConnectionEvents::getNetworkConnectionFromAda
hr = connection->GetAdapterId(&adapterId);
if (FAILED(hr)) {
qCDebug(lcNetMon) << "Failed to get adapter ID from network connection:"
<< errorStringFromHResult(hr);
<< QSystemError::windowsComString(hr);
continue;
}
if (guid == adapterId)
@ -258,7 +252,8 @@ bool QNetworkConnectionEvents::setTarget(const QNetworkInterface &iface)
}
auto hr = connection->GetConnectionId(&guid);
if (FAILED(hr)) {
qCDebug(lcNetMon) << "Failed to get the connection's GUID:" << errorStringFromHResult(hr);
qCDebug(lcNetMon) << "Failed to get the connection's GUID:"
<< QSystemError::windowsComString(hr);
return false;
}
currentConnectionId = guid;
@ -281,7 +276,7 @@ bool QNetworkConnectionEvents::startMonitoring()
auto hr = connectionPoint->Advise(this, &cookie);
if (FAILED(hr)) {
qCDebug(lcNetMon) << "Failed to subscribe to network connectivity events:"
<< errorStringFromHResult(hr);
<< QSystemError::windowsComString(hr);
return false;
}
return true;
@ -292,7 +287,7 @@ bool QNetworkConnectionEvents::stopMonitoring()
auto hr = connectionPoint->Unadvise(cookie);
if (FAILED(hr)) {
qCDebug(lcNetMon) << "Failed to unsubscribe from network connection events:"
<< errorStringFromHResult(hr);
<< QSystemError::windowsComString(hr);
return false;
}
cookie = 0;

View File

@ -2,6 +2,7 @@
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "qnetworklistmanagerevents.h"
#include <QtCore/private/qsystemerror_p.h>
#include <QtCore/qpointer.h>
@ -42,7 +43,7 @@ QNetworkListManagerEvents::QNetworkListManagerEvents() : QObject(nullptr)
IID_INetworkListManager, &networkListManager);
if (FAILED(hr)) {
qCWarning(lcNetInfoNLM) << "Could not get a NetworkListManager instance:"
<< errorStringFromHResult(hr);
<< QSystemError::windowsComString(hr);
return;
}
@ -54,7 +55,7 @@ QNetworkListManagerEvents::QNetworkListManagerEvents() : QObject(nullptr)
}
if (FAILED(hr)) {
qCWarning(lcNetInfoNLM) << "Failed to get connection point for network list manager events:"
<< errorStringFromHResult(hr);
<< QSystemError::windowsComString(hr);
}
}
@ -92,17 +93,19 @@ bool QNetworkListManagerEvents::start()
auto hr = connectionPoint->Advise(this, &cookie);
if (FAILED(hr)) {
qCWarning(lcNetInfoNLM) << "Failed to subscribe to network connectivity events:"
<< errorStringFromHResult(hr);
<< QSystemError::windowsComString(hr);
return false;
}
// Update connectivity since it might have changed since this class was constructed
NLM_CONNECTIVITY connectivity;
hr = networkListManager->GetConnectivity(&connectivity);
if (FAILED(hr))
qCWarning(lcNetInfoNLM) << "Could not get connectivity:" << errorStringFromHResult(hr);
else
if (FAILED(hr)) {
qCWarning(lcNetInfoNLM) << "Could not get connectivity:"
<< QSystemError::windowsComString(hr);
} else {
emit connectivityChanged(connectivity);
}
#if QT_CONFIG(cpp_winrt)
using namespace winrt::Windows::Networking::Connectivity;
@ -130,7 +133,7 @@ void QNetworkListManagerEvents::stop()
auto hr = connectionPoint->Unadvise(cookie);
if (FAILED(hr)) {
qCWarning(lcNetInfoNLM) << "Failed to unsubscribe from network connectivity events:"
<< errorStringFromHResult(hr);
<< QSystemError::windowsComString(hr);
} else {
cookie = 0;
}

View File

@ -14,7 +14,6 @@
#include <netlistmgr.h>
#include <wrl/client.h>
#include <wrl/wrappers/corewrappers.h>
#include <comdef.h>
#if QT_CONFIG(cpp_winrt)
#include <winrt/base.h>
@ -26,12 +25,6 @@ using namespace Microsoft::WRL;
QT_BEGIN_NAMESPACE
Q_DECLARE_LOGGING_CATEGORY(lcNetInfoNLM)
inline QString errorStringFromHResult(HRESULT hr)
{
_com_error error(hr);
return QString::fromWCharArray(error.ErrorMessage());
}
class QNetworkListManagerEvents : public QObject, public INetworkListManagerEvents
{
Q_OBJECT

View File

@ -16,6 +16,7 @@
#include <QtCore/qthread.h>
#include <QtCore/qvariant.h>
#include <QtCore/qurl.h>
#include <QtCore/private/qsystemerror_p.h>
#include <QtGui/private/qwindowsguieventdispatcher_p.h>
@ -300,7 +301,7 @@ void QWindowsClipboard::setMimeData(QMimeData *mimeData, QClipboard::Mode mode)
mimeData->formats().join(u", ") : QString(QStringLiteral("NULL"));
qErrnoWarning("OleSetClipboard: Failed to set mime data (%s) on clipboard: %s",
qPrintable(mimeDataFormats),
QWindowsContext::comErrorString(src).constData());
qPrintable(QSystemError::windowsComString(src)));
releaseIData();
return;
}

View File

@ -46,13 +46,13 @@
#include <QtCore/quuid.h>
#include <QtCore/private/qwinregistry_p.h>
#include <QtCore/private/qfactorycacheregistration_p.h>
#include <QtCore/private/qsystemerror_p.h>
#include <QtGui/private/qwindowsguieventdispatcher_p.h>
#include <stdlib.h>
#include <stdio.h>
#include <windowsx.h>
#include <comdef.h>
#include <dbt.h>
#include <wtsapi32.h>
#include <shellscalingapi.h>
@ -192,7 +192,7 @@ QWindowsContextPrivate::QWindowsContextPrivate()
m_darkMode = QWindowsTheme::queryDarkMode();
if (FAILED(m_oleInitializeResult)) {
qWarning() << "QWindowsContext: OleInitialize() failed: "
<< QWindowsContext::comErrorString(m_oleInitializeResult);
<< QSystemError::windowsComString(m_oleInitializeResult);
}
}
@ -383,7 +383,7 @@ void QWindowsContext::setProcessDpiAwareness(QtWindows::ProcessDpiAwareness dpiA
// Silence warning in that case unless debug is enabled.
if (FAILED(hr) && hr != E_ACCESSDENIED) {
qCWarning(lcQpaWindow).noquote().nospace() << "SetProcessDpiAwareness("
<< dpiAwareness << ") failed: " << QWindowsContext::comErrorString(hr)
<< dpiAwareness << ") failed: " << QSystemError::windowsComString(hr)
<< ", using " << QWindowsContext::processDpiAwareness();
}
}
@ -399,7 +399,7 @@ bool QWindowsContext::setProcessDpiV2Awareness()
if (dwError != ERROR_ACCESS_DENIED) {
qCWarning(lcQpaWindow).noquote().nospace()
<< "SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2) failed: "
<< QWindowsContext::comErrorString(HRESULT(dwError));
<< QSystemError::windowsComString(HRESULT(dwError));
return false;
}
}
@ -622,23 +622,6 @@ int QWindowsContext::screenDepth() const
return GetDeviceCaps(d->m_displayContext, BITSPIXEL);
}
QString QWindowsContext::windowsErrorMessage(unsigned long errorCode)
{
QString rc = QString::fromLatin1("#%1: ").arg(errorCode);
char16_t *lpMsgBuf;
const DWORD len = FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr, errorCode, 0, reinterpret_cast<LPTSTR>(&lpMsgBuf), 0, nullptr);
if (len) {
rc = QString::fromUtf16(lpMsgBuf, int(len));
LocalFree(lpMsgBuf);
} else {
rc += QString::fromLatin1("<unknown error>");
}
return rc;
}
void QWindowsContext::addWindow(HWND hwnd, QWindowsWindow *w)
{
d->m_windows.insert(hwnd, w);
@ -839,79 +822,6 @@ HWND QWindowsContext::createDummyWindow(const QString &classNameIn,
HWND_MESSAGE, nullptr, static_cast<HINSTANCE>(GetModuleHandle(nullptr)), nullptr);
}
/*!
\brief Common COM error strings.
*/
QByteArray QWindowsContext::comErrorString(HRESULT hr)
{
QByteArray result = QByteArrayLiteral("COM error 0x")
+ QByteArray::number(quintptr(hr), 16) + ' ';
switch (hr) {
case S_OK:
result += QByteArrayLiteral("S_OK");
break;
case S_FALSE:
result += QByteArrayLiteral("S_FALSE");
break;
case E_UNEXPECTED:
result += QByteArrayLiteral("E_UNEXPECTED");
break;
case E_ACCESSDENIED:
result += QByteArrayLiteral("E_ACCESSDENIED");
break;
case CO_E_ALREADYINITIALIZED:
result += QByteArrayLiteral("CO_E_ALREADYINITIALIZED");
break;
case CO_E_NOTINITIALIZED:
result += QByteArrayLiteral("CO_E_NOTINITIALIZED");
break;
case RPC_E_CHANGED_MODE:
result += QByteArrayLiteral("RPC_E_CHANGED_MODE");
break;
case OLE_E_WRONGCOMPOBJ:
result += QByteArrayLiteral("OLE_E_WRONGCOMPOBJ");
break;
case CO_E_NOT_SUPPORTED:
result += QByteArrayLiteral("CO_E_NOT_SUPPORTED");
break;
case E_NOTIMPL:
result += QByteArrayLiteral("E_NOTIMPL");
break;
case E_INVALIDARG:
result += QByteArrayLiteral("E_INVALIDARG");
break;
case E_NOINTERFACE:
result += QByteArrayLiteral("E_NOINTERFACE");
break;
case E_POINTER:
result += QByteArrayLiteral("E_POINTER");
break;
case E_HANDLE:
result += QByteArrayLiteral("E_HANDLE");
break;
case E_ABORT:
result += QByteArrayLiteral("E_ABORT");
break;
case E_FAIL:
result += QByteArrayLiteral("E_FAIL");
break;
case RPC_E_WRONG_THREAD:
result += QByteArrayLiteral("RPC_E_WRONG_THREAD");
break;
case RPC_E_THREAD_NOT_INIT:
result += QByteArrayLiteral("RPC_E_THREAD_NOT_INIT");
break;
default:
break;
}
_com_error error(hr);
result += QByteArrayLiteral(" (");
result += QString::fromWCharArray(error.ErrorMessage()).toUtf8();
result += ')';
return result;
}
void QWindowsContext::forceNcCalcSize(HWND hwnd)
{
// Force WM_NCCALCSIZE to adjust margin

View File

@ -88,8 +88,6 @@ public:
static QWindowsContext *instance();
static QString windowsErrorMessage(unsigned long errorCode);
void addWindow(HWND, QWindowsWindow *w);
void removeWindow(HWND);
@ -139,7 +137,6 @@ public:
QWindowsScreenManager &screenManager();
QWindowsTabletSupport *tabletSupport() const;
static QByteArray comErrorString(HRESULT hr);
bool asyncExpose() const;
void setAsyncExpose(bool value);

View File

@ -31,6 +31,7 @@
#include <QtCore/qmutex.h>
#include <QtCore/quuid.h>
#include <QtCore/qtemporaryfile.h>
#include <QtCore/private/qsystemerror_p.h>
#include <algorithm>
#include <vector>
@ -631,7 +632,7 @@ bool QWindowsShellItem::copyData(QIODevice *out, QString *errorMessage)
HRESULT hr = m_item->BindToHandler(nullptr, BHID_Stream, IID_PPV_ARGS(&istream));
if (FAILED(hr)) {
*errorMessage = "BindToHandler() failed: "_L1
+ QLatin1StringView(QWindowsContext::comErrorString(hr));
+ QSystemError::windowsComString(hr);
return false;
}
enum : ULONG { bufSize = 102400 };
@ -648,7 +649,7 @@ bool QWindowsShellItem::copyData(QIODevice *out, QString *errorMessage)
istream->Release();
if (hr != S_OK && hr != S_FALSE) {
*errorMessage = "Read() failed: "_L1
+ QLatin1StringView(QWindowsContext::comErrorString(hr));
+ QSystemError::windowsComString(hr);
return false;
}
return true;

View File

@ -15,6 +15,7 @@
#include <QtCore/QStandardPaths>
#if defined(Q_OS_WIN)
# include <QtCore/qt_windows.h>
# include <QtCore/private/qsystemerror_p.h>
# include <shlwapi.h>
# include <delayimp.h>
#else // Q_OS_WIN
@ -116,22 +117,6 @@ QStringList findSharedLibraries(const QDir &directory, Platform platform,
}
#ifdef Q_OS_WIN
QString winErrorMessage(unsigned long error)
{
QString rc = QString::fromLatin1("#%1: ").arg(error);
char16_t *lpMsgBuf;
const DWORD len = FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, error, 0, reinterpret_cast<LPTSTR>(&lpMsgBuf), 0, NULL);
if (len) {
rc = QString::fromUtf16(lpMsgBuf, int(len));
LocalFree(lpMsgBuf);
} else {
rc += QString::fromLatin1("<unknown error>");
}
return rc;
}
// Case-Normalize file name via GetShortPathNameW()/GetLongPathNameW()
QString normalizeFileName(const QString &name)
@ -263,8 +248,10 @@ bool runProcess(const QString &binary, const QStringList &args,
CloseHandle(si.hStdOutput);
if (stdErr)
CloseHandle(si.hStdError);
if (errorMessage)
*errorMessage = QStringLiteral("CreateProcessW failed: ") + winErrorMessage(GetLastError());
if (errorMessage) {
*errorMessage = QStringLiteral("CreateProcessW failed: ")
+ QSystemError::windowsString();
}
return false;
}
@ -778,19 +765,22 @@ bool readPeExecutable(const QString &peExecutableFileName, QString *errorMessage
hFile = CreateFile(reinterpret_cast<const WCHAR*>(peExecutableFileName.utf16()), GENERIC_READ, FILE_SHARE_READ, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE || hFile == NULL) {
*errorMessage = QString::fromLatin1("Cannot open '%1': %2").arg(peExecutableFileName, winErrorMessage(GetLastError()));
*errorMessage = QString::fromLatin1("Cannot open '%1': %2")
.arg(peExecutableFileName, QSystemError::windowsString());
break;
}
hFileMap = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
if (hFileMap == NULL) {
*errorMessage = QString::fromLatin1("Cannot create file mapping of '%1': %2").arg(peExecutableFileName, winErrorMessage(GetLastError()));
*errorMessage = QString::fromLatin1("Cannot create file mapping of '%1': %2")
.arg(peExecutableFileName, QSystemError::windowsString());
break;
}
fileMemory = MapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, 0);
if (!fileMemory) {
*errorMessage = QString::fromLatin1("Cannot map '%1': %2").arg(peExecutableFileName, winErrorMessage(GetLastError()));
*errorMessage = QString::fromLatin1("Cannot map '%1': %2")
.arg(peExecutableFileName, QSystemError::windowsString());
break;
}