summaryrefslogtreecommitdiffstatshomepage
path: root/src/osd/modules/font/font_dwrite.cpp
blob: 725c8b9bc8104bfb6777d421b10eb8fe77a5da36 (plain) (blame)
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
// license:BSD-3-Clause
// copyright-holders:Aaron Giles, Brad Hughes
/*
* font_dwrite.c
*
*/

#include "font_module.h"
#include "modules/osdmodule.h"
#include "modules/lib/osdlib.h"

// We take dependencies on WRL client headers and
// we can only build with a high enough version
#if defined(OSD_WINDOWS) && (_WIN32_WINNT >= 0x0602)

#define WIN32_LEAN_AND_MEAN
#include <windows.h>

#include <memory>

// Windows Imaging Components
#include <wincodec.h>

// Load InitGuid after WIC to work around missing format problem
#include <initguid.h>

// Direct2D
#include <d2d1_1.h>
#include <dwrite_1.h>

// WIC GUIDs
DEFINE_GUID(CLSID_WICImagingFactory, 0xcacaf262, 0x9370, 0x4615, 0xa1, 0x3b, 0x9f, 0x55, 0x39, 0xda, 0x4c, 0xa);
DEFINE_GUID(GUID_WICPixelFormat8bppAlpha, 0xe6cd0116, 0xeeba, 0x4161, 0xaa, 0x85, 0x27, 0xdd, 0x9f, 0xb3, 0xa8, 0x95);

#include <wrl/client.h>
#undef interface

#include "strconv.h"
#include "corestr.h"
#include "winutil.h"

using namespace Microsoft::WRL;

//-------------------------------------------------
//  Some formulas and constants
//-------------------------------------------------

//#define DEFAULT_CELL_HEIGHT (200)
#define DEFAULT_EM_HEIGHT (166.5f)

// 1DIP = 1/96in vs 1pt = 1/72in (or 4 / 3)
static const float DIPS_PER_POINT = (4.0f / 3.0f);
static const float POINTS_PER_DIP = (3.0f / 4.0f);

//-------------------------------------------------
//  Error handling macros
//-------------------------------------------------

// Macro to check for a failed HRESULT and if failed, return 0
#define HR_RET( CALL, ret ) do { \
	result = CALL; \
	if (FAILED(result)) { \
		osd_printf_error(#CALL " failed with error 0x%X\n", (unsigned int)result); \
		return ret; } \
} while (0)

#define HR_RETHR( CALL ) HR_RET(CALL, result)
#define HR_RET0( CALL ) HR_RET(CALL, 0)
#define HR_RET1( CALL ) HR_RET(CALL, 1)

struct osd_deleter
{
	void operator () (void * osd_pointer) const
	{
		osd_free(osd_pointer);
	}
};

typedef std::unique_ptr<char, osd_deleter> osd_utf8_ptr;

// Typedefs for dynamically loaded functions
typedef HRESULT (WINAPI *d2d_create_factory_fn)(D2D1_FACTORY_TYPE, REFIID, const D2D1_FACTORY_OPTIONS *, void **);
typedef HRESULT (WINAPI *dwrite_create_factory_fn)(DWRITE_FACTORY_TYPE, REFIID, IUnknown **);

// Debugging functions
#ifdef DWRITE_DEBUGGING

//-------------------------------------------------
//  Save image to file
//-------------------------------------------------

HRESULT SaveBitmap(IWICBitmap* bitmap, GUID pixelFormat, const WCHAR *filename)
{
	HRESULT result = S_OK;
	ComPtr<IWICStream> stream;
	ComPtr<ID2D1Factory1> d2dfactory;
	ComPtr<IDWriteFactory> dwriteFactory;
	ComPtr<IWICImagingFactory> wicFactory;

	osd::dynamic_module::ptr d2d1_dll = osd::dynamic_module::open({ "d2d1.dll" });
	osd::dynamic_module::ptr dwrite_dll = osd::dynamic_module::open({ "dwrite.dll" });

	d2d_create_factory_fn pfn_D2D1CreateFactory = d2d1_dll->bind<d2d_create_factory_fn>("D2D1CreateFactory");
	dwrite_create_factory_fn pfn_DWriteCreateFactory = dwrite_dll->bind<dwrite_create_factory_fn>("DWriteCreateFactory");

	if (!pfn_D2D1CreateFactory || !pfn_DWriteCreateFactory)
		return ERROR_DLL_NOT_FOUND;

	// Create a Direct2D factory
	HR_RETHR((*pfn_D2D1CreateFactory)(
		D2D1_FACTORY_TYPE_SINGLE_THREADED,
		__uuidof(ID2D1Factory1),
		nullptr,
		reinterpret_cast<void**>(d2dfactory.GetAddressOf())));

	// Initialize COM - ignore failure
	CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);

	// Create a DirectWrite factory.
	HR_RETHR((*pfn_DWriteCreateFactory)(
		DWRITE_FACTORY_TYPE_SHARED,
		__uuidof(IDWriteFactory),
		reinterpret_cast<IUnknown **>(dwriteFactory.GetAddressOf())));

	HR_RETHR(CoCreateInstance(
		CLSID_WICImagingFactory,
		nullptr,
		CLSCTX_INPROC_SERVER,
		__uuidof(IWICImagingFactory),
		(void**)&wicFactory));

	HR_RETHR(wicFactory->CreateStream(&stream));
	HR_RETHR(stream->InitializeFromFilename(filename, GENERIC_WRITE));

	ComPtr<IWICBitmapEncoder> encoder;
	HR_RETHR(wicFactory->CreateEncoder(GUID_ContainerFormatBmp, nullptr, &encoder));
	HR_RETHR(encoder->Initialize(stream.Get(), WICBitmapEncoderNoCache));

	ComPtr<IWICBitmapFrameEncode> frameEncode;
	HR_RETHR(encoder->CreateNewFrame(&frameEncode, nullptr));
	HR_RETHR(frameEncode->Initialize(nullptr));

	UINT width, height;
	HR_RETHR(bitmap->GetSize(&width, &height));
	HR_RETHR(frameEncode->SetSize(width, height));
	HR_RETHR(frameEncode->SetPixelFormat(&pixelFormat));

	HR_RETHR(frameEncode->WriteSource(bitmap, nullptr));

	HR_RETHR(frameEncode->Commit());
	HR_RETHR(encoder->Commit());

	return S_OK;
}

HRESULT SaveBitmap2(bitmap_argb32 &bitmap, const WCHAR *filename)
{
	HRESULT result;

	// Convert the bitmap into a form we understand and save it
	std::unique_ptr<UINT32> pBitmap(new UINT32[bitmap.width() * bitmap.height()]);
	for (int y = 0; y < bitmap.height(); y++)
	{
		UINT32* pRow = pBitmap.get() + (y * bitmap.width());
		for (int x = 0; x < bitmap.width(); x++)
		{
			UINT32 pixel = bitmap.pix32(y, x);
			pRow[x] = (pixel == 0xFFFFFFFF) ? rgb_t(0xFF, 0x00, 0x00, 0x00) : rgb_t(0xFF, 0xFF, 0xFF, 0xFF);
		}
	}

	ComPtr<IWICImagingFactory> wicFactory;
	HR_RETHR(CoCreateInstance(
		CLSID_WICImagingFactory,
		nullptr,
		CLSCTX_INPROC_SERVER,
		__uuidof(IWICImagingFactory),
		(void**)&wicFactory));

	// Save bitmap
	ComPtr<IWICBitmap> bmp2 = nullptr;
	wicFactory->CreateBitmapFromMemory(
		bitmap.width(),
		bitmap.height(),
		GUID_WICPixelFormat32bppRGBA,
		bitmap.width() * sizeof(UINT32),
		bitmap.width() * bitmap.height() * sizeof(UINT32),
		(BYTE*)pBitmap.get(),
		&bmp2);

	SaveBitmap(bmp2.Get(), GUID_WICPixelFormat32bppRGBA, filename);

	return S_OK;
}

#endif

//-------------------------------------------------
//  FontDimension class - holds a font dimension
//  and makes it availabile in different formats
//-------------------------------------------------

class FontDimension
{
private:
	UINT16  m_designUnitsPerEm;
	float   m_emSizeInDip;
	float   m_designUnits;

public:
	FontDimension(UINT16 designUnitsPerEm, float emSizeInDip, float designUnits)
	{
		m_designUnitsPerEm = designUnitsPerEm;
		m_emSizeInDip = emSizeInDip;
		m_designUnits = designUnits;
	}

	UINT16 DesignUnitsPerEm() const
	{
		return m_designUnitsPerEm;
	}

	float EmSizeInDip() const
	{
		return m_emSizeInDip;
	}

	float DesignUnits() const
	{
		return m_designUnits;
	}

	int Dips() const
	{
		return static_cast<int>(floor((m_designUnits * m_emSizeInDip) / m_designUnitsPerEm));
	}

	float Points() const
	{
		return Dips() * POINTS_PER_DIP;
	}

	FontDimension operator-(const FontDimension &other) const
	{
		if (m_designUnitsPerEm != other.m_designUnitsPerEm || m_emSizeInDip != other.m_emSizeInDip)
		{
			throw emu_fatalerror("Attempted subtraction of FontDimension with different scale.");
		}

		return FontDimension(m_designUnitsPerEm, m_emSizeInDip, m_designUnits - other.m_designUnits);
	}

	FontDimension operator+(const FontDimension &other) const
	{
		if (m_designUnitsPerEm != other.m_designUnitsPerEm || m_emSizeInDip != other.m_emSizeInDip)
		{
			throw emu_fatalerror("Attempted addition of FontDimension with different scale.");
		}

		return FontDimension(m_designUnitsPerEm, m_emSizeInDip, m_designUnits + other.m_designUnits);
	}
};

//-------------------------------------------------
//  FontABCWidths class - hold width-related
//  font dimensions for a glyph
//-------------------------------------------------

class FontABCWidths
{
private:
	FontDimension m_advanceWidth;
	FontDimension m_a;
	FontDimension m_c;

public:
	FontABCWidths(const FontDimension &advanceWidth, const FontDimension &leftSideBearing, const FontDimension &rightsideBearing) :
		m_advanceWidth(advanceWidth),
		m_a(leftSideBearing),
		m_c(rightsideBearing)
	{
	}

	FontDimension advanceWidth() const { return m_advanceWidth; }
	FontDimension abcA() const { return m_a; }

	// Relationship between advanceWidth and B is ADV = A + B + C so B = ADV - A - C
	FontDimension abcB() const { return advanceWidth() - abcA() - abcC(); }
	FontDimension abcC() const { return m_c; }
};

//-------------------------------------------------
//  FontDimensionFactory class - simple way of
//  creating font dimensions
//-------------------------------------------------

class FontDimensionFactory
{
private:
	UINT16 m_designUnitsPerEm;
	float m_emSizeInDip;

public:
	float EmSizeInDip() const
	{
		return m_emSizeInDip;
	}

	FontDimensionFactory(UINT16 designUnitsPerEm, float emSizeInDip)
	{
		m_designUnitsPerEm = designUnitsPerEm;
		m_emSizeInDip = emSizeInDip;
	}

	FontDimension FromDip(float dip) const
	{
		float sizeInDesignUnits = (dip / m_emSizeInDip) * m_designUnitsPerEm;
		return FontDimension(m_designUnitsPerEm, m_emSizeInDip, sizeInDesignUnits);
	}

	FontDimension FromDesignUnit(float designUnits) const
	{
		return FontDimension(m_designUnitsPerEm, m_emSizeInDip, designUnits);
	}

	FontDimension FromPoint(float pointSize) const
	{
		float sizeInDip = pointSize * (4.0f / 3.0f);
		float sizeInDesignUnits = (sizeInDip / m_emSizeInDip) * m_designUnitsPerEm;
		return FontDimension(m_designUnitsPerEm, m_emSizeInDip, sizeInDesignUnits);
	}

	FontABCWidths CreateAbcWidths(float advanceWidth, float leftSideBearing, float rightSideBearing) const
	{
		return FontABCWidths(
			FromDesignUnit(advanceWidth),
			FromDesignUnit(leftSideBearing),
			FromDesignUnit(rightSideBearing));
	}
};

//-------------------------------------------------
//  font_open - attempt to "open" a handle to the
//  font with the given name
//-------------------------------------------------

class osd_font_dwrite : public osd_font
{
private:
	ComPtr<ID2D1Factory>            m_d2dfactory;
	ComPtr<IDWriteFactory>          m_dwriteFactory;
	ComPtr<IWICImagingFactory>      m_wicFactory;
	ComPtr<IDWriteFont>             m_font;
	float                           m_fontEmHeightInDips;

public:
	osd_font_dwrite(ComPtr<ID2D1Factory> d2dfactory, ComPtr<IDWriteFactory> dwriteFactory, ComPtr<IWICImagingFactory> wicFactory)
		: m_d2dfactory(d2dfactory), m_dwriteFactory(dwriteFactory), m_wicFactory(wicFactory), m_fontEmHeightInDips(0)
	{
	}

	virtual bool open(std::string const &font_path, std::string const &_name, int &height) override
	{
		if (m_d2dfactory == nullptr || m_dwriteFactory == nullptr || m_wicFactory == nullptr)
			return false;

		HRESULT result;

		// accept qualifiers from the name
		std::string name(_name);
		if (name.compare("default") == 0) name = "Tahoma";
		bool bold = (strreplace(name, "[B]", "") + strreplace(name, "[b]", "") > 0);
		bool italic = (strreplace(name, "[I]", "") + strreplace(name, "[i]", "") > 0);

		// convert the face name
		std::unique_ptr<WCHAR, void(*)(void *)> familyName(wstring_from_utf8(name.c_str()), osd_free);

		// find the font
		HR_RET0(find_font(
			familyName.get(),
			bold ? DWRITE_FONT_WEIGHT_BOLD : DWRITE_FONT_WEIGHT_NORMAL,
			DWRITE_FONT_STRETCH_NORMAL,
			italic ? DWRITE_FONT_STYLE_ITALIC : DWRITE_FONT_STYLE_NORMAL,
			m_font.GetAddressOf()));

		DWRITE_FONT_METRICS metrics;
		m_font->GetMetrics(&metrics);

		m_fontEmHeightInDips = DEFAULT_EM_HEIGHT;
		height = static_cast<int>(round(m_fontEmHeightInDips * DIPS_PER_POINT));

		return true;
	}

	//-------------------------------------------------
	//  font_close - release resources associated with
	//  a given OSD font
	//-------------------------------------------------

	virtual void close() override
	{
		m_font = nullptr;
		m_fontEmHeightInDips = 0;
	}

	//-------------------------------------------------
	//  font_get_bitmap - allocate and populate a
	//  BITMAP_FORMAT_ARGB32 bitmap containing the
	//  pixel values rgb_t(0xff,0xff,0xff,0xff)
	//  or rgb_t(0x00,0xff,0xff,0xff) for each
	//  pixel of a black & white font
	//-------------------------------------------------

	virtual bool get_bitmap(unicode_char chnum, bitmap_argb32 &bitmap, std::int32_t &width, std::int32_t &xoffs, std::int32_t &yoffs) override
	{
		const int MEM_ALIGN_CONST = 31;
		const int BITMAP_PAD = 50;

		HRESULT result;
		UINT cbData;
		BYTE* pixels = nullptr;

		ComPtr<ID2D1BitmapRenderTarget>     target;
		ComPtr<ID2D1SolidColorBrush>        pWhiteBrush;
		ComPtr<IWICBitmap>                  wicBitmap;
		ComPtr<IWICBitmapLock>              lock;

		ComPtr<IDWriteFontFace> face;
		HR_RET0(m_font->CreateFontFace(face.GetAddressOf()));

		// get the GDI metrics
		DWRITE_FONT_METRICS gdi_metrics;
		HR_RET0(face->GetGdiCompatibleMetrics(
			m_fontEmHeightInDips,
			1.0f,
			nullptr,
			&gdi_metrics));

		FontDimensionFactory fdf(gdi_metrics.designUnitsPerEm, m_fontEmHeightInDips);

		UINT32 tempChar = chnum;
		UINT16 glyphIndex;
		HR_RET0(face->GetGlyphIndicesW(&tempChar, 1, &glyphIndex));

		// get the width of this character
		DWRITE_GLYPH_METRICS glyph_metrics = { 0 };
		HR_RET0(face->GetGdiCompatibleGlyphMetrics(
			m_fontEmHeightInDips,
			1.0f,
			nullptr,
			FALSE,
			&glyphIndex,
			1,
			&glyph_metrics));

		// The height is the ascent added to the descent
		// By definition, the Em is equal to Cell Height minus Internal Leading (topSide bearing).
		//auto cellheight = fdf.FromDesignUnit(gdi_metrics.ascent + gdi_metrics.descent + gdi_metrics.);
		auto ascent = fdf.FromDesignUnit(gdi_metrics.ascent);
		auto descent = fdf.FromDesignUnit(gdi_metrics.descent);
		auto charHeight = ascent + descent;

		auto abc = fdf.CreateAbcWidths(
			glyph_metrics.advanceWidth,
			glyph_metrics.leftSideBearing,
			glyph_metrics.rightSideBearing);

		width = abc.abcA().Dips() + abc.abcB().Dips() + abc.abcC().Dips();

		// determine desired bitmap size
		int bmwidth = (BITMAP_PAD + abc.abcA().Dips() + abc.abcB().Dips() + abc.abcC().Dips() + BITMAP_PAD + MEM_ALIGN_CONST) & ~MEM_ALIGN_CONST;
		int bmheight = BITMAP_PAD + charHeight.Dips() + BITMAP_PAD;

		// GUID_WICPixelFormat8bppAlpha is 8 bits per pixel
		const REFWICPixelFormatGUID     source_bitmap_wic_format = GUID_WICPixelFormat8bppAlpha;
		const DXGI_FORMAT               source_bitmap_dxgi_format = DXGI_FORMAT_A8_UNORM;
		const D2D1_ALPHA_MODE           source_bitmap_d2d_alpha_mode = D2D1_ALPHA_MODE_STRAIGHT;

		// describe the bitmap we want
		HR_RET0(m_wicFactory->CreateBitmap(
			bmwidth,
			bmheight,
			source_bitmap_wic_format,
			WICBitmapCacheOnLoad,
			wicBitmap.GetAddressOf()));

		D2D1_RENDER_TARGET_PROPERTIES targetProps;
		targetProps = D2D1::RenderTargetProperties();
		targetProps.pixelFormat = D2D1::PixelFormat(source_bitmap_dxgi_format, source_bitmap_d2d_alpha_mode);

		// create a DIB to render to
		HR_RET0(this->m_d2dfactory->CreateWicBitmapRenderTarget(
			wicBitmap.Get(),
			&targetProps,
			reinterpret_cast<ID2D1RenderTarget**>(target.GetAddressOf())));

		target->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_ALIASED);

		// Create our brush
		HR_RET0(target->CreateSolidColorBrush(D2D1::ColorF(1.0f, 1.0f, 1.0f, 1.0f), pWhiteBrush.GetAddressOf()));

		// Signal the start of the frame
		target->BeginDraw();

		// clear the bitmap
		// In the alpha mask, it will look like 0x00 per pixel
		target->Clear(D2D1::ColorF(0.0f, 0.0f, 0.0f, 0.0f));

		// now draw the character
		DWRITE_GLYPH_RUN run = { nullptr };
		DWRITE_GLYPH_OFFSET offsets;
		offsets.advanceOffset = 0;
		offsets.ascenderOffset = 0;
		float advanceWidth = abc.advanceWidth().Dips();

		run.fontEmSize = m_fontEmHeightInDips;
		run.fontFace = face.Get();
		run.glyphCount = 1;
		run.glyphIndices = &glyphIndex;
		run.glyphAdvances = &advanceWidth;
		run.glyphOffsets = &offsets;

		auto baseline_origin = D2D1::Point2F(BITMAP_PAD + abc.abcA().Dips() + 1, BITMAP_PAD + ascent.Dips());
		target->DrawGlyphRun(
			baseline_origin,
			&run,
			pWhiteBrush.Get(),
			DWRITE_MEASURING_MODE_GDI_CLASSIC);

		HR_RET0(target->EndDraw());

#ifdef DWRITE_DEBUGGING
		// Save to file for debugging
		SaveBitmap(wicBitmap.Get(), GUID_WICPixelFormatBlackWhite, L"C:\\temp\\ddraw_step1.bmp");
#endif

		// characters are expected to be full-height
		rectangle actbounds;
		actbounds.min_y = BITMAP_PAD;
		actbounds.max_y = BITMAP_PAD + charHeight.Dips() - 1;

		// Lock the bitmap and get the data pointer
		WICRect rect = { 0, 0, bmwidth, bmheight };
		HR_RET0(wicBitmap->Lock(&rect, WICBitmapLockRead, lock.GetAddressOf()));
		HR_RET0(lock->GetDataPointer(&cbData, static_cast<BYTE**>(&pixels)));

		// determine the actual left of the character
		for (actbounds.min_x = 0; actbounds.min_x < bmwidth; actbounds.min_x++)
		{
			BYTE *offs = pixels + actbounds.min_x;
			UINT8 summary = 0;
			for (int y = 0; y < bmheight; y++)
				summary |= offs[y * bmwidth];
			if (summary != 0)
			{
				break;
			}
		}

		// determine the actual right of the character
		// Start from the right edge, and move in until we find a pixel
		for (actbounds.max_x = bmwidth - 1; actbounds.max_x >= 0; actbounds.max_x--)
		{
			BYTE *offs = pixels + actbounds.max_x;
			UINT8 summary = 0;

			// Go through the entire column and build a summary
			for (int y = 0; y < bmheight; y++)
				summary |= offs[y * bmwidth];
			if (summary != 0)
			{
				break;
			}
		}

		// allocate a new bitmap
		if (actbounds.max_x >= actbounds.min_x && actbounds.max_y >= actbounds.min_y)
		{
			bitmap.allocate(actbounds.max_x + 1 - actbounds.min_x, actbounds.max_y + 1 - actbounds.min_y);

			// copy the bits into it
			for (int y = 0; y < bitmap.height(); y++)
			{
				UINT32 *dstrow = &bitmap.pix32(y);
				UINT8 *srcrow = &pixels[(y + actbounds.min_y) * bmwidth];
				for (int x = 0; x < bitmap.width(); x++)
				{
					int effx = x + actbounds.min_x;
					dstrow[x] = rgb_t(srcrow[effx], 0xff, 0xff, 0xff);
				}
			}

			// set the final offset values
			xoffs = actbounds.min_x - (BITMAP_PAD + abc.abcA().Dips());
			yoffs = actbounds.max_y - (BITMAP_PAD + ascent.Dips());

#ifdef DWRITE_DEBUGGING
			SaveBitmap2(bitmap, L"C:\\temp\\dwrite_final.bmp");
#endif
		}

		BOOL success = bitmap.valid();

#ifdef DWRITE_DEBUGGING
		osd_printf_debug(
			"dwr: %s, c'%S' w%i x%i y%i asc%i dsc%i a%ib%ic%i\n",
			success ? "Success" : "Error",
			(WCHAR*)&chnum,
			width,
			xoffs,
			yoffs,
			ascent.Dips(),
			descent.Dips(),
			abc.abcA().Dips(),
			abc.abcB().Dips(),
			abc.abcC().Dips());
#endif
		return success;
	}

private:

	//-------------------------------------------------
	//  find_font - finds a font, given attributes
	//-------------------------------------------------

	HRESULT find_font(std::wstring familyName, DWRITE_FONT_WEIGHT weight, DWRITE_FONT_STRETCH stretch, DWRITE_FONT_STYLE style, IDWriteFont ** ppfont) const
	{
		HRESULT result;

		ComPtr<IDWriteFontCollection> fonts;
		HR_RETHR(m_dwriteFactory->GetSystemFontCollection(fonts.GetAddressOf()));

		UINT family_index; BOOL exists;
		HR_RETHR(fonts->FindFamilyName(familyName.c_str(), &family_index, &exists));
		if (!exists)
		{
			osd_printf_error("Font with family name %S does not exist", familyName.c_str());
			return E_FAIL;
		}

		ComPtr<IDWriteFontFamily> family;
		HR_RETHR(fonts->GetFontFamily(family_index, family.GetAddressOf()));

		ComPtr<IDWriteFont> font;
		HR_RETHR(family->GetFirstMatchingFont(weight, stretch, style, font.GetAddressOf()));

		*ppfont = font.Detach();
		return result;
	}
};

//-------------------------------------------------
//  font_dwrite - the DirectWrite font module
//-------------------------------------------------

class font_dwrite : public osd_module, public font_module
{
private:
	osd::dynamic_module::ptr   m_d2d1_dll;
	osd::dynamic_module::ptr   m_dwrite_dll;
	d2d_create_factory_fn      m_pfnD2D1CreateFactory;
	dwrite_create_factory_fn   m_pfnDWriteCreateFactory;
	ComPtr<ID2D1Factory>       m_d2dfactory;
	ComPtr<IDWriteFactory>     m_dwriteFactory;
	ComPtr<IWICImagingFactory> m_wicFactory;

public:
	font_dwrite() :
		osd_module(OSD_FONT_PROVIDER, "dwrite"),
		font_module(),
		m_d2dfactory(nullptr),
		m_dwriteFactory(nullptr),
		m_wicFactory(nullptr)
	{
	}

	virtual bool probe() override
	{
		m_d2d1_dll = osd::dynamic_module::open({ "d2d1.dll" });
		m_dwrite_dll = osd::dynamic_module::open({ "dwrite.dll" });

		m_pfnD2D1CreateFactory = m_d2d1_dll->bind<d2d_create_factory_fn>("D2D1CreateFactory");
		m_pfnDWriteCreateFactory = m_dwrite_dll->bind<dwrite_create_factory_fn>("DWriteCreateFactory");

		// This module is available if it can load the expected API Functions
		if (!m_pfnD2D1CreateFactory || !m_pfnDWriteCreateFactory)
			return false;

		return true;
	}

	virtual int init(const osd_options &options) override
	{
		HRESULT result;

		osd_printf_verbose("FontProvider: Initializing DirectWrite\n");

		// Make sure we can initialize our api functions
		if (!m_pfnD2D1CreateFactory || !m_pfnDWriteCreateFactory)
		{
			osd_printf_error("ERROR: FontProvider: Failed to load DirectWrite functions.\n");
			return -1;
		}

		// Create a Direct2D factory.
		HR_RET1((*m_pfnD2D1CreateFactory)(
			D2D1_FACTORY_TYPE_SINGLE_THREADED,
			__uuidof(ID2D1Factory),
			nullptr,
			reinterpret_cast<void**>(this->m_d2dfactory.GetAddressOf())));

		// Initialize COM
		CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);

		// Create a DirectWrite factory.
		HR_RET1((*m_pfnDWriteCreateFactory)(
			DWRITE_FACTORY_TYPE_SHARED,
			__uuidof(IDWriteFactory),
			reinterpret_cast<IUnknown **>(m_dwriteFactory.GetAddressOf())));

		HR_RET1(CoCreateInstance(
			CLSID_WICImagingFactory,
			nullptr,
			CLSCTX_INPROC_SERVER,
			__uuidof(IWICImagingFactory),
			static_cast<void**>(&m_wicFactory)));

		osd_printf_verbose("FontProvider: DirectWrite initialized successfully.\n");
		return 0;
	}

	virtual osd_font::ptr font_alloc() override
	{
		return std::make_unique<osd_font_dwrite>(m_d2dfactory, m_dwriteFactory, m_wicFactory);
	}

	virtual bool get_font_families(std::string const &font_path, std::vector<std::pair<std::string, std::string> > &fontresult) override
	{
		HRESULT result;
		ComPtr<IDWriteFontFamily> family;
		ComPtr<IDWriteLocalizedStrings> names;

		// For now, we're just enumerating system fonts, if we want to support custom font
		// collections, there's more work that neeeds to be done
		ComPtr<IDWriteFontCollection> fonts;
		HR_RET0(m_dwriteFactory->GetSystemFontCollection(fonts.GetAddressOf()));

		int family_count = fonts->GetFontFamilyCount();
		for (int i = 0; i < family_count; i++)
		{
			HR_RET0(fonts->GetFontFamily(i, family.ReleaseAndGetAddressOf()));

			HR_RET0(family->GetFamilyNames(names.ReleaseAndGetAddressOf()));

			std::unique_ptr<WCHAR[]> name = nullptr;
			HR_RET0(get_localized_familyname(names, name));

			auto utf8_name = osd_utf8_ptr(utf8_from_wstring(name.get()));
			name.reset();

			// Review: should the config name, be unlocalized?
			// maybe the english name?
			fontresult.push_back(
				make_pair(
					std::string(utf8_name.get()),
					std::string(utf8_name.get())));

			utf8_name.reset();
		}

		std::stable_sort(fontresult.begin(), fontresult.end());
		return true;
	}

private:
	HRESULT get_family_for_locale(ComPtr<IDWriteLocalizedStrings> family_names, const WCHAR* locale, std::unique_ptr<WCHAR[]> &family_name) const
	{
		HRESULT result;
		UINT32 index;
		BOOL exists = false;

		result = family_names->FindLocaleName(locale, &index, &exists);

		// if the above find did not find a match, retry with US English
		if (SUCCEEDED(result) && !exists)
			family_names->FindLocaleName(L"en-us", &index, &exists);

		// If the specified locale doesn't exist, select the first on the list.
		if (!exists)
			index = 0;

		// Get the length and allocate our buffer
		UINT32 name_length = 0;
		HR_RETHR(family_names->GetStringLength(index, &name_length));
		auto name_buffer = std::make_unique<WCHAR[]>(name_length + 1);

		// Get the name
		HR_RETHR(family_names->GetString(index, name_buffer.get(), name_length + 1));

		family_name = std::move(name_buffer);
		return S_OK;
	}

	HRESULT get_localized_familyname(ComPtr<IDWriteLocalizedStrings> family_names, std::unique_ptr<WCHAR[]> &family_name) const
	{
		wchar_t localeName[LOCALE_NAME_MAX_LENGTH];

		// Get the default locale for this user.
		int defaultLocaleSuccess = GetUserDefaultLocaleName(localeName, LOCALE_NAME_MAX_LENGTH);

		// If the default locale is returned, find that locale name, otherwise use "en-us".
		if (defaultLocaleSuccess)
			return get_family_for_locale(family_names, localeName, family_name);

		// If locale can't be determined, fall back to US English
		return get_family_for_locale(family_names, L"en-us", family_name);
	}
};

#else
MODULE_NOT_SUPPORTED(font_dwrite, OSD_FONT_PROVIDER, "dwrite")
#endif

MODULE_DEFINITION(FONT_DWRITE, font_dwrite)