cool#10630 doc sign: fix Impress sign line, to be able to finish signing again
[LibreOffice.git] / include / comphelper / windowserrorstring.hxx
blob7b6bdb6db8b16f695af61a9236bfaabee61ec676
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 */
10 #ifndef INCLUDED_COMPHELPER_WINDOWSERRORSTRING_HXX
11 #define INCLUDED_COMPHELPER_WINDOWSERRORSTRING_HXX
13 #include <prewin.h>
14 #include <postwin.h>
15 #include <rtl/ustring.hxx>
16 #include <o3tl/char16_t2wchar_t.hxx>
18 namespace {
20 inline OUString WindowsErrorString(DWORD nErrorCode)
22 LPWSTR pMsgBuf;
24 if (FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
25 nullptr,
26 nErrorCode,
27 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
28 reinterpret_cast<LPWSTR>(&pMsgBuf),
30 nullptr) == 0)
31 return OUString::number(nErrorCode, 16);
33 OUString result(o3tl::toU(pMsgBuf));
34 result.endsWith("\r\n", &result);
36 HeapFree(GetProcessHeap(), 0, pMsgBuf);
38 return result;
41 inline OUString WindowsErrorStringFromHRESULT(HRESULT hr)
43 // See https://devblogs.microsoft.com/oldnewthing/20061103-07/?p=29133
44 // Also https://social.msdn.microsoft.com/Forums/vstudio/en-US/c33d9a4a-1077-4efd-99e8-0c222743d2f8
45 // (which refers to https://msdn.microsoft.com/en-us/library/aa382475)
46 // explains why can't we just reinterpret_cast HRESULT to DWORD Win32 error:
47 // we might actually have a Win32 error code converted using HRESULT_FROM_WIN32 macro
49 DWORD nErrorCode = DWORD(hr);
50 if (HRESULT(hr & 0xFFFF0000) == MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIN32, 0) || hr == S_OK)
52 nErrorCode = HRESULT_CODE(hr);
53 // https://msdn.microsoft.com/en-us/library/ms679360 mentions that the codes might have
54 // high word bits set (e.g., bit 29 could be set if error comes from a 3rd-party library).
55 // So try to restore the original error code to avoid wrong error messages
56 DWORD nLastError = GetLastError();
57 if ((nLastError & 0xFFFF) == nErrorCode)
58 nErrorCode = nLastError;
61 return WindowsErrorString(nErrorCode);
64 } // anonymous namespace
66 #endif
68 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */