-
-
Notifications
You must be signed in to change notification settings - Fork 667
Expand file tree
/
Copy pathPlaceholderImageHelper.cpp
More file actions
2272 lines (1863 loc) · 91.3 KB
/
Copy pathPlaceholderImageHelper.cpp
File metadata and controls
2272 lines (1863 loc) · 91.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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "pch.h"
#include "PlaceholderImageHelper.h"
#if __has_include("PlaceholderImageHelper.g.cpp")
#include "PlaceholderImageHelper.g.cpp"
#endif
#include "SVG/nanosvg.h"
#include "StringUtils.h"
#include "Helpers\COMHelper.h"
#include "Helpers\BlurHelper.h"
#include <zlib.h>
#include <format>
#include <numbers>
#include <src\webp\decode.h>
#include <src\webp\demux.h>
#include <shcore.h>
#include <propkey.h>
#include <winrt/Windows.ApplicationModel.h>
#include <winrt/Windows.Foundation.Collections.h>
#include <winrt/Windows.Graphics.Effects.h>
#include <winrt/Windows.UI.Xaml.Media.Imaging.h>
#include <winrt/Windows.Security.Cryptography.h>
#include <windows.ui.xaml.media.dxinterop.h>
#include <BufferSurface.h>
using namespace D2D1;
using namespace winrt::Windows::ApplicationModel;
using namespace winrt::Windows::Graphics::DirectX;
using namespace winrt::Windows::UI::Xaml::Media::Imaging;
namespace winrt::Telegram::Native::implementation
{
class CustomEmojiInlineObject
: public winrt::implements<CustomEmojiInlineObject, IDWriteInlineObject>
{
IFACEMETHODIMP2 Draw(
_In_opt_ void* clientDrawingContext,
_In_ IDWriteTextRenderer* renderer,
FLOAT originX,
FLOAT originY,
BOOL isSideways,
BOOL isRightToLeft,
_In_opt_ IUnknown* clientDrawingEffect
) override
{
return S_OK;
}
IFACEMETHODIMP2 GetMetrics(_Out_ DWRITE_INLINE_OBJECT_METRICS* metrics) override
{
DWRITE_INLINE_OBJECT_METRICS inlineMetrics = {};
inlineMetrics.width = 20;
inlineMetrics.height = 20;
inlineMetrics.baseline = 20;
*metrics = inlineMetrics;
return S_OK;
}
IFACEMETHODIMP2 GetOverhangMetrics(_Out_ DWRITE_OVERHANG_METRICS* overhangs) override
{
DWRITE_OVERHANG_METRICS inlineOverhangs = {};
inlineOverhangs.left = 0;
inlineOverhangs.top = -2;
inlineOverhangs.right = 0;
inlineOverhangs.bottom = -6;
*overhangs = inlineOverhangs;
return S_OK;
}
IFACEMETHODIMP2 GetBreakConditions(_Out_ DWRITE_BREAK_CONDITION* breakConditionBefore, _Out_ DWRITE_BREAK_CONDITION* breakConditionAfter) override
{
*breakConditionBefore = DWRITE_BREAK_CONDITION_CAN_BREAK;
*breakConditionAfter = DWRITE_BREAK_CONDITION_MAY_NOT_BREAK;
return S_OK;
}
};
class CustomFontFileEnumerator
: public winrt::implements<CustomFontFileEnumerator, IDWriteFontFileEnumerator>
{
winrt::com_ptr<IDWriteFactory> m_factory;
std::vector<const wchar_t*> m_filenames;
int32_t m_index;
winrt::com_ptr<IDWriteFontFile> m_theFile;
public:
CustomFontFileEnumerator(IDWriteFactory* factory, void const* collectionKey, uint32_t collectionKeySize)
: m_factory()
, m_index(0)
{
auto keys = static_cast<const wchar_t* const*>(collectionKey);
auto count = collectionKeySize / sizeof(const wchar_t*);
m_filenames = std::vector<const wchar_t*>(keys, keys + count);
m_factory.copy_from(factory);
}
IFACEMETHODIMP2 MoveNext(BOOL* hasCurrentFile) override
{
if (m_index == m_filenames.size())
{
*hasCurrentFile = FALSE;
}
else if (SUCCEEDED(m_factory->CreateFontFileReference(m_filenames[m_index++], nullptr, m_theFile.put())))
{
*hasCurrentFile = TRUE;
}
else
{
*hasCurrentFile = FALSE;
}
return S_OK;
}
IFACEMETHODIMP2 GetCurrentFontFile(IDWriteFontFile** fontFile) override
{
m_theFile.copy_to(fontFile);
return S_OK;
}
};
class CustomFontLoader
: public winrt::implements<CustomFontLoader, IDWriteFontCollectionLoader>
{
// DWrite keeps its own copy of the collection key and hands it back to
// CreateEnumeratorFromKey whenever it needs to rebuild the collection, so the strings the
// key points at have to live as long as the loader is registered, not as long as the call
// that creates the collection.
hstring m_paths[2];
const wchar_t* m_key[2];
public:
CustomFontLoader(hstring const& fontPath, hstring const& emojiPath)
: m_paths{ fontPath, emojiPath }
, m_key{ m_paths[0].c_str(), m_paths[1].c_str() }
{
}
void const* Key() const noexcept
{
return m_key;
}
// Byte count, as DWrite expects: it copies collectionKeySize bytes out of the key.
uint32_t KeySize() const noexcept
{
return static_cast<uint32_t>(sizeof(m_key));
}
IFACEMETHODIMP2 CreateEnumeratorFromKey(
IDWriteFactory* factory,
void const* collectionKey,
uint32_t collectionKeySize,
IDWriteFontFileEnumerator** fontFileEnumerator) override
{
return ExceptionBoundary(
[=]
{
auto enumerator = winrt::make_self<CustomFontFileEnumerator>(factory, collectionKey, collectionKeySize);
enumerator.as<IDWriteFontFileEnumerator>().copy_to(fontFileEnumerator);
});
}
};
IBuffer PlaceholderImageHelper::DrawWebP(hstring fileName, int32_t maxWidth, int32_t& pixelWidth, int32_t& pixelHeight) noexcept
{
pixelWidth = 0;
pixelHeight = 0;
DWORD desired_access = GENERIC_READ;
// TODO: share mode
DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_DELETE | FILE_SHARE_WRITE;
DWORD creation_disposition = OPEN_ALWAYS;
DWORD native_flags = FILE_FLAG_BACKUP_SEMANTICS;
//if (flags & Direct) {
// native_flags |= FILE_FLAG_WRITE_THROUGH | FILE_FLAG_NO_BUFFERING;
//}
//if (flags & WinStat) {
// native_flags |= FILE_FLAG_BACKUP_SEMANTICS;
//}
CREATEFILE2_EXTENDED_PARAMETERS extended_parameters;
std::memset(&extended_parameters, 0, sizeof(extended_parameters));
extended_parameters.dwSize = sizeof(extended_parameters);
extended_parameters.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
extended_parameters.dwFileFlags = native_flags;
HANDLE handle = CreateFile2FromAppW(fileName.c_str(), desired_access, share_mode, creation_disposition, &extended_parameters);
if (handle == INVALID_HANDLE_VALUE)
{
return nullptr;
}
LARGE_INTEGER pFileSize;
if (!GetFileSizeEx(handle, &pFileSize))
{
CloseHandle(handle);
return nullptr;
}
size_t length = static_cast<size_t>(pFileSize.QuadPart);
char* buffer = (char*)malloc(length);
DWORD numberOfBytesRead;
if (!ReadFile(handle, buffer, length, &numberOfBytesRead, NULL))
{
CloseHandle(handle);
return nullptr;
}
CloseHandle(handle);
WebPData webPData;
webPData.bytes = (uint8_t*)buffer;
webPData.size = length;
auto spDemuxer = std::unique_ptr<WebPDemuxer, decltype(&WebPDemuxDelete)>
{
WebPDemux(&webPData),
WebPDemuxDelete
};
if (!spDemuxer)
{
//throw ref new InvalidArgumentException(ref new String(L"Failed to create demuxer"));
free(buffer);
return nullptr;
}
IBuffer surface;
WebPIterator iter;
if (WebPDemuxGetFrame(spDemuxer.get(), 1, &iter))
{
WebPDecoderConfig config;
int ret = WebPInitDecoderConfig(&config);
if (!ret)
{
//throw ref new FailureException(ref new String(L"WebPInitDecoderConfig failed"));
free(buffer);
return nullptr;
}
ret = (WebPGetFeatures(iter.fragment.bytes, iter.fragment.size, &config.input) == VP8_STATUS_OK);
if (!ret)
{
//throw ref new FailureException(ref new String(L"WebPGetFeatures failed"));
free(buffer);
return nullptr;
}
int width = iter.width;
int height = iter.height;
if (iter.width > maxWidth || iter.height > maxWidth)
{
auto ratioX = (double)maxWidth / iter.width;
auto ratioY = (double)maxWidth / iter.height;
auto ratio = std::min(ratioX, ratioY);
width = (int)(iter.width * ratio);
height = (int)(iter.height * ratio);
}
pixelWidth = width;
pixelHeight = height;
surface = Telegram::Native::BufferSurface::Create(width * 4 * height);
auto pixels = surface.data();
//uint8_t* pixels = new uint8_t[(width * 4) * height];
if (width != iter.width || height != iter.height)
{
config.options.scaled_width = width;
config.options.scaled_height = height;
config.options.use_scaling = 1;
config.options.no_fancy_upsampling = 1;
}
config.output.colorspace = MODE_bgrA;
config.output.is_external_memory = 1;
config.output.u.RGBA.rgba = pixels;
config.output.u.RGBA.stride = width * 4;
config.output.u.RGBA.size = (width * 4) * height;
ret = WebPDecode(iter.fragment.bytes, iter.fragment.size, &config);
if (ret != VP8_STATUS_OK)
{
//throw ref new FailureException(ref new String(L"Failed to decode frame"));
//delete[] pixels;
free(buffer);
return nullptr;
}
//delete[] pixels;
}
free(buffer);
return surface;
}
bool PlaceholderImageHelper::IsWebP(hstring fileName, int32_t& pixelWidth, int32_t& pixelHeight) noexcept
{
pixelWidth = 0;
pixelHeight = 0;
DWORD desired_access = GENERIC_READ;
// TODO: share mode
DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_DELETE | FILE_SHARE_WRITE;
DWORD creation_disposition = OPEN_ALWAYS;
DWORD native_flags = FILE_FLAG_BACKUP_SEMANTICS;
//if (flags & Direct) {
// native_flags |= FILE_FLAG_WRITE_THROUGH | FILE_FLAG_NO_BUFFERING;
//}
//if (flags & WinStat) {
// native_flags |= FILE_FLAG_BACKUP_SEMANTICS;
//}
CREATEFILE2_EXTENDED_PARAMETERS extended_parameters;
std::memset(&extended_parameters, 0, sizeof(extended_parameters));
extended_parameters.dwSize = sizeof(extended_parameters);
extended_parameters.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
extended_parameters.dwFileFlags = native_flags;
HANDLE handle = CreateFile2FromAppW(fileName.c_str(), desired_access, share_mode, creation_disposition, &extended_parameters);
if (handle == INVALID_HANDLE_VALUE)
{
return false;
}
LARGE_INTEGER pFileSize;
if (!GetFileSizeEx(handle, &pFileSize))
{
CloseHandle(handle);
return false;
}
size_t length = static_cast<size_t>(pFileSize.QuadPart);
char* buffer = (char*)malloc(length);
DWORD numberOfBytesRead;
if (!ReadFile(handle, buffer, length, &numberOfBytesRead, NULL))
{
CloseHandle(handle);
return false;
}
CloseHandle(handle);
WebPData webPData;
webPData.bytes = (uint8_t*)buffer;
webPData.size = length;
auto spDemuxer = std::unique_ptr<WebPDemuxer, decltype(&WebPDemuxDelete)>
{
WebPDemux(&webPData),
WebPDemuxDelete
};
if (!spDemuxer)
{
//throw ref new InvalidArgumentException(ref new String(L"Failed to create demuxer"));
free(buffer);
return false;
}
IBuffer surface;
WebPIterator iter;
if (WebPDemuxGetFrame(spDemuxer.get(), 1, &iter))
{
pixelWidth = iter.width;
pixelHeight = iter.height;
}
free(buffer);
return true;
}
winrt::Telegram::Native::SurfaceImage PlaceholderImageHelper::Create(int32_t pixelWidth, int32_t pixelHeight)
{
std::lock_guard const guard(m_criticalSection);
auto surface = winrt::make_self<SurfaceImage>(m_d2dDevice.get(), pixelWidth, pixelHeight);
return surface.as<winrt::Telegram::Native::SurfaceImage>();
}
HRESULT PlaceholderImageHelper::Invalidate(winrt::Telegram::Native::SurfaceImage imageSource, IBuffer buffer)
{
std::lock_guard const guard(m_criticalSection);
HRESULT result;
com_ptr<SurfaceImage> source = imageSource.as<SurfaceImage>();
int32_t pixelWidth = source->m_pixelWidth;
int32_t pixelHeight = source->m_pixelHeight;
winrt::com_ptr<ISurfaceImageSourceNativeWithD2D> native = source->m_native;
D2D1_SIZE_U size{ pixelWidth, pixelHeight };
D2D1_RECT_U rect{ 0, 0, pixelWidth, pixelHeight };
RECT updateRect{ 0, 0, pixelWidth, pixelHeight };
POINT offset{ 0, 0 };
com_ptr<ID2D1DeviceContext> d2d1DeviceContext;
result = native->BeginDraw(updateRect, __uuidof(ID2D1DeviceContext), d2d1DeviceContext.put_void(), &offset);
if (result == DXGI_ERROR_DEVICE_REMOVED || result == DXGI_ERROR_DEVICE_RESET)
{
ReturnIfFailed(result, CreateDeviceResources());
ReturnIfFailed(result, source->CreateDeviceResources(m_d2dDevice.get()));
return Invalidate(imageSource, buffer);
}
com_ptr<ID2D1Bitmap1> bitmap;
D2D1_BITMAP_PROPERTIES1 properties = { { DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED }, 96, 96, D2D1_BITMAP_OPTIONS_NONE, 0 };
CleanupIfFailed(result, d2d1DeviceContext->CreateBitmap(size, buffer.data(), pixelWidth * 4, &properties, bitmap.put()));
d2d1DeviceContext->SetTransform(D2D1::Matrix3x2F::Translation(offset.x, offset.y));
d2d1DeviceContext->Clear(D2D1::ColorF(0, 0, 0, 0));
d2d1DeviceContext->DrawBitmap(bitmap.get());
Cleanup:
return native->EndDraw();
}
winrt::Windows::Foundation::IAsyncOperation<ChatBackgroundPattern> PlaceholderImageHelper::DrawSvgAsync(Compositor compositor, hstring path, float intensity, bool negative, double rasterizationScale)
{
winrt::apartment_context ui_thread;
co_await winrt::resume_background();
ChatBackgroundPattern pattern{ nullptr };
try
{
pattern = DrawSvg(compositor, path, intensity, negative, rasterizationScale);
}
catch (...)
{
pattern = nullptr;
}
co_await ui_thread;
co_return pattern;
}
constexpr float PI = 3.14159265358979323846f;
inline static ChatBackgroundSymbol ParseGiftPattern(float topLeftX, float topLeftY, float topRightX, float topRightY, float bottomRightX, float bottomRightY, float bottomLeftX, float bottomLeftY)
{
ChatBackgroundSymbol pattern;
pattern.Offset = float2(topLeftX, topLeftY);
float dx_top = topRightX - topLeftX;
float dy_top = topRightY - topLeftY;
pattern.RotationAngle = atan2(dy_top, dx_top);
float dx_left = bottomLeftX - topLeftX;
float dy_left = bottomLeftY - topLeftY;
float width = sqrt(dx_top * dx_top + dy_top * dy_top);
float height = sqrt(dx_left * dx_left + dy_left * dy_left);
pattern.Size = float2(width, height);
return pattern;
}
inline static bool IsGzipCompressed(const char* data, size_t length)
{
if (length < 10) return false;
return (static_cast<unsigned char>(data[0]) == 0x1f &&
static_cast<unsigned char>(data[1]) == 0x8b);
}
inline static std::string DecompressFromFile(hstring path)
{
FILE* file;
_wfopen_s(&file, path.c_str(), L"rb");
if (file == NULL)
{
return "";
}
fseek(file, 0, SEEK_END);
size_t length = ftell(file);
fseek(file, 0, SEEK_SET);
if (length == 0)
{
fclose(file);
return "";
}
char* buffer = (char*)malloc(length);
if (!buffer)
{
fclose(file);
return "";
}
fread(buffer, 1, length, file);
fclose(file);
if (!IsGzipCompressed(buffer, length))
{
// Construct the string *before* freeing the buffer; the previous order read freed memory.
std::string raw(buffer, length);
free(buffer);
return raw;
}
z_stream stream = {};
if (inflateInit2(&stream, 15 + 16) != Z_OK)
{
free(buffer);
return "";
}
stream.next_in = reinterpret_cast<Bytef*>(buffer);
stream.avail_in = static_cast<uInt>(length);
std::string decompressed;
// Pre-size to avoid the append/realloc cascade that fragments the heap (gzip on these is ~3-5x).
decompressed.reserve(length * 4);
// One reusable stack buffer instead of allocating a vector on every inflate iteration.
char chunk[32768];
int ret;
do
{
stream.next_out = reinterpret_cast<Bytef*>(chunk);
stream.avail_out = static_cast<uInt>(sizeof(chunk));
ret = inflate(&stream, Z_NO_FLUSH);
if (ret != Z_OK && ret != Z_STREAM_END)
{
inflateEnd(&stream);
free(buffer);
return "";
}
decompressed.append(chunk, sizeof(chunk) - stream.avail_out);
} while (ret != Z_STREAM_END);
inflateEnd(&stream);
free(buffer);
return decompressed;
}
// Returns decompressed SVG bytes for the given file, caching results in a small LRU so repeated
// background re-renders don't re-read + gunzip the same file (which churns/fragments the heap).
// Must be called while holding m_criticalSection. nsvgParse mutates its input in place, so callers
// must copy the returned bytes into a local buffer before parsing.
const std::string& PlaceholderImageHelper::GetDecompressedSvg(hstring const& path)
{
std::wstring key(path.c_str());
auto found = m_svgCacheIndex.find(key);
if (found != m_svgCacheIndex.end())
{
// Promote to most-recently-used.
m_svgCacheList.splice(m_svgCacheList.begin(), m_svgCacheList, found->second);
return found->second->second;
}
auto decompressed = DecompressFromFile(path);
if (decompressed.empty())
{
// Don't cache failures (e.g. file not yet downloaded) so a later retry can re-read.
static const std::string empty;
return empty;
}
m_svgCacheList.emplace_front(key, std::move(decompressed));
m_svgCacheIndex[key] = m_svgCacheList.begin();
if (m_svgCacheList.size() > kSvgCacheCapacity)
{
m_svgCacheIndex.erase(m_svgCacheList.back().first);
m_svgCacheList.pop_back();
}
return m_svgCacheList.front().second;
}
ChatBackgroundPattern PlaceholderImageHelper::DrawSvg(Compositor compositor, hstring path, float intensity, bool negative, double rasterizationScale)
{
std::lock_guard const guard(m_criticalSection);
HRESULT result;
if (rasterizationScale < 1)
{
rasterizationScale = 1;
}
else if (rasterizationScale > 4)
{
rasterizationScale = 4;
}
auto scale = (int)(rasterizationScale * 100);
float rasterScale = (float)rasterizationScale;
float dpi = 0.25f * rasterScale;
// nsvgParse mutates its input buffer in place, so parse a copy of the cached bytes.
std::string data(GetDecompressedSvg(path));
auto patterns = winrt::single_threaded_vector<ChatBackgroundSymbol>();
struct NSVGimage* image;
image = nsvgParse((char*)data.c_str(), "px", 96);
auto unique = std::shared_ptr<NSVGimage>(image, [](NSVGimage* p)
{
nsvgDelete(p);
});
auto imageWidth = image->width;
auto imageHeight = image->height;
winrt::com_ptr<ID2D1SolidColorBrush> blackBrush;
winrt::com_ptr<abi::ICompositionGraphicsDevice> deviceInterop;
CompositionGraphicsDevice device{ nullptr };
CompositionDrawingSurface surface{ nullptr };
winrt::com_ptr<abi::ICompositionDrawingSurfaceInterop> surfaceInterop;
winrt::Windows::Foundation::Size imageSize(imageWidth * dpi, imageHeight * dpi);
winrt::com_ptr<ID2D1DeviceContext> d2dContext;
POINT offset;
auto compositorInterop = compositor.as<abi::ICompositorInterop>();
CleanupIfFailed(result, compositorInterop->CreateGraphicsDevice(m_d2dDevice.get(), deviceInterop.put()));
device = deviceInterop.as<CompositionGraphicsDevice>();
surface = device.CreateDrawingSurface(imageSize, DirectXPixelFormat::B8G8R8A8UIntNormalized, DirectXAlphaMode::Premultiplied);
surfaceInterop = surface.as<abi::ICompositionDrawingSurfaceInterop>();
// TODO: BeginDraw can return DXGI_ERROR_DEVICE_REMOVED, but it shouldn't be possible
// Because we always create a new composition graphics device (not great ndr, but we must use background instance not to block messages measure)
// And we handle device loss right before this method is invoked.
CleanupIfFailed(result, surfaceInterop->BeginDraw(nullptr, __uuidof(ID2D1DeviceContext), d2dContext.put_void(), &offset));
if (negative)
{
d2dContext->Clear(D2D1::ColorF(0, 0, 0, 1));
d2dContext->SetPrimitiveBlend(D2D1_PRIMITIVE_BLEND_COPY);
CleanupIfFailed(result, d2dContext->CreateSolidColorBrush(D2D1::ColorF(0, 0, 0, 1 - intensity), blackBrush.put()));
}
else
{
d2dContext->Clear(D2D1::ColorF(0, 0, 0, 0));
CleanupIfFailed(result, d2dContext->CreateSolidColorBrush(D2D1::ColorF(0, 0, 0, intensity), blackBrush.put()));
}
d2dContext->SetTransform(D2D1::Matrix3x2F::Scale(1 * dpi, 1 * dpi));
for (auto shape = image->shapes; shape != NULL; shape = shape->next)
{
if (!(shape->flags & NSVG_FLAGS_VISIBLE) || (shape->fill.type == NSVG_PAINT_NONE && shape->stroke.type == NSVG_PAINT_NONE))
{
continue;
}
if (strcmp(shape->id, "GiftPatterns") == 0)
{
if (shape->paths && shape->paths->npts == 13)
{
auto topLeftX = shape->paths->pts[0] * (1 * dpi);
auto topLeftY = shape->paths->pts[1] * (1 * dpi);
auto topRightX = shape->paths->pts[6] * (1 * dpi);
auto topRightY = shape->paths->pts[7] * (1 * dpi);
auto bottomRightX = shape->paths->pts[12] * (1 * dpi);
auto bottomRightY = shape->paths->pts[13] * (1 * dpi);
auto bottomLeftX = shape->paths->pts[18] * (1 * dpi);
auto bottomLeftY = shape->paths->pts[19] * (1 * dpi);
patterns.Append(ParseGiftPattern(topLeftX, topLeftY, topRightX, topRightY, bottomRightX, bottomRightY, bottomLeftX, bottomLeftY));
}
continue;
}
blackBrush->SetOpacity(shape->opacity);
winrt::com_ptr<ID2D1PathGeometry1> geometry;
CleanupIfFailed(result, m_d2dFactory->CreatePathGeometry(geometry.put()));
winrt::com_ptr<ID2D1GeometrySink> sink;
CleanupIfFailed(result, geometry->Open(sink.put()));
for (NSVGpath* path = shape->paths; path != NULL; path = path->next)
{
sink->BeginFigure({ path->pts[0], path->pts[1] }, D2D1_FIGURE_BEGIN_FILLED);
for (int i = 0; i < path->npts - 1; i += 3)
{
float* p = &path->pts[i * 2];
sink->AddBezier({ { p[2], p[3] }, { p[4], p[5] }, { p[6], p[7] } });
}
sink->EndFigure(path->closed ? D2D1_FIGURE_END_CLOSED : D2D1_FIGURE_END_OPEN);
}
CleanupIfFailed(result, sink->Close());
if (shape->fill.type != NSVG_PAINT_NONE)
{
switch (shape->fillRule)
{
case NSVG_FILLRULE_EVENODD:
sink->SetFillMode(D2D1_FILL_MODE_ALTERNATE);
break;
default:
sink->SetFillMode(D2D1_FILL_MODE_WINDING);
break;
}
winrt::com_ptr<ID2D1PathGeometry1> widenGeometry;
CleanupIfFailed(result, m_d2dFactory->CreatePathGeometry(widenGeometry.put()));
winrt::com_ptr<ID2D1GeometrySink> widenSink;
CleanupIfFailed(result, widenGeometry->Open(widenSink.put()));
geometry->Widen(0.25f * rasterizationScale / dpi, NULL, NULL, widenSink.get());
widenSink->Close();
d2dContext->FillGeometry(widenGeometry.get(), blackBrush.get());
d2dContext->FillGeometry(geometry.get(), blackBrush.get());
}
if (shape->stroke.type != NSVG_PAINT_NONE)
{
D2D1_STROKE_STYLE_PROPERTIES1 strokeProperties{};
strokeProperties.miterLimit = shape->miterLimit;
switch (shape->strokeLineCap)
{
case NSVG_CAP_BUTT:
strokeProperties.startCap = strokeProperties.endCap = D2D1_CAP_STYLE_FLAT;
break;
case NSVG_CAP_ROUND:
strokeProperties.startCap = strokeProperties.endCap = D2D1_CAP_STYLE_ROUND;
break;
case NSVG_CAP_SQUARE:
strokeProperties.startCap = strokeProperties.endCap = D2D1_CAP_STYLE_SQUARE;
break;
default:
break;
}
switch (shape->strokeLineJoin)
{
case NSVG_JOIN_BEVEL:
strokeProperties.lineJoin = D2D1_LINE_JOIN_BEVEL;
break;
case NSVG_JOIN_MITER:
strokeProperties.lineJoin = D2D1_LINE_JOIN_MITER;
break;
case NSVG_JOIN_ROUND:
strokeProperties.lineJoin = D2D1_LINE_JOIN_ROUND;
break;
default:
break;
}
winrt::com_ptr<ID2D1StrokeStyle1> strokeStyle;
CleanupIfFailed(result, m_d2dFactory->CreateStrokeStyle(strokeProperties, NULL, 0, strokeStyle.put()));
auto strokeWidth = std::max(1 * rasterScale / dpi, shape->strokeWidth);
d2dContext->DrawGeometry(geometry.get(), blackBrush.get(), strokeWidth, strokeStyle.get());
}
}
d2dContext->SetTransform(D2D1::Matrix3x2F::Identity());
CleanupIfFailed(result, surfaceInterop->EndDraw());
return ChatBackgroundPattern(surface, imageWidth, imageHeight, rasterizationScale, patterns);
Cleanup:
return nullptr;
}
SoftwareBitmap PlaceholderImageHelper::DrawBlurred(hstring fileName, float blurAmount)
{
std::lock_guard const guard(m_criticalSection);
HRESULT result;
HANDLE file = CreateFile2FromAppW(fileName.data(), GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, nullptr);
if (file == INVALID_HANDLE_VALUE)
{
return nullptr;
}
winrt::com_ptr<IWICBitmapDecoder> wicBitmapDecoder;
winrt::com_ptr<IWICBitmapFrameDecode> wicFrameDecode;
winrt::com_ptr<IWICFormatConverter> wicFormatConverter;
SoftwareBitmap bitmap{ nullptr };
CleanupIfFailed(result, m_wicFactory->CreateDecoderFromFileHandle(reinterpret_cast<ULONG_PTR>(file), nullptr, WICDecodeMetadataCacheOnDemand, wicBitmapDecoder.put()));
CleanupIfFailed(result, wicBitmapDecoder->GetFrame(0, wicFrameDecode.put()));
CleanupIfFailed(result, m_wicFactory->CreateFormatConverter(wicFormatConverter.put()));
CleanupIfFailed(result, wicFormatConverter->Initialize(wicFrameDecode.get(), GUID_WICPixelFormat32bppPBGRA, WICBitmapDitherTypeNone, nullptr, 0.f, WICBitmapPaletteTypeCustom));
CleanupIfFailed(result, DrawBlurredImpl(wicFormatConverter.get(), blurAmount, bitmap, false));
Cleanup:
CloseHandle(file);
return bitmap;
}
SoftwareBitmap PlaceholderImageHelper::DrawBlurred(IVector<uint8_t> bytes, float blurAmount)
{
std::lock_guard const guard(m_criticalSection);
HRESULT result;
winrt::com_ptr<IStream> stream;
auto bytesView = std::vector<byte>(bytes.begin(), bytes.end());
winrt::com_ptr<IWICBitmapDecoder> wicBitmapDecoder;
winrt::com_ptr<IWICBitmapFrameDecode> wicFrameDecode;
winrt::com_ptr<IWICFormatConverter> wicFormatConverter;
SoftwareBitmap bitmap{ nullptr };
CleanupIfFailed(result, CreateStreamOnHGlobal(nullptr, TRUE, stream.put()));
CleanupIfFailed(result, stream->Write(bytesView.data(), bytesView.size(), nullptr));
CleanupIfFailed(result, stream->Seek({ 0 }, STREAM_SEEK_SET, nullptr));
CleanupIfFailed(result, m_wicFactory->CreateDecoderFromStream(stream.get(), nullptr, WICDecodeMetadataCacheOnDemand, wicBitmapDecoder.put()));
CleanupIfFailed(result, wicBitmapDecoder->GetFrame(0, wicFrameDecode.put()));
CleanupIfFailed(result, m_wicFactory->CreateFormatConverter(wicFormatConverter.put()));
CleanupIfFailed(result, wicFormatConverter->Initialize(wicFrameDecode.get(), GUID_WICPixelFormat32bppPBGRA, WICBitmapDitherTypeNone, nullptr, 0.f, WICBitmapPaletteTypeCustom));
CleanupIfFailed(result, DrawBlurredImpl(wicFormatConverter.get(), blurAmount, bitmap, true));
Cleanup:
return bitmap;
}
HRESULT PlaceholderImageHelper::DrawBlurredImpl(IWICBitmapSource* wicBitmapSource, float blurAmount, SoftwareBitmap& bitmap, bool minithumbnail)
{
HRESULT result;
winrt::com_ptr<ID2D1ImageSourceFromWic> imageSource;
ReturnIfFailed(result, m_d2dContext->CreateImageSourceFromWic(wicBitmapSource, imageSource.put()));
D2D1_SIZE_U size;
ReturnIfFailed(result, wicBitmapSource->GetSize(&size.width, &size.height));
uint32_t totalPixels = size.width * size.height;
// Disabled for now
if (false && ((totalPixels <= 400 * 400 && blurAmount == 3) || (totalPixels <= 150 * 150 && blurAmount == 15)))
{
UINT bytesPerPixel = 4;
UINT stride = size.width * bytesPerPixel;
UINT bufferSize = stride * size.height;
bitmap = SoftwareBitmap(BitmapPixelFormat::Bgra8, size.width, size.height, BitmapAlphaMode::Premultiplied);
auto buffer = bitmap.LockBuffer(BitmapBufferAccessMode::Write);
auto reference = buffer.CreateReference();
auto pixels = reference.data();
WICRect rect = { 0, 0, static_cast<INT>(size.width), static_cast<INT>(size.height) };
ReturnIfFailed(result, wicBitmapSource->CopyPixels(&rect, stride, bufferSize, pixels));
if (blurAmount == 3)
{
if (totalPixels <= 100 * 100)
{
FixedRadius3Blur::ApplyBlur(pixels, size.width, size.height);
}
else
{
FixedRadius3BoxBlur::ApplyFastBlur(pixels, size.width, size.height);
}
}
else if (totalPixels <= 50 * 50)
{
FixedRadius15Blur::ApplyBlur(pixels, size.width, size.height);
}
else
{
FixedRadius15BoxBlur::ApplyFastBlur(pixels, size.width, size.height);
}
return S_OK;
}
winrt::com_ptr<ID2D1Bitmap1> targetBitmap;
D2D1_BITMAP_PROPERTIES1 properties = { { DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED }, 96, 96, D2D1_BITMAP_OPTIONS_TARGET, 0 };
ReturnIfFailed(result, m_d2dContext->CreateBitmap(size, nullptr, 0, &properties, targetBitmap.put()));
ReturnIfFailed(result, m_gaussianBlurEffect->SetValue(D2D1_GAUSSIANBLUR_PROP_STANDARD_DEVIATION, blurAmount));
m_gaussianBlurEffect->SetInput(0, imageSource.get());
m_d2dContext->SetTarget(targetBitmap.get());
m_d2dContext->BeginDraw();
//m_d2dContext->SetTransform(D2D1::Matrix3x2F::Identity());
m_d2dContext->Clear(D2D1::ColorF(ColorF::Black, 0.0f));
m_d2dContext->DrawImage(m_gaussianBlurEffect.get());
if ((result = m_d2dContext->EndDraw()) == D2DERR_RECREATE_TARGET)
{
ReturnIfFailed(result, CreateDeviceResources());
return DrawBlurredImpl(wicBitmapSource, blurAmount, bitmap, minithumbnail);
}
//winrt::com_ptr<IDXGISurface> surface;
//ReturnIfFailed(result, targetBitmap->GetSurface(surface.put()));
//winrt::Windows::Graphics::DirectX::Direct3D11::IDirect3DSurface direct3DSurface{ nullptr };
//ReturnIfFailed(result, CreateDirect3D11SurfaceFromDXGISurface(surface.get(), reinterpret_cast<::IInspectable**>(winrt::put_abi(direct3DSurface))));
//bitmap = SoftwareBitmap::CreateCopyFromSurfaceAsync(direct3DSurface, BitmapAlphaMode::Premultiplied).get();
//return result;
winrt::com_ptr<ID2D1Bitmap1> readBitmap;
D2D1_BITMAP_PROPERTIES1 properties2 = { { DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED }, 96, 96, D2D1_BITMAP_OPTIONS_CPU_READ | D2D1_BITMAP_OPTIONS_CANNOT_DRAW, 0 };
ReturnIfFailed(result, m_d2dContext->CreateBitmap(size, nullptr, 0, &properties2, readBitmap.put()));
D2D1_POINT_2U origin{ 0, 0 };
D2D1_RECT_U source{ 0, 0, size.width, size.height };
D2D1_MAPPED_RECT map;
ReturnIfFailed(result, readBitmap->CopyFromBitmap(&origin, targetBitmap.get(), &source));
ReturnIfFailed(result, readBitmap->Map(D2D1_MAP_OPTIONS_READ, &map));
// Fast path
uint32_t rowSizeBytes = size.width * 4;
if (map.pitch == rowSizeBytes)
{
uint32_t bufferSize = map.pitch * size.height;
winrt::array_view<const uint8_t> pixelData(
static_cast<const uint8_t*>(map.bits),
static_cast<const uint8_t*>(map.bits) + bufferSize
);
// BufferSurface here also works
auto buffer = winrt::Windows::Security::Cryptography::CryptographicBuffer::CreateFromByteArray(pixelData);
bitmap = SoftwareBitmap::CreateCopyFromBuffer(buffer, BitmapPixelFormat::Bgra8, size.width, size.height, BitmapAlphaMode::Premultiplied);
}
else
{
bitmap = SoftwareBitmap(BitmapPixelFormat::Bgra8, size.width, size.height, BitmapAlphaMode::Premultiplied);
auto buffer = bitmap.LockBuffer(BitmapBufferAccessMode::Write);
auto reference = buffer.CreateReference();
const uint8_t* srcRow = static_cast<const uint8_t*>(map.bits);
uint8_t* dstRow = reference.data();
for (uint32_t y = 0; y < size.height; ++y)
{
memcpy(dstRow, srcRow, rowSizeBytes);
srcRow += map.pitch;
dstRow += rowSizeBytes;
}
}
return readBitmap->Unmap();
}
PlaceholderImageHelper::PlaceholderImageHelper(Window window)
: m_window(window)
, m_compositor(nullptr)
, m_compositionDevice(nullptr)
, m_alphaMaskFactory(nullptr)
{
if (window)
{
m_compositor = window.Compositor();
}
winrt::check_hresult(CreateDeviceIndependentResources());
winrt::check_hresult(CreateDeviceResources());
}
HRESULT PlaceholderImageHelper::CreateDeviceIndependentResources()
{
if (m_compositor)
{