Repository navigation
Expand file tree
/
Copy pathMenuBitmap.cpp
More file actions
337 lines (296 loc) · 12.3 KB
/
Copy pathMenuBitmap.cpp
File metadata and controls
337 lines (296 loc) · 12.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
#include "MenuBitmap.h"
#include <wincodec.h>
#include <objidl.h>
#include <algorithm>
#include "Common.h"
#pragma comment(lib, "windowscodecs.lib")
#pragma comment(lib, "ole32.lib")
#pragma comment(lib, "gdi32.lib")
#pragma comment(lib, "user32.lib")
namespace {
std::wstring HrText(HRESULT hr)
{
wchar_t buffer[16];
swprintf_s(buffer, L"0x%08X", static_cast<unsigned int>(hr));
return buffer;
}
template <class T>
class ComPtr {
public:
ComPtr() = default;
~ComPtr() { reset(); }
ComPtr(const ComPtr&) = delete;
ComPtr& operator=(const ComPtr&) = delete;
T** put() { reset(); return &p_; }
T* get() const { return p_; }
T* operator->() const { return p_; }
explicit operator bool() const { return p_ != nullptr; }
void reset()
{
if (p_) { p_->Release(); p_ = nullptr; }
}
private:
T* p_ = nullptr;
};
// GetDpiForWindow and GetSystemMetricsForDpi are Windows 10 1607; the manifest
// also claims 8.1, where a static import would stop the process from starting.
UINT DpiForPoint(POINT screenPoint)
{
typedef HRESULT(WINAPI * GetDpiForMonitorFn)(HMONITOR, int, UINT*, UINT*);
static GetDpiForMonitorFn getDpiForMonitor = reinterpret_cast<GetDpiForMonitorFn>(
GetProcAddress(LoadLibraryW(L"shcore.dll"), "GetDpiForMonitor"));
if (getDpiForMonitor) {
HMONITOR monitor = MonitorFromPoint(screenPoint, MONITOR_DEFAULTTONEAREST);
UINT dpiX = 0, dpiY = 0;
if (SUCCEEDED(getDpiForMonitor(monitor, 0 /*MDT_EFFECTIVE_DPI*/, &dpiX, &dpiY))
&& dpiX != 0)
return dpiX;
}
// Windows 7/8: one dpi for the whole desktop.
HDC screen = GetDC(nullptr);
UINT dpi = screen ? static_cast<UINT>(GetDeviceCaps(screen, LOGPIXELSX)) : 96;
if (screen)
ReleaseDC(nullptr, screen);
return dpi ? dpi : 96;
}
int MetricForDpi(int index, UINT dpi)
{
typedef int(WINAPI * GetSystemMetricsForDpiFn)(int, UINT);
static GetSystemMetricsForDpiFn forDpi = reinterpret_cast<GetSystemMetricsForDpiFn>(
GetProcAddress(GetModuleHandleW(L"user32.dll"), "GetSystemMetricsForDpi"));
if (forDpi)
return forDpi(index, dpi);
return GetSystemMetrics(index);
}
} // namespace
HBITMAP MenuBitmaps::Keep(HBITMAP bitmap)
{
if (bitmap)
bitmaps_.push_back(bitmap);
return bitmap;
}
void MenuBitmaps::Clear()
{
for (HBITMAP bitmap : bitmaps_)
DeleteObject(bitmap);
bitmaps_.clear();
}
SIZE MenuThumbnailSize(POINT screenPoint, int logicalWidth, int logicalHeight)
{
UINT dpi = DpiForPoint(screenPoint);
SIZE size;
size.cx = MulDiv(logicalWidth, static_cast<int>(dpi), 96);
size.cy = MulDiv(logicalHeight, static_cast<int>(dpi), 96);
return size;
}
SIZE MenuCheckSize(POINT screenPoint)
{
UINT dpi = DpiForPoint(screenPoint);
SIZE size;
size.cx = MetricForDpi(SM_CXMENUCHECK, dpi);
size.cy = MetricForDpi(SM_CYMENUCHECK, dpi);
return size;
}
std::string EncodeThumbnailJpeg(const std::string& bytes, int maxWidth, int maxHeight)
{
if (bytes.empty())
throw AppError{ L"There is no image to make a preview from." };
if (maxWidth <= 0 || maxHeight <= 0)
throw AppError{ L"The preview size is not usable." };
ComPtr<IWICImagingFactory> factory;
HRESULT hr = CoCreateInstance(CLSID_WICImagingFactory, nullptr, CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(factory.put()));
if (FAILED(hr))
throw AppError{ L"Could not start the image decoder (" + HrText(hr) + L")." };
ComPtr<IWICStream> source;
hr = factory->CreateStream(source.put());
if (SUCCEEDED(hr)) {
hr = source->InitializeFromMemory(
reinterpret_cast<BYTE*>(const_cast<char*>(bytes.data())),
static_cast<DWORD>(bytes.size()));
}
if (FAILED(hr))
throw AppError{ L"Could not read the image (" + HrText(hr) + L")." };
ComPtr<IWICBitmapDecoder> decoder;
hr = factory->CreateDecoderFromStream(source.get(), nullptr,
WICDecodeMetadataCacheOnDemand, decoder.put());
if (FAILED(hr))
throw AppError{ L"That file is not an image Windows can read." };
ComPtr<IWICBitmapFrameDecode> frame;
hr = decoder->GetFrame(0, frame.put());
UINT sourceWidth = 0, sourceHeight = 0;
if (SUCCEEDED(hr))
hr = frame->GetSize(&sourceWidth, &sourceHeight);
if (FAILED(hr) || sourceWidth == 0 || sourceHeight == 0)
throw AppError{ L"The image could not be decoded." };
// Fit inside the box without cropping: the crop happens later, when the
// cached preview is turned into a menu bitmap at the right size.
double scale = (std::min)(static_cast<double>(maxWidth) / sourceWidth,
static_cast<double>(maxHeight) / sourceHeight);
if (scale > 1.0)
scale = 1.0; // never enlarge a picture that is already small
UINT targetWidth = static_cast<UINT>(sourceWidth * scale);
UINT targetHeight = static_cast<UINT>(sourceHeight * scale);
if (targetWidth == 0) targetWidth = 1;
if (targetHeight == 0) targetHeight = 1;
ComPtr<IWICBitmapScaler> scaler;
hr = factory->CreateBitmapScaler(scaler.put());
if (SUCCEEDED(hr))
hr = scaler->Initialize(frame.get(), targetWidth, targetHeight,
WICBitmapInterpolationModeFant);
if (FAILED(hr))
throw AppError{ L"Could not scale the preview (" + HrText(hr) + L")." };
// JPEG has no alpha channel, so the pixels have to be plain BGR.
ComPtr<IWICFormatConverter> converter;
hr = factory->CreateFormatConverter(converter.put());
if (SUCCEEDED(hr)) {
hr = converter->Initialize(scaler.get(), GUID_WICPixelFormat24bppBGR,
WICBitmapDitherTypeNone, nullptr, 0.0, WICBitmapPaletteTypeCustom);
}
if (FAILED(hr))
throw AppError{ L"Could not convert the preview (" + HrText(hr) + L")." };
// A growable stream, since the encoded size is not known up front.
IStream* rawOutput = nullptr;
hr = CreateStreamOnHGlobal(nullptr, TRUE, &rawOutput);
if (FAILED(hr))
throw AppError{ L"Could not allocate the preview buffer." };
ComPtr<IStream> output;
*output.put() = rawOutput;
ComPtr<IWICBitmapEncoder> encoder;
hr = factory->CreateEncoder(GUID_ContainerFormatJpeg, nullptr, encoder.put());
if (SUCCEEDED(hr))
hr = encoder->Initialize(output.get(), WICBitmapEncoderNoCache);
if (FAILED(hr))
throw AppError{ L"Could not start the preview encoder (" + HrText(hr) + L")." };
ComPtr<IWICBitmapFrameEncode> encodedFrame;
IPropertyBag2* rawOptions = nullptr;
hr = encoder->CreateNewFrame(encodedFrame.put(), &rawOptions);
ComPtr<IPropertyBag2> options;
if (rawOptions)
*options.put() = rawOptions;
if (SUCCEEDED(hr))
hr = encodedFrame->Initialize(options.get());
if (SUCCEEDED(hr))
hr = encodedFrame->SetSize(targetWidth, targetHeight);
WICPixelFormatGUID format = GUID_WICPixelFormat24bppBGR;
if (SUCCEEDED(hr))
hr = encodedFrame->SetPixelFormat(&format);
if (SUCCEEDED(hr))
hr = encodedFrame->WriteSource(converter.get(), nullptr);
if (SUCCEEDED(hr))
hr = encodedFrame->Commit();
if (SUCCEEDED(hr))
hr = encoder->Commit();
if (FAILED(hr))
throw AppError{ L"Could not encode the preview (" + HrText(hr) + L")." };
HGLOBAL memory = nullptr;
hr = GetHGlobalFromStream(output.get(), &memory);
if (FAILED(hr) || !memory)
throw AppError{ L"Could not read back the preview." };
SIZE_T length = GlobalSize(memory);
const void* data = GlobalLock(memory);
if (!data || length == 0)
throw AppError{ L"The encoded preview was empty." };
std::string encoded(static_cast<const char*>(data), length);
GlobalUnlock(memory);
return encoded;
}
HBITMAP CreateMenuThumbnail(const std::string& bytes, SIZE size)
{
if (bytes.empty())
throw AppError{ L"The thumbnail download was empty." };
if (size.cx <= 0 || size.cy <= 0)
throw AppError{ L"The thumbnail size is not usable." };
ComPtr<IWICImagingFactory> factory;
HRESULT hr = CoCreateInstance(CLSID_WICImagingFactory, nullptr, CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(factory.put()));
if (FAILED(hr))
throw AppError{ L"Could not start the image decoder (" + HrText(hr) + L")." };
// The stream keeps a pointer into `bytes`, so `bytes` must stay alive until
// the last CopyPixels below. It is a const reference for exactly that reason.
ComPtr<IWICStream> stream;
hr = factory->CreateStream(stream.put());
if (SUCCEEDED(hr)) {
hr = stream->InitializeFromMemory(
reinterpret_cast<BYTE*>(const_cast<char*>(bytes.data())),
static_cast<DWORD>(bytes.size()));
}
if (FAILED(hr))
throw AppError{ L"Could not read the thumbnail (" + HrText(hr) + L")." };
ComPtr<IWICBitmapDecoder> decoder;
hr = factory->CreateDecoderFromStream(stream.get(), nullptr,
WICDecodeMetadataCacheOnDemand, decoder.put());
if (FAILED(hr))
throw AppError{ L"The thumbnail is not an image Windows can read." };
ComPtr<IWICBitmapFrameDecode> frame;
hr = decoder->GetFrame(0, frame.put());
UINT sourceWidth = 0, sourceHeight = 0;
if (SUCCEEDED(hr))
hr = frame->GetSize(&sourceWidth, &sourceHeight);
if (FAILED(hr) || sourceWidth == 0 || sourceHeight == 0)
throw AppError{ L"The thumbnail could not be decoded." };
// Centre-crop to the target aspect first, so the scaler never squashes.
UINT cropWidth = sourceWidth, cropHeight = sourceHeight;
if (static_cast<long long>(sourceWidth) * size.cy
> static_cast<long long>(sourceHeight) * size.cx) {
cropWidth = static_cast<UINT>(
static_cast<long long>(sourceHeight) * size.cx / size.cy);
} else {
cropHeight = static_cast<UINT>(
static_cast<long long>(sourceWidth) * size.cy / size.cx);
}
if (cropWidth == 0) cropWidth = 1;
if (cropHeight == 0) cropHeight = 1;
ComPtr<IWICBitmapClipper> clipper;
WICRect crop;
crop.X = static_cast<INT>((sourceWidth - cropWidth) / 2);
crop.Y = static_cast<INT>((sourceHeight - cropHeight) / 2);
crop.Width = static_cast<INT>(cropWidth);
crop.Height = static_cast<INT>(cropHeight);
hr = factory->CreateBitmapClipper(clipper.put());
if (SUCCEEDED(hr))
hr = clipper->Initialize(frame.get(), &crop);
if (FAILED(hr))
throw AppError{ L"Could not crop the thumbnail (" + HrText(hr) + L")." };
ComPtr<IWICBitmapScaler> scaler;
hr = factory->CreateBitmapScaler(scaler.put());
if (SUCCEEDED(hr)) {
hr = scaler->Initialize(clipper.get(), static_cast<UINT>(size.cx),
static_cast<UINT>(size.cy), WICBitmapInterpolationModeFant);
}
if (FAILED(hr))
throw AppError{ L"Could not scale the thumbnail (" + HrText(hr) + L")." };
// 32bppPBGRA is premultiplied BGRA, which is byte-for-byte what a 32bpp DIB
// section holds and what the menu's AlphaBlend expects.
ComPtr<IWICFormatConverter> converter;
hr = factory->CreateFormatConverter(converter.put());
if (SUCCEEDED(hr)) {
hr = converter->Initialize(scaler.get(), GUID_WICPixelFormat32bppPBGRA,
WICBitmapDitherTypeNone, nullptr, 0.0, WICBitmapPaletteTypeCustom);
}
if (FAILED(hr))
throw AppError{ L"Could not convert the thumbnail (" + HrText(hr) + L")." };
// A negative height means top-down, which is the order CopyPixels writes in.
// With a positive height the picture comes out upside down.
BITMAPINFO info = {};
info.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
info.bmiHeader.biWidth = size.cx;
info.bmiHeader.biHeight = -size.cy;
info.bmiHeader.biPlanes = 1;
info.bmiHeader.biBitCount = 32;
info.bmiHeader.biCompression = BI_RGB;
void* pixels = nullptr;
HBITMAP bitmap = CreateDIBSection(nullptr, &info, DIB_RGB_COLORS, &pixels, nullptr, 0);
if (!bitmap || !pixels)
throw AppError{ L"Could not allocate the thumbnail bitmap." };
UINT stride = static_cast<UINT>(size.cx) * 4;
hr = converter->CopyPixels(nullptr, stride, stride * static_cast<UINT>(size.cy),
static_cast<BYTE*>(pixels));
if (FAILED(hr)) {
DeleteObject(bitmap);
throw AppError{ L"Could not read the thumbnail pixels (" + HrText(hr) + L")." };
}
// GDI caches DIB section writes; without this the menu can blit stale bits.
GdiFlush();
return bitmap;
}