Update Scintilla to version 3.5.2
[TortoiseGit.git] / ext / scintilla / win32 / PlatWin.cxx
blob84cdca0d4de1ff963aa383c2bc413ab1897be403
1 // Scintilla source code edit control
2 /** @file PlatWin.cxx
3 ** Implementation of platform facilities on Windows.
4 **/
5 // Copyright 1998-2003 by Neil Hodgson <neilh@scintilla.org>
6 // The License.txt file describes the conditions under which this software may be distributed.
8 #include <stdlib.h>
9 #include <string.h>
10 #include <stdio.h>
11 #include <stdarg.h>
12 #include <time.h>
13 #include <math.h>
14 #include <ctype.h>
15 #include <limits.h>
17 #include <vector>
18 #include <map>
20 #undef _WIN32_WINNT
21 #define _WIN32_WINNT 0x0500
22 #undef WINVER
23 #define WINVER 0x0500
24 #include <windows.h>
25 #include <commctrl.h>
26 #include <richedit.h>
27 #include <windowsx.h>
29 #if defined(NTDDI_WIN7) && !defined(DISABLE_D2D)
30 #define USE_D2D 1
31 #endif
33 #if defined(USE_D2D)
34 #include <d2d1.h>
35 #include <dwrite.h>
36 #endif
38 #include "Platform.h"
39 #include "StringCopy.h"
40 #include "XPM.h"
41 #include "UniConversion.h"
42 #include "FontQuality.h"
44 #ifndef IDC_HAND
45 #define IDC_HAND MAKEINTRESOURCE(32649)
46 #endif
48 #ifndef SPI_GETFONTSMOOTHINGCONTRAST
49 #define SPI_GETFONTSMOOTHINGCONTRAST 0x200C
50 #endif
52 static void *PointerFromWindow(HWND hWnd) {
53 return reinterpret_cast<void *>(::GetWindowLongPtr(hWnd, 0));
56 static void SetWindowPointer(HWND hWnd, void *ptr) {
57 ::SetWindowLongPtr(hWnd, 0, reinterpret_cast<LONG_PTR>(ptr));
60 extern UINT CodePageFromCharSet(DWORD characterSet, UINT documentCodePage);
62 // Declarations needed for functions dynamically loaded as not available on all Windows versions.
63 typedef BOOL (WINAPI *AlphaBlendSig)(HDC, int, int, int, int, HDC, int, int, int, int, BLENDFUNCTION);
64 typedef HMONITOR (WINAPI *MonitorFromPointSig)(POINT, DWORD);
65 typedef HMONITOR (WINAPI *MonitorFromRectSig)(LPCRECT, DWORD);
66 typedef BOOL (WINAPI *GetMonitorInfoSig)(HMONITOR, LPMONITORINFO);
68 static CRITICAL_SECTION crPlatformLock;
69 static HINSTANCE hinstPlatformRes = 0;
70 static bool onNT = false;
72 static HMODULE hDLLImage = 0;
73 static AlphaBlendSig AlphaBlendFn = 0;
75 static HMODULE hDLLUser32 = 0;
76 static HMONITOR (WINAPI *MonitorFromPointFn)(POINT, DWORD) = 0;
77 static HMONITOR (WINAPI *MonitorFromRectFn)(LPCRECT, DWORD) = 0;
78 static BOOL (WINAPI *GetMonitorInfoFn)(HMONITOR, LPMONITORINFO) = 0;
80 static HCURSOR reverseArrowCursor = NULL;
82 #ifdef SCI_NAMESPACE
83 namespace Scintilla {
84 #endif
86 bool IsNT() {
87 return onNT;
90 Point Point::FromLong(long lpoint) {
91 return Point(static_cast<short>(LOWORD(lpoint)), static_cast<short>(HIWORD(lpoint)));
94 static RECT RectFromPRectangle(PRectangle prc) {
95 RECT rc = {static_cast<LONG>(prc.left), static_cast<LONG>(prc.top),
96 static_cast<LONG>(prc.right), static_cast<LONG>(prc.bottom)};
97 return rc;
100 #if defined(USE_D2D)
101 IDWriteFactory *pIDWriteFactory = 0;
102 ID2D1Factory *pD2DFactory = 0;
103 IDWriteRenderingParams *defaultRenderingParams = 0;
104 IDWriteRenderingParams *customClearTypeRenderingParams = 0;
106 static HMODULE hDLLD2D = NULL;
107 static HMODULE hDLLDWrite = NULL;
109 bool LoadD2D() {
110 static bool triedLoadingD2D = false;
111 if (!triedLoadingD2D) {
112 typedef HRESULT (WINAPI *D2D1CFSig)(D2D1_FACTORY_TYPE factoryType, REFIID riid,
113 CONST D2D1_FACTORY_OPTIONS *pFactoryOptions, IUnknown **factory);
114 typedef HRESULT (WINAPI *DWriteCFSig)(DWRITE_FACTORY_TYPE factoryType, REFIID iid,
115 IUnknown **factory);
117 hDLLD2D = ::LoadLibraryEx(TEXT("D2D1.DLL"), 0, 0x00000800 /*LOAD_LIBRARY_SEARCH_SYSTEM32*/);
118 if (hDLLD2D) {
119 D2D1CFSig fnD2DCF = (D2D1CFSig)::GetProcAddress(hDLLD2D, "D2D1CreateFactory");
120 if (fnD2DCF) {
121 // A single threaded factory as Scintilla always draw on the GUI thread
122 fnD2DCF(D2D1_FACTORY_TYPE_SINGLE_THREADED,
123 __uuidof(ID2D1Factory),
125 reinterpret_cast<IUnknown**>(&pD2DFactory));
128 hDLLDWrite = ::LoadLibraryEx(TEXT("DWRITE.DLL"), 0, 0x00000800 /*LOAD_LIBRARY_SEARCH_SYSTEM32*/);
129 if (hDLLDWrite) {
130 DWriteCFSig fnDWCF = (DWriteCFSig)::GetProcAddress(hDLLDWrite, "DWriteCreateFactory");
131 if (fnDWCF) {
132 fnDWCF(DWRITE_FACTORY_TYPE_SHARED,
133 __uuidof(IDWriteFactory),
134 reinterpret_cast<IUnknown**>(&pIDWriteFactory));
138 if (pIDWriteFactory) {
139 HRESULT hr = pIDWriteFactory->CreateRenderingParams(&defaultRenderingParams);
140 if (SUCCEEDED(hr)) {
141 unsigned int clearTypeContrast;
142 ::SystemParametersInfo(SPI_GETFONTSMOOTHINGCONTRAST, 0, &clearTypeContrast, 0);
144 FLOAT gamma;
145 if (clearTypeContrast >= 1000 && clearTypeContrast <= 2200)
146 gamma = static_cast<FLOAT>(clearTypeContrast) / 1000.0f;
147 else
148 gamma = defaultRenderingParams->GetGamma();
150 pIDWriteFactory->CreateCustomRenderingParams(gamma, defaultRenderingParams->GetEnhancedContrast(), defaultRenderingParams->GetClearTypeLevel(),
151 defaultRenderingParams->GetPixelGeometry(), defaultRenderingParams->GetRenderingMode(), &customClearTypeRenderingParams);
156 triedLoadingD2D = true;
157 return pIDWriteFactory && pD2DFactory;
159 #endif
161 struct FormatAndMetrics {
162 int technology;
163 HFONT hfont;
164 #if defined(USE_D2D)
165 IDWriteTextFormat *pTextFormat;
166 #endif
167 int extraFontFlag;
168 int characterSet;
169 FLOAT yAscent;
170 FLOAT yDescent;
171 FLOAT yInternalLeading;
172 FormatAndMetrics(HFONT hfont_, int extraFontFlag_, int characterSet_) :
173 technology(SCWIN_TECH_GDI), hfont(hfont_),
174 #if defined(USE_D2D)
175 pTextFormat(0),
176 #endif
177 extraFontFlag(extraFontFlag_), characterSet(characterSet_), yAscent(2), yDescent(1), yInternalLeading(0) {
179 #if defined(USE_D2D)
180 FormatAndMetrics(IDWriteTextFormat *pTextFormat_,
181 int extraFontFlag_,
182 int characterSet_,
183 FLOAT yAscent_,
184 FLOAT yDescent_,
185 FLOAT yInternalLeading_) :
186 technology(SCWIN_TECH_DIRECTWRITE),
187 hfont(0),
188 pTextFormat(pTextFormat_),
189 extraFontFlag(extraFontFlag_),
190 characterSet(characterSet_),
191 yAscent(yAscent_),
192 yDescent(yDescent_),
193 yInternalLeading(yInternalLeading_) {
195 #endif
196 ~FormatAndMetrics() {
197 if (hfont)
198 ::DeleteObject(hfont);
199 #if defined(USE_D2D)
200 if (pTextFormat)
201 pTextFormat->Release();
202 pTextFormat = 0;
203 #endif
204 extraFontFlag = 0;
205 characterSet = 0;
206 yAscent = 2;
207 yDescent = 1;
208 yInternalLeading = 0;
210 HFONT HFont();
213 HFONT FormatAndMetrics::HFont() {
214 LOGFONTW lf = {};
215 #if defined(USE_D2D)
216 if (technology == SCWIN_TECH_GDI) {
217 if (0 == ::GetObjectW(hfont, sizeof(lf), &lf)) {
218 return 0;
220 } else {
221 HRESULT hr = pTextFormat->GetFontFamilyName(lf.lfFaceName, LF_FACESIZE);
222 if (!SUCCEEDED(hr)) {
223 return 0;
225 lf.lfWeight = pTextFormat->GetFontWeight();
226 lf.lfItalic = pTextFormat->GetFontStyle() == DWRITE_FONT_STYLE_ITALIC;
227 lf.lfHeight = -static_cast<int>(pTextFormat->GetFontSize());
229 #else
230 if (0 == ::GetObjectW(hfont, sizeof(lf), &lf)) {
231 return 0;
233 #endif
234 return ::CreateFontIndirectW(&lf);
237 #ifndef CLEARTYPE_QUALITY
238 #define CLEARTYPE_QUALITY 5
239 #endif
241 static BYTE Win32MapFontQuality(int extraFontFlag) {
242 switch (extraFontFlag & SC_EFF_QUALITY_MASK) {
244 case SC_EFF_QUALITY_NON_ANTIALIASED:
245 return NONANTIALIASED_QUALITY;
247 case SC_EFF_QUALITY_ANTIALIASED:
248 return ANTIALIASED_QUALITY;
250 case SC_EFF_QUALITY_LCD_OPTIMIZED:
251 return CLEARTYPE_QUALITY;
253 default:
254 return SC_EFF_QUALITY_DEFAULT;
258 #if defined(USE_D2D)
259 static D2D1_TEXT_ANTIALIAS_MODE DWriteMapFontQuality(int extraFontFlag) {
260 switch (extraFontFlag & SC_EFF_QUALITY_MASK) {
262 case SC_EFF_QUALITY_NON_ANTIALIASED:
263 return D2D1_TEXT_ANTIALIAS_MODE_ALIASED;
265 case SC_EFF_QUALITY_ANTIALIASED:
266 return D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE;
268 case SC_EFF_QUALITY_LCD_OPTIMIZED:
269 return D2D1_TEXT_ANTIALIAS_MODE_CLEARTYPE;
271 default:
272 return D2D1_TEXT_ANTIALIAS_MODE_DEFAULT;
275 #endif
277 static void SetLogFont(LOGFONTA &lf, const char *faceName, int characterSet, float size, int weight, bool italic, int extraFontFlag) {
278 lf = LOGFONTA();
279 // The negative is to allow for leading
280 lf.lfHeight = -(abs(static_cast<int>(size + 0.5)));
281 lf.lfWeight = weight;
282 lf.lfItalic = static_cast<BYTE>(italic ? 1 : 0);
283 lf.lfCharSet = static_cast<BYTE>(characterSet);
284 lf.lfQuality = Win32MapFontQuality(extraFontFlag);
285 StringCopy(lf.lfFaceName, faceName);
289 * Create a hash from the parameters for a font to allow easy checking for identity.
290 * If one font is the same as another, its hash will be the same, but if the hash is the
291 * same then they may still be different.
293 static int HashFont(const FontParameters &fp) {
294 return
295 static_cast<int>(fp.size) ^
296 (fp.characterSet << 10) ^
297 ((fp.extraFontFlag & SC_EFF_QUALITY_MASK) << 9) ^
298 ((fp.weight/100) << 12) ^
299 (fp.italic ? 0x20000000 : 0) ^
300 (fp.technology << 15) ^
301 fp.faceName[0];
304 class FontCached : Font {
305 FontCached *next;
306 int usage;
307 float size;
308 LOGFONTA lf;
309 int technology;
310 int hash;
311 explicit FontCached(const FontParameters &fp);
312 ~FontCached() {}
313 bool SameAs(const FontParameters &fp);
314 virtual void Release();
316 static FontCached *first;
317 public:
318 static FontID FindOrCreate(const FontParameters &fp);
319 static void ReleaseId(FontID fid_);
322 FontCached *FontCached::first = 0;
324 FontCached::FontCached(const FontParameters &fp) :
325 next(0), usage(0), size(1.0), hash(0) {
326 SetLogFont(lf, fp.faceName, fp.characterSet, fp.size, fp.weight, fp.italic, fp.extraFontFlag);
327 technology = fp.technology;
328 hash = HashFont(fp);
329 fid = 0;
330 if (technology == SCWIN_TECH_GDI) {
331 HFONT hfont = ::CreateFontIndirectA(&lf);
332 fid = reinterpret_cast<void *>(new FormatAndMetrics(hfont, fp.extraFontFlag, fp.characterSet));
333 } else {
334 #if defined(USE_D2D)
335 IDWriteTextFormat *pTextFormat;
336 const int faceSize = 200;
337 WCHAR wszFace[faceSize];
338 UTF16FromUTF8(fp.faceName, static_cast<unsigned int>(strlen(fp.faceName))+1, wszFace, faceSize);
339 FLOAT fHeight = fp.size;
340 DWRITE_FONT_STYLE style = fp.italic ? DWRITE_FONT_STYLE_ITALIC : DWRITE_FONT_STYLE_NORMAL;
341 HRESULT hr = pIDWriteFactory->CreateTextFormat(wszFace, NULL,
342 static_cast<DWRITE_FONT_WEIGHT>(fp.weight),
343 style,
344 DWRITE_FONT_STRETCH_NORMAL, fHeight, L"en-us", &pTextFormat);
345 if (SUCCEEDED(hr)) {
346 pTextFormat->SetWordWrapping(DWRITE_WORD_WRAPPING_NO_WRAP);
348 const int maxLines = 2;
349 DWRITE_LINE_METRICS lineMetrics[maxLines];
350 UINT32 lineCount = 0;
351 FLOAT yAscent = 1.0f;
352 FLOAT yDescent = 1.0f;
353 FLOAT yInternalLeading = 0.0f;
354 IDWriteTextLayout *pTextLayout = 0;
355 hr = pIDWriteFactory->CreateTextLayout(L"X", 1, pTextFormat,
356 100.0f, 100.0f, &pTextLayout);
357 if (SUCCEEDED(hr)) {
358 hr = pTextLayout->GetLineMetrics(lineMetrics, maxLines, &lineCount);
359 if (SUCCEEDED(hr)) {
360 yAscent = lineMetrics[0].baseline;
361 yDescent = lineMetrics[0].height - lineMetrics[0].baseline;
363 FLOAT emHeight;
364 hr = pTextLayout->GetFontSize(0, &emHeight);
365 if (SUCCEEDED(hr)) {
366 yInternalLeading = lineMetrics[0].height - emHeight;
369 pTextLayout->Release();
370 pTextFormat->SetLineSpacing(DWRITE_LINE_SPACING_METHOD_UNIFORM, lineMetrics[0].height, lineMetrics[0].baseline);
372 fid = reinterpret_cast<void *>(new FormatAndMetrics(pTextFormat, fp.extraFontFlag, fp.characterSet, yAscent, yDescent, yInternalLeading));
374 #endif
376 usage = 1;
379 bool FontCached::SameAs(const FontParameters &fp) {
380 return
381 (size == fp.size) &&
382 (lf.lfWeight == fp.weight) &&
383 (lf.lfItalic == static_cast<BYTE>(fp.italic ? 1 : 0)) &&
384 (lf.lfCharSet == fp.characterSet) &&
385 (lf.lfQuality == Win32MapFontQuality(fp.extraFontFlag)) &&
386 (technology == fp.technology) &&
387 0 == strcmp(lf.lfFaceName,fp.faceName);
390 void FontCached::Release() {
391 delete reinterpret_cast<FormatAndMetrics *>(fid);
392 fid = 0;
395 FontID FontCached::FindOrCreate(const FontParameters &fp) {
396 FontID ret = 0;
397 ::EnterCriticalSection(&crPlatformLock);
398 int hashFind = HashFont(fp);
399 for (FontCached *cur=first; cur; cur=cur->next) {
400 if ((cur->hash == hashFind) &&
401 cur->SameAs(fp)) {
402 cur->usage++;
403 ret = cur->fid;
406 if (ret == 0) {
407 FontCached *fc = new FontCached(fp);
408 fc->next = first;
409 first = fc;
410 ret = fc->fid;
412 ::LeaveCriticalSection(&crPlatformLock);
413 return ret;
416 void FontCached::ReleaseId(FontID fid_) {
417 ::EnterCriticalSection(&crPlatformLock);
418 FontCached **pcur=&first;
419 for (FontCached *cur=first; cur; cur=cur->next) {
420 if (cur->fid == fid_) {
421 cur->usage--;
422 if (cur->usage == 0) {
423 *pcur = cur->next;
424 cur->Release();
425 cur->next = 0;
426 delete cur;
428 break;
430 pcur=&cur->next;
432 ::LeaveCriticalSection(&crPlatformLock);
435 Font::Font() {
436 fid = 0;
439 Font::~Font() {
442 #define FONTS_CACHED
444 void Font::Create(const FontParameters &fp) {
445 Release();
446 if (fp.faceName)
447 fid = FontCached::FindOrCreate(fp);
450 void Font::Release() {
451 if (fid)
452 FontCached::ReleaseId(fid);
453 fid = 0;
456 // Buffer to hold strings and string position arrays without always allocating on heap.
457 // May sometimes have string too long to allocate on stack. So use a fixed stack-allocated buffer
458 // when less than safe size otherwise allocate on heap and free automatically.
459 template<typename T, int lengthStandard>
460 class VarBuffer {
461 T bufferStandard[lengthStandard];
462 // Private so VarBuffer objects can not be copied
463 VarBuffer(const VarBuffer &);
464 VarBuffer &operator=(const VarBuffer &);
465 public:
466 T *buffer;
467 explicit VarBuffer(size_t length) : buffer(0) {
468 if (length > lengthStandard) {
469 buffer = new T[length];
470 } else {
471 buffer = bufferStandard;
474 ~VarBuffer() {
475 if (buffer != bufferStandard) {
476 delete []buffer;
477 buffer = 0;
482 const int stackBufferLength = 10000;
483 class TextWide : public VarBuffer<wchar_t, stackBufferLength> {
484 public:
485 int tlen;
486 TextWide(const char *s, int len, bool unicodeMode, int codePage=0) :
487 VarBuffer<wchar_t, stackBufferLength>(len) {
488 if (unicodeMode) {
489 tlen = UTF16FromUTF8(s, len, buffer, len);
490 } else {
491 // Support Asian string display in 9x English
492 tlen = ::MultiByteToWideChar(codePage, 0, s, len, buffer, len);
496 typedef VarBuffer<XYPOSITION, stackBufferLength> TextPositions;
498 class SurfaceGDI : public Surface {
499 bool unicodeMode;
500 HDC hdc;
501 bool hdcOwned;
502 HPEN pen;
503 HPEN penOld;
504 HBRUSH brush;
505 HBRUSH brushOld;
506 HFONT font;
507 HFONT fontOld;
508 HBITMAP bitmap;
509 HBITMAP bitmapOld;
510 int maxWidthMeasure;
511 int maxLenText;
513 int codePage;
514 // If 9x OS and current code page is same as ANSI code page.
515 bool win9xACPSame;
517 void BrushColor(ColourDesired back);
518 void SetFont(Font &font_);
520 // Private so SurfaceGDI objects can not be copied
521 SurfaceGDI(const SurfaceGDI &);
522 SurfaceGDI &operator=(const SurfaceGDI &);
523 public:
524 SurfaceGDI();
525 virtual ~SurfaceGDI();
527 void Init(WindowID wid);
528 void Init(SurfaceID sid, WindowID wid);
529 void InitPixMap(int width, int height, Surface *surface_, WindowID wid);
531 void Release();
532 bool Initialised();
533 void PenColour(ColourDesired fore);
534 int LogPixelsY();
535 int DeviceHeightFont(int points);
536 void MoveTo(int x_, int y_);
537 void LineTo(int x_, int y_);
538 void Polygon(Point *pts, int npts, ColourDesired fore, ColourDesired back);
539 void RectangleDraw(PRectangle rc, ColourDesired fore, ColourDesired back);
540 void FillRectangle(PRectangle rc, ColourDesired back);
541 void FillRectangle(PRectangle rc, Surface &surfacePattern);
542 void RoundedRectangle(PRectangle rc, ColourDesired fore, ColourDesired back);
543 void AlphaRectangle(PRectangle rc, int cornerSize, ColourDesired fill, int alphaFill,
544 ColourDesired outline, int alphaOutline, int flags);
545 void DrawRGBAImage(PRectangle rc, int width, int height, const unsigned char *pixelsImage);
546 void Ellipse(PRectangle rc, ColourDesired fore, ColourDesired back);
547 void Copy(PRectangle rc, Point from, Surface &surfaceSource);
549 void DrawTextCommon(PRectangle rc, Font &font_, XYPOSITION ybase, const char *s, int len, UINT fuOptions);
550 void DrawTextNoClip(PRectangle rc, Font &font_, XYPOSITION ybase, const char *s, int len, ColourDesired fore, ColourDesired back);
551 void DrawTextClipped(PRectangle rc, Font &font_, XYPOSITION ybase, const char *s, int len, ColourDesired fore, ColourDesired back);
552 void DrawTextTransparent(PRectangle rc, Font &font_, XYPOSITION ybase, const char *s, int len, ColourDesired fore);
553 void MeasureWidths(Font &font_, const char *s, int len, XYPOSITION *positions);
554 XYPOSITION WidthText(Font &font_, const char *s, int len);
555 XYPOSITION WidthChar(Font &font_, char ch);
556 XYPOSITION Ascent(Font &font_);
557 XYPOSITION Descent(Font &font_);
558 XYPOSITION InternalLeading(Font &font_);
559 XYPOSITION ExternalLeading(Font &font_);
560 XYPOSITION Height(Font &font_);
561 XYPOSITION AverageCharWidth(Font &font_);
563 void SetClip(PRectangle rc);
564 void FlushCachedState();
566 void SetUnicodeMode(bool unicodeMode_);
567 void SetDBCSMode(int codePage_);
570 SurfaceGDI::SurfaceGDI() :
571 unicodeMode(false),
572 hdc(0), hdcOwned(false),
573 pen(0), penOld(0),
574 brush(0), brushOld(0),
575 font(0), fontOld(0),
576 bitmap(0), bitmapOld(0) {
577 // Windows 9x has only a 16 bit coordinate system so break after 30000 pixels
578 maxWidthMeasure = IsNT() ? INT_MAX : 30000;
579 // There appears to be a 16 bit string length limit in GDI on NT and a limit of
580 // 8192 characters on Windows 95.
581 maxLenText = IsNT() ? 65535 : 8192;
583 codePage = 0;
584 win9xACPSame = false;
587 SurfaceGDI::~SurfaceGDI() {
588 Release();
591 void SurfaceGDI::Release() {
592 if (penOld) {
593 ::SelectObject(reinterpret_cast<HDC>(hdc), penOld);
594 ::DeleteObject(pen);
595 penOld = 0;
597 pen = 0;
598 if (brushOld) {
599 ::SelectObject(reinterpret_cast<HDC>(hdc), brushOld);
600 ::DeleteObject(brush);
601 brushOld = 0;
603 brush = 0;
604 if (fontOld) {
605 // Fonts are not deleted as they are owned by a Font object
606 ::SelectObject(reinterpret_cast<HDC>(hdc), fontOld);
607 fontOld = 0;
609 font = 0;
610 if (bitmapOld) {
611 ::SelectObject(reinterpret_cast<HDC>(hdc), bitmapOld);
612 ::DeleteObject(bitmap);
613 bitmapOld = 0;
615 bitmap = 0;
616 if (hdcOwned) {
617 ::DeleteDC(reinterpret_cast<HDC>(hdc));
618 hdc = 0;
619 hdcOwned = false;
623 bool SurfaceGDI::Initialised() {
624 return hdc != 0;
627 void SurfaceGDI::Init(WindowID) {
628 Release();
629 hdc = ::CreateCompatibleDC(NULL);
630 hdcOwned = true;
631 ::SetTextAlign(reinterpret_cast<HDC>(hdc), TA_BASELINE);
634 void SurfaceGDI::Init(SurfaceID sid, WindowID) {
635 Release();
636 hdc = reinterpret_cast<HDC>(sid);
637 ::SetTextAlign(reinterpret_cast<HDC>(hdc), TA_BASELINE);
640 void SurfaceGDI::InitPixMap(int width, int height, Surface *surface_, WindowID) {
641 Release();
642 hdc = ::CreateCompatibleDC(static_cast<SurfaceGDI *>(surface_)->hdc);
643 hdcOwned = true;
644 bitmap = ::CreateCompatibleBitmap(static_cast<SurfaceGDI *>(surface_)->hdc, width, height);
645 bitmapOld = static_cast<HBITMAP>(::SelectObject(hdc, bitmap));
646 ::SetTextAlign(reinterpret_cast<HDC>(hdc), TA_BASELINE);
649 void SurfaceGDI::PenColour(ColourDesired fore) {
650 if (pen) {
651 ::SelectObject(hdc, penOld);
652 ::DeleteObject(pen);
653 pen = 0;
654 penOld = 0;
656 pen = ::CreatePen(0,1,fore.AsLong());
657 penOld = static_cast<HPEN>(::SelectObject(reinterpret_cast<HDC>(hdc), pen));
660 void SurfaceGDI::BrushColor(ColourDesired back) {
661 if (brush) {
662 ::SelectObject(hdc, brushOld);
663 ::DeleteObject(brush);
664 brush = 0;
665 brushOld = 0;
667 // Only ever want pure, non-dithered brushes
668 ColourDesired colourNearest = ::GetNearestColor(hdc, back.AsLong());
669 brush = ::CreateSolidBrush(colourNearest.AsLong());
670 brushOld = static_cast<HBRUSH>(::SelectObject(hdc, brush));
673 void SurfaceGDI::SetFont(Font &font_) {
674 if (font_.GetID() != font) {
675 FormatAndMetrics *pfm = reinterpret_cast<FormatAndMetrics *>(font_.GetID());
676 PLATFORM_ASSERT(pfm->technology == SCWIN_TECH_GDI);
677 if (fontOld) {
678 ::SelectObject(hdc, pfm->hfont);
679 } else {
680 fontOld = static_cast<HFONT>(::SelectObject(hdc, pfm->hfont));
682 font = reinterpret_cast<HFONT>(pfm->hfont);
686 int SurfaceGDI::LogPixelsY() {
687 return ::GetDeviceCaps(hdc, LOGPIXELSY);
690 int SurfaceGDI::DeviceHeightFont(int points) {
691 return ::MulDiv(points, LogPixelsY(), 72);
694 void SurfaceGDI::MoveTo(int x_, int y_) {
695 ::MoveToEx(hdc, x_, y_, 0);
698 void SurfaceGDI::LineTo(int x_, int y_) {
699 ::LineTo(hdc, x_, y_);
702 void SurfaceGDI::Polygon(Point *pts, int npts, ColourDesired fore, ColourDesired back) {
703 PenColour(fore);
704 BrushColor(back);
705 std::vector<POINT> outline;
706 for (int i=0; i<npts; i++) {
707 POINT pt = {static_cast<LONG>(pts[i].x), static_cast<LONG>(pts[i].y)};
708 outline.push_back(pt);
710 ::Polygon(hdc, &outline[0], npts);
713 void SurfaceGDI::RectangleDraw(PRectangle rc, ColourDesired fore, ColourDesired back) {
714 PenColour(fore);
715 BrushColor(back);
716 const RECT rcw = RectFromPRectangle(rc);
717 ::Rectangle(hdc, rcw.left, rcw.top, rcw.right, rcw.bottom);
720 void SurfaceGDI::FillRectangle(PRectangle rc, ColourDesired back) {
721 // Using ExtTextOut rather than a FillRect ensures that no dithering occurs.
722 // There is no need to allocate a brush either.
723 RECT rcw = RectFromPRectangle(rc);
724 ::SetBkColor(hdc, back.AsLong());
725 ::ExtTextOut(hdc, rcw.left, rcw.top, ETO_OPAQUE, &rcw, TEXT(""), 0, NULL);
728 void SurfaceGDI::FillRectangle(PRectangle rc, Surface &surfacePattern) {
729 HBRUSH br;
730 if (static_cast<SurfaceGDI &>(surfacePattern).bitmap)
731 br = ::CreatePatternBrush(static_cast<SurfaceGDI &>(surfacePattern).bitmap);
732 else // Something is wrong so display in red
733 br = ::CreateSolidBrush(RGB(0xff, 0, 0));
734 RECT rcw = RectFromPRectangle(rc);
735 ::FillRect(hdc, &rcw, br);
736 ::DeleteObject(br);
739 void SurfaceGDI::RoundedRectangle(PRectangle rc, ColourDesired fore, ColourDesired back) {
740 PenColour(fore);
741 BrushColor(back);
742 const RECT rcw = RectFromPRectangle(rc);
743 ::RoundRect(hdc,
744 rcw.left + 1, rcw.top,
745 rcw.right - 1, rcw.bottom,
746 8, 8);
749 // Plot a point into a DWORD buffer symetrically to all 4 qudrants
750 static void AllFour(DWORD *pixels, int width, int height, int x, int y, DWORD val) {
751 pixels[y*width+x] = val;
752 pixels[y*width+width-1-x] = val;
753 pixels[(height-1-y)*width+x] = val;
754 pixels[(height-1-y)*width+width-1-x] = val;
757 #ifndef AC_SRC_OVER
758 #define AC_SRC_OVER 0x00
759 #endif
760 #ifndef AC_SRC_ALPHA
761 #define AC_SRC_ALPHA 0x01
762 #endif
764 static DWORD dwordFromBGRA(byte b, byte g, byte r, byte a) {
765 union {
766 byte pixVal[4];
767 DWORD val;
768 } converter;
769 converter.pixVal[0] = b;
770 converter.pixVal[1] = g;
771 converter.pixVal[2] = r;
772 converter.pixVal[3] = a;
773 return converter.val;
776 void SurfaceGDI::AlphaRectangle(PRectangle rc, int cornerSize, ColourDesired fill, int alphaFill,
777 ColourDesired outline, int alphaOutline, int /* flags*/ ) {
778 const RECT rcw = RectFromPRectangle(rc);
779 if (AlphaBlendFn && rc.Width() > 0) {
780 HDC hMemDC = ::CreateCompatibleDC(reinterpret_cast<HDC>(hdc));
781 int width = static_cast<int>(rc.Width());
782 int height = static_cast<int>(rc.Height());
783 // Ensure not distorted too much by corners when small
784 cornerSize = Platform::Minimum(cornerSize, (Platform::Minimum(width, height) / 2) - 2);
785 BITMAPINFO bpih = {{sizeof(BITMAPINFOHEADER), width, height, 1, 32, BI_RGB, 0, 0, 0, 0, 0}};
786 void *image = 0;
787 HBITMAP hbmMem = CreateDIBSection(reinterpret_cast<HDC>(hMemDC), &bpih,
788 DIB_RGB_COLORS, &image, NULL, 0);
790 if (hbmMem) {
791 HBITMAP hbmOld = SelectBitmap(hMemDC, hbmMem);
793 DWORD valEmpty = dwordFromBGRA(0,0,0,0);
794 DWORD valFill = dwordFromBGRA(
795 static_cast<byte>(GetBValue(fill.AsLong()) * alphaFill / 255),
796 static_cast<byte>(GetGValue(fill.AsLong()) * alphaFill / 255),
797 static_cast<byte>(GetRValue(fill.AsLong()) * alphaFill / 255),
798 static_cast<byte>(alphaFill));
799 DWORD valOutline = dwordFromBGRA(
800 static_cast<byte>(GetBValue(outline.AsLong()) * alphaOutline / 255),
801 static_cast<byte>(GetGValue(outline.AsLong()) * alphaOutline / 255),
802 static_cast<byte>(GetRValue(outline.AsLong()) * alphaOutline / 255),
803 static_cast<byte>(alphaOutline));
804 DWORD *pixels = reinterpret_cast<DWORD *>(image);
805 for (int y=0; y<height; y++) {
806 for (int x=0; x<width; x++) {
807 if ((x==0) || (x==width-1) || (y == 0) || (y == height-1)) {
808 pixels[y*width+x] = valOutline;
809 } else {
810 pixels[y*width+x] = valFill;
814 for (int c=0; c<cornerSize; c++) {
815 for (int x=0; x<c+1; x++) {
816 AllFour(pixels, width, height, x, c-x, valEmpty);
819 for (int x=1; x<cornerSize; x++) {
820 AllFour(pixels, width, height, x, cornerSize-x, valOutline);
823 BLENDFUNCTION merge = { AC_SRC_OVER, 0, 255, AC_SRC_ALPHA };
825 AlphaBlendFn(reinterpret_cast<HDC>(hdc), rcw.left, rcw.top, width, height, hMemDC, 0, 0, width, height, merge);
827 SelectBitmap(hMemDC, hbmOld);
828 ::DeleteObject(hbmMem);
830 ::DeleteDC(hMemDC);
831 } else {
832 BrushColor(outline);
833 FrameRect(hdc, &rcw, brush);
837 void SurfaceGDI::DrawRGBAImage(PRectangle rc, int width, int height, const unsigned char *pixelsImage) {
838 if (AlphaBlendFn && rc.Width() > 0) {
839 HDC hMemDC = ::CreateCompatibleDC(reinterpret_cast<HDC>(hdc));
840 if (rc.Width() > width)
841 rc.left += static_cast<int>((rc.Width() - width) / 2);
842 rc.right = rc.left + width;
843 if (rc.Height() > height)
844 rc.top += static_cast<int>((rc.Height() - height) / 2);
845 rc.bottom = rc.top + height;
847 BITMAPINFO bpih = {{sizeof(BITMAPINFOHEADER), width, height, 1, 32, BI_RGB, 0, 0, 0, 0, 0}};
848 unsigned char *image = 0;
849 HBITMAP hbmMem = CreateDIBSection(reinterpret_cast<HDC>(hMemDC), &bpih,
850 DIB_RGB_COLORS, reinterpret_cast<void **>(&image), NULL, 0);
851 if (hbmMem) {
852 HBITMAP hbmOld = SelectBitmap(hMemDC, hbmMem);
854 for (int y=height-1; y>=0; y--) {
855 for (int x=0; x<width; x++) {
856 unsigned char *pixel = image + (y*width+x) * 4;
857 unsigned char alpha = pixelsImage[3];
858 // Input is RGBA, output is BGRA with premultiplied alpha
859 pixel[2] = static_cast<unsigned char>((*pixelsImage++) * alpha / 255);
860 pixel[1] = static_cast<unsigned char>((*pixelsImage++) * alpha / 255);
861 pixel[0] = static_cast<unsigned char>((*pixelsImage++) * alpha / 255);
862 pixel[3] = static_cast<unsigned char>(*pixelsImage++);
866 BLENDFUNCTION merge = { AC_SRC_OVER, 0, 255, AC_SRC_ALPHA };
868 AlphaBlendFn(reinterpret_cast<HDC>(hdc), static_cast<int>(rc.left), static_cast<int>(rc.top),
869 static_cast<int>(rc.Width()), static_cast<int>(rc.Height()), hMemDC, 0, 0, width, height, merge);
871 SelectBitmap(hMemDC, hbmOld);
872 ::DeleteObject(hbmMem);
874 ::DeleteDC(hMemDC);
879 void SurfaceGDI::Ellipse(PRectangle rc, ColourDesired fore, ColourDesired back) {
880 PenColour(fore);
881 BrushColor(back);
882 const RECT rcw = RectFromPRectangle(rc);
883 ::Ellipse(hdc, rcw.left, rcw.top, rcw.right, rcw.bottom);
886 void SurfaceGDI::Copy(PRectangle rc, Point from, Surface &surfaceSource) {
887 ::BitBlt(hdc,
888 static_cast<int>(rc.left), static_cast<int>(rc.top),
889 static_cast<int>(rc.Width()), static_cast<int>(rc.Height()),
890 static_cast<SurfaceGDI &>(surfaceSource).hdc,
891 static_cast<int>(from.x), static_cast<int>(from.y), SRCCOPY);
894 typedef VarBuffer<int, stackBufferLength> TextPositionsI;
896 void SurfaceGDI::DrawTextCommon(PRectangle rc, Font &font_, XYPOSITION ybase, const char *s, int len, UINT fuOptions) {
897 SetFont(font_);
898 RECT rcw = RectFromPRectangle(rc);
899 SIZE sz={0,0};
900 int pos = 0;
901 int x = static_cast<int>(rc.left);
902 const int yBaseInt = static_cast<int>(ybase);
904 // Text drawing may fail if the text is too big.
905 // If it does fail, slice up into segments and draw each segment.
906 const int maxSegmentLength = 0x200;
908 if ((!unicodeMode) && (IsNT() || (codePage==0) || win9xACPSame)) {
909 // Use ANSI calls
910 int lenDraw = Platform::Minimum(len, maxLenText);
911 if (!::ExtTextOutA(hdc, x, yBaseInt, fuOptions, &rcw, s, lenDraw, NULL)) {
912 while (lenDraw > pos) {
913 int seglen = Platform::Minimum(maxSegmentLength, lenDraw - pos);
914 if (!::ExtTextOutA(hdc, x, yBaseInt, fuOptions, &rcw, s + pos, seglen, NULL)) {
915 PLATFORM_ASSERT(false);
916 return;
918 ::GetTextExtentPoint32A(hdc, s+pos, seglen, &sz);
919 x += sz.cx;
920 pos += seglen;
923 } else {
924 // Use Unicode calls
925 const TextWide tbuf(s, len, unicodeMode, codePage);
926 if (!::ExtTextOutW(hdc, x, yBaseInt, fuOptions, &rcw, tbuf.buffer, tbuf.tlen, NULL)) {
927 while (tbuf.tlen > pos) {
928 int seglen = Platform::Minimum(maxSegmentLength, tbuf.tlen - pos);
929 if (!::ExtTextOutW(hdc, x, yBaseInt, fuOptions, &rcw, tbuf.buffer + pos, seglen, NULL)) {
930 PLATFORM_ASSERT(false);
931 return;
933 ::GetTextExtentPoint32W(hdc, tbuf.buffer+pos, seglen, &sz);
934 x += sz.cx;
935 pos += seglen;
941 void SurfaceGDI::DrawTextNoClip(PRectangle rc, Font &font_, XYPOSITION ybase, const char *s, int len,
942 ColourDesired fore, ColourDesired back) {
943 ::SetTextColor(hdc, fore.AsLong());
944 ::SetBkColor(hdc, back.AsLong());
945 DrawTextCommon(rc, font_, ybase, s, len, ETO_OPAQUE);
948 void SurfaceGDI::DrawTextClipped(PRectangle rc, Font &font_, XYPOSITION ybase, const char *s, int len,
949 ColourDesired fore, ColourDesired back) {
950 ::SetTextColor(hdc, fore.AsLong());
951 ::SetBkColor(hdc, back.AsLong());
952 DrawTextCommon(rc, font_, ybase, s, len, ETO_OPAQUE | ETO_CLIPPED);
955 void SurfaceGDI::DrawTextTransparent(PRectangle rc, Font &font_, XYPOSITION ybase, const char *s, int len,
956 ColourDesired fore) {
957 // Avoid drawing spaces in transparent mode
958 for (int i=0; i<len; i++) {
959 if (s[i] != ' ') {
960 ::SetTextColor(hdc, fore.AsLong());
961 ::SetBkMode(hdc, TRANSPARENT);
962 DrawTextCommon(rc, font_, ybase, s, len, 0);
963 ::SetBkMode(hdc, OPAQUE);
964 return;
969 XYPOSITION SurfaceGDI::WidthText(Font &font_, const char *s, int len) {
970 SetFont(font_);
971 SIZE sz={0,0};
972 if ((!unicodeMode) && (IsNT() || (codePage==0) || win9xACPSame)) {
973 ::GetTextExtentPoint32A(hdc, s, Platform::Minimum(len, maxLenText), &sz);
974 } else {
975 const TextWide tbuf(s, len, unicodeMode, codePage);
976 ::GetTextExtentPoint32W(hdc, tbuf.buffer, tbuf.tlen, &sz);
978 return static_cast<XYPOSITION>(sz.cx);
981 void SurfaceGDI::MeasureWidths(Font &font_, const char *s, int len, XYPOSITION *positions) {
982 SetFont(font_);
983 SIZE sz={0,0};
984 int fit = 0;
985 if (unicodeMode) {
986 const TextWide tbuf(s, len, unicodeMode, codePage);
987 TextPositionsI poses(tbuf.tlen);
988 fit = tbuf.tlen;
989 if (!::GetTextExtentExPointW(hdc, tbuf.buffer, tbuf.tlen, maxWidthMeasure, &fit, poses.buffer, &sz)) {
990 // Likely to have failed because on Windows 9x where function not available
991 // So measure the character widths by measuring each initial substring
992 // Turns a linear operation into a qudratic but seems fast enough on test files
993 for (int widthSS=0; widthSS < tbuf.tlen; widthSS++) {
994 ::GetTextExtentPoint32W(hdc, tbuf.buffer, widthSS+1, &sz);
995 poses.buffer[widthSS] = sz.cx;
998 // Map the widths given for UTF-16 characters back onto the UTF-8 input string
999 int ui=0;
1000 const unsigned char *us = reinterpret_cast<const unsigned char *>(s);
1001 int i=0;
1002 while (ui<fit) {
1003 unsigned char uch = us[i];
1004 unsigned int lenChar = 1;
1005 if (uch >= (0x80 + 0x40 + 0x20 + 0x10)) {
1006 lenChar = 4;
1007 ui++;
1008 } else if (uch >= (0x80 + 0x40 + 0x20)) {
1009 lenChar = 3;
1010 } else if (uch >= (0x80)) {
1011 lenChar = 2;
1013 for (unsigned int bytePos=0; (bytePos<lenChar) && (i<len); bytePos++) {
1014 positions[i++] = static_cast<XYPOSITION>(poses.buffer[ui]);
1016 ui++;
1018 XYPOSITION lastPos = 0.0f;
1019 if (i > 0)
1020 lastPos = positions[i-1];
1021 while (i<len) {
1022 positions[i++] = lastPos;
1024 } else if (IsNT() || (codePage==0) || win9xACPSame) {
1025 // Zero positions to avoid random behaviour on failure.
1026 std::fill(positions, positions + len, 0.0f);
1027 // len may be larger than platform supports so loop over segments small enough for platform
1028 int startOffset = 0;
1029 while (len > 0) {
1030 int lenBlock = Platform::Minimum(len, maxLenText);
1031 TextPositionsI poses(len);
1032 if (!::GetTextExtentExPointA(hdc, s, lenBlock, maxWidthMeasure, &fit, poses.buffer, &sz)) {
1033 // Eeek - a NULL DC or other foolishness could cause this.
1034 return;
1035 } else if (fit < lenBlock) {
1036 // For some reason, such as an incomplete DBCS character
1037 // Not all the positions are filled in so make them equal to end.
1038 if (fit == 0)
1039 poses.buffer[fit++] = 0;
1040 for (int i = fit; i<lenBlock; i++)
1041 poses.buffer[i] = poses.buffer[fit-1];
1043 for (int i=0; i<lenBlock; i++)
1044 positions[i] = static_cast<XYPOSITION>(poses.buffer[i] + startOffset);
1045 startOffset = poses.buffer[lenBlock-1];
1046 len -= lenBlock;
1047 positions += lenBlock;
1048 s += lenBlock;
1050 } else {
1051 // Support Asian string display in 9x English
1052 const TextWide tbuf(s, len, unicodeMode, codePage);
1053 TextPositionsI poses(tbuf.tlen);
1054 for (int widthSS=0; widthSS<tbuf.tlen; widthSS++) {
1055 ::GetTextExtentPoint32W(hdc, tbuf.buffer, widthSS+1, &sz);
1056 poses.buffer[widthSS] = sz.cx;
1059 int ui = 0;
1060 for (int i=0; i<len;) {
1061 if (Platform::IsDBCSLeadByte(codePage, s[i])) {
1062 positions[i] = static_cast<XYPOSITION>(poses.buffer[ui]);
1063 positions[i + 1] = static_cast<XYPOSITION>(poses.buffer[ui]);
1064 i += 2;
1065 } else {
1066 positions[i] = static_cast<XYPOSITION>(poses.buffer[ui]);
1067 i++;
1070 ui++;
1075 XYPOSITION SurfaceGDI::WidthChar(Font &font_, char ch) {
1076 SetFont(font_);
1077 SIZE sz;
1078 ::GetTextExtentPoint32A(hdc, &ch, 1, &sz);
1079 return static_cast<XYPOSITION>(sz.cx);
1082 XYPOSITION SurfaceGDI::Ascent(Font &font_) {
1083 SetFont(font_);
1084 TEXTMETRIC tm;
1085 ::GetTextMetrics(hdc, &tm);
1086 return static_cast<XYPOSITION>(tm.tmAscent);
1089 XYPOSITION SurfaceGDI::Descent(Font &font_) {
1090 SetFont(font_);
1091 TEXTMETRIC tm;
1092 ::GetTextMetrics(hdc, &tm);
1093 return static_cast<XYPOSITION>(tm.tmDescent);
1096 XYPOSITION SurfaceGDI::InternalLeading(Font &font_) {
1097 SetFont(font_);
1098 TEXTMETRIC tm;
1099 ::GetTextMetrics(hdc, &tm);
1100 return static_cast<XYPOSITION>(tm.tmInternalLeading);
1103 XYPOSITION SurfaceGDI::ExternalLeading(Font &font_) {
1104 SetFont(font_);
1105 TEXTMETRIC tm;
1106 ::GetTextMetrics(hdc, &tm);
1107 return static_cast<XYPOSITION>(tm.tmExternalLeading);
1110 XYPOSITION SurfaceGDI::Height(Font &font_) {
1111 SetFont(font_);
1112 TEXTMETRIC tm;
1113 ::GetTextMetrics(hdc, &tm);
1114 return static_cast<XYPOSITION>(tm.tmHeight);
1117 XYPOSITION SurfaceGDI::AverageCharWidth(Font &font_) {
1118 SetFont(font_);
1119 TEXTMETRIC tm;
1120 ::GetTextMetrics(hdc, &tm);
1121 return static_cast<XYPOSITION>(tm.tmAveCharWidth);
1124 void SurfaceGDI::SetClip(PRectangle rc) {
1125 ::IntersectClipRect(hdc, static_cast<int>(rc.left), static_cast<int>(rc.top),
1126 static_cast<int>(rc.right), static_cast<int>(rc.bottom));
1129 void SurfaceGDI::FlushCachedState() {
1130 pen = 0;
1131 brush = 0;
1132 font = 0;
1135 void SurfaceGDI::SetUnicodeMode(bool unicodeMode_) {
1136 unicodeMode=unicodeMode_;
1139 void SurfaceGDI::SetDBCSMode(int codePage_) {
1140 // No action on window as automatically handled by system.
1141 codePage = codePage_;
1142 win9xACPSame = !IsNT() && ((unsigned int)codePage == ::GetACP());
1145 #if defined(USE_D2D)
1147 class SurfaceD2D : public Surface {
1148 bool unicodeMode;
1149 int x, y;
1151 int codePage;
1152 int codePageText;
1154 ID2D1RenderTarget *pRenderTarget;
1155 bool ownRenderTarget;
1156 int clipsActive;
1158 IDWriteTextFormat *pTextFormat;
1159 FLOAT yAscent;
1160 FLOAT yDescent;
1161 FLOAT yInternalLeading;
1163 ID2D1SolidColorBrush *pBrush;
1165 int logPixelsY;
1166 float dpiScaleX;
1167 float dpiScaleY;
1169 void SetFont(Font &font_);
1171 // Private so SurfaceD2D objects can not be copied
1172 SurfaceD2D(const SurfaceD2D &);
1173 SurfaceD2D &operator=(const SurfaceD2D &);
1174 public:
1175 SurfaceD2D();
1176 virtual ~SurfaceD2D();
1178 void SetScale();
1179 void Init(WindowID wid);
1180 void Init(SurfaceID sid, WindowID wid);
1181 void InitPixMap(int width, int height, Surface *surface_, WindowID wid);
1183 void Release();
1184 bool Initialised();
1186 HRESULT FlushDrawing();
1188 void PenColour(ColourDesired fore);
1189 void D2DPenColour(ColourDesired fore, int alpha=255);
1190 int LogPixelsY();
1191 int DeviceHeightFont(int points);
1192 void MoveTo(int x_, int y_);
1193 void LineTo(int x_, int y_);
1194 void Polygon(Point *pts, int npts, ColourDesired fore, ColourDesired back);
1195 void RectangleDraw(PRectangle rc, ColourDesired fore, ColourDesired back);
1196 void FillRectangle(PRectangle rc, ColourDesired back);
1197 void FillRectangle(PRectangle rc, Surface &surfacePattern);
1198 void RoundedRectangle(PRectangle rc, ColourDesired fore, ColourDesired back);
1199 void AlphaRectangle(PRectangle rc, int cornerSize, ColourDesired fill, int alphaFill,
1200 ColourDesired outline, int alphaOutline, int flags);
1201 void DrawRGBAImage(PRectangle rc, int width, int height, const unsigned char *pixelsImage);
1202 void Ellipse(PRectangle rc, ColourDesired fore, ColourDesired back);
1203 void Copy(PRectangle rc, Point from, Surface &surfaceSource);
1205 void DrawTextCommon(PRectangle rc, Font &font_, XYPOSITION ybase, const char *s, int len, UINT fuOptions);
1206 void DrawTextNoClip(PRectangle rc, Font &font_, XYPOSITION ybase, const char *s, int len, ColourDesired fore, ColourDesired back);
1207 void DrawTextClipped(PRectangle rc, Font &font_, XYPOSITION ybase, const char *s, int len, ColourDesired fore, ColourDesired back);
1208 void DrawTextTransparent(PRectangle rc, Font &font_, XYPOSITION ybase, const char *s, int len, ColourDesired fore);
1209 void MeasureWidths(Font &font_, const char *s, int len, XYPOSITION *positions);
1210 XYPOSITION WidthText(Font &font_, const char *s, int len);
1211 XYPOSITION WidthChar(Font &font_, char ch);
1212 XYPOSITION Ascent(Font &font_);
1213 XYPOSITION Descent(Font &font_);
1214 XYPOSITION InternalLeading(Font &font_);
1215 XYPOSITION ExternalLeading(Font &font_);
1216 XYPOSITION Height(Font &font_);
1217 XYPOSITION AverageCharWidth(Font &font_);
1219 void SetClip(PRectangle rc);
1220 void FlushCachedState();
1222 void SetUnicodeMode(bool unicodeMode_);
1223 void SetDBCSMode(int codePage_);
1226 SurfaceD2D::SurfaceD2D() :
1227 unicodeMode(false),
1228 x(0), y(0) {
1230 codePage = 0;
1231 codePageText = 0;
1233 pRenderTarget = NULL;
1234 ownRenderTarget = false;
1235 clipsActive = 0;
1237 // From selected font
1238 pTextFormat = NULL;
1239 yAscent = 2;
1240 yDescent = 1;
1241 yInternalLeading = 0;
1243 pBrush = NULL;
1245 logPixelsY = 72;
1246 dpiScaleX = 1.0;
1247 dpiScaleY = 1.0;
1250 SurfaceD2D::~SurfaceD2D() {
1251 Release();
1254 void SurfaceD2D::Release() {
1255 if (pBrush) {
1256 pBrush->Release();
1257 pBrush = 0;
1259 if (pRenderTarget) {
1260 while (clipsActive) {
1261 pRenderTarget->PopAxisAlignedClip();
1262 clipsActive--;
1264 if (ownRenderTarget) {
1265 pRenderTarget->Release();
1267 pRenderTarget = 0;
1271 void SurfaceD2D::SetScale() {
1272 HDC hdcMeasure = ::CreateCompatibleDC(NULL);
1273 logPixelsY = ::GetDeviceCaps(hdcMeasure, LOGPIXELSY);
1274 dpiScaleX = ::GetDeviceCaps(hdcMeasure, LOGPIXELSX) / 96.0f;
1275 dpiScaleY = logPixelsY / 96.0f;
1276 ::DeleteDC(hdcMeasure);
1279 bool SurfaceD2D::Initialised() {
1280 return pRenderTarget != 0;
1283 HRESULT SurfaceD2D::FlushDrawing() {
1284 return pRenderTarget->Flush();
1287 void SurfaceD2D::Init(WindowID /* wid */) {
1288 Release();
1289 SetScale();
1292 void SurfaceD2D::Init(SurfaceID sid, WindowID) {
1293 Release();
1294 SetScale();
1295 pRenderTarget = reinterpret_cast<ID2D1RenderTarget *>(sid);
1298 void SurfaceD2D::InitPixMap(int width, int height, Surface *surface_, WindowID) {
1299 Release();
1300 SetScale();
1301 SurfaceD2D *psurfOther = static_cast<SurfaceD2D *>(surface_);
1302 ID2D1BitmapRenderTarget *pCompatibleRenderTarget = NULL;
1303 D2D1_SIZE_F desiredSize = D2D1::SizeF(static_cast<float>(width), static_cast<float>(height));
1304 D2D1_PIXEL_FORMAT desiredFormat;
1305 #ifdef __MINGW32__
1306 desiredFormat.format = DXGI_FORMAT_UNKNOWN;
1307 #else
1308 desiredFormat = psurfOther->pRenderTarget->GetPixelFormat();
1309 #endif
1310 desiredFormat.alphaMode = D2D1_ALPHA_MODE_IGNORE;
1311 HRESULT hr = psurfOther->pRenderTarget->CreateCompatibleRenderTarget(
1312 &desiredSize, NULL, &desiredFormat, D2D1_COMPATIBLE_RENDER_TARGET_OPTIONS_NONE, &pCompatibleRenderTarget);
1313 if (SUCCEEDED(hr)) {
1314 pRenderTarget = pCompatibleRenderTarget;
1315 pRenderTarget->BeginDraw();
1316 ownRenderTarget = true;
1320 void SurfaceD2D::PenColour(ColourDesired fore) {
1321 D2DPenColour(fore);
1324 void SurfaceD2D::D2DPenColour(ColourDesired fore, int alpha) {
1325 if (pRenderTarget) {
1326 D2D_COLOR_F col;
1327 col.r = (fore.AsLong() & 0xff) / 255.0f;
1328 col.g = ((fore.AsLong() & 0xff00) >> 8) / 255.0f;
1329 col.b = (fore.AsLong() >> 16) / 255.0f;
1330 col.a = alpha / 255.0f;
1331 if (pBrush) {
1332 pBrush->SetColor(col);
1333 } else {
1334 HRESULT hr = pRenderTarget->CreateSolidColorBrush(col, &pBrush);
1335 if (!SUCCEEDED(hr) && pBrush) {
1336 pBrush->Release();
1337 pBrush = 0;
1343 void SurfaceD2D::SetFont(Font &font_) {
1344 FormatAndMetrics *pfm = reinterpret_cast<FormatAndMetrics *>(font_.GetID());
1345 PLATFORM_ASSERT(pfm->technology == SCWIN_TECH_DIRECTWRITE);
1346 pTextFormat = pfm->pTextFormat;
1347 yAscent = pfm->yAscent;
1348 yDescent = pfm->yDescent;
1349 yInternalLeading = pfm->yInternalLeading;
1350 codePageText = codePage;
1351 if (pfm->characterSet) {
1352 codePageText = CodePageFromCharSet(pfm->characterSet, codePage);
1354 if (pRenderTarget) {
1355 D2D1_TEXT_ANTIALIAS_MODE aaMode;
1356 aaMode = DWriteMapFontQuality(pfm->extraFontFlag);
1358 if (aaMode == D2D1_TEXT_ANTIALIAS_MODE_CLEARTYPE && customClearTypeRenderingParams)
1359 pRenderTarget->SetTextRenderingParams(customClearTypeRenderingParams);
1360 else if (defaultRenderingParams)
1361 pRenderTarget->SetTextRenderingParams(defaultRenderingParams);
1363 pRenderTarget->SetTextAntialiasMode(aaMode);
1367 int SurfaceD2D::LogPixelsY() {
1368 return logPixelsY;
1371 int SurfaceD2D::DeviceHeightFont(int points) {
1372 return ::MulDiv(points, LogPixelsY(), 72);
1375 void SurfaceD2D::MoveTo(int x_, int y_) {
1376 x = x_;
1377 y = y_;
1380 static int Delta(int difference) {
1381 if (difference < 0)
1382 return -1;
1383 else if (difference > 0)
1384 return 1;
1385 else
1386 return 0;
1389 static float RoundFloat(float f) {
1390 return float(int(f+0.5f));
1393 void SurfaceD2D::LineTo(int x_, int y_) {
1394 if (pRenderTarget) {
1395 int xDiff = x_ - x;
1396 int xDelta = Delta(xDiff);
1397 int yDiff = y_ - y;
1398 int yDelta = Delta(yDiff);
1399 if ((xDiff == 0) || (yDiff == 0)) {
1400 // Horizontal or vertical lines can be more precisely drawn as a filled rectangle
1401 int xEnd = x_ - xDelta;
1402 int left = Platform::Minimum(x, xEnd);
1403 int width = abs(x - xEnd) + 1;
1404 int yEnd = y_ - yDelta;
1405 int top = Platform::Minimum(y, yEnd);
1406 int height = abs(y - yEnd) + 1;
1407 D2D1_RECT_F rectangle1 = D2D1::RectF(static_cast<float>(left), static_cast<float>(top),
1408 static_cast<float>(left+width), static_cast<float>(top+height));
1409 pRenderTarget->FillRectangle(&rectangle1, pBrush);
1410 } else if ((abs(xDiff) == abs(yDiff))) {
1411 // 45 degree slope
1412 pRenderTarget->DrawLine(D2D1::Point2F(x + 0.5f, y + 0.5f),
1413 D2D1::Point2F(x_ + 0.5f - xDelta, y_ + 0.5f - yDelta), pBrush);
1414 } else {
1415 // Line has a different slope so difficult to avoid last pixel
1416 pRenderTarget->DrawLine(D2D1::Point2F(x + 0.5f, y + 0.5f),
1417 D2D1::Point2F(x_ + 0.5f, y_ + 0.5f), pBrush);
1419 x = x_;
1420 y = y_;
1424 void SurfaceD2D::Polygon(Point *pts, int npts, ColourDesired fore, ColourDesired back) {
1425 if (pRenderTarget) {
1426 ID2D1Factory *pFactory = 0;
1427 pRenderTarget->GetFactory(&pFactory);
1428 ID2D1PathGeometry *geometry=0;
1429 HRESULT hr = pFactory->CreatePathGeometry(&geometry);
1430 if (SUCCEEDED(hr)) {
1431 ID2D1GeometrySink *sink = 0;
1432 hr = geometry->Open(&sink);
1433 if (SUCCEEDED(hr)) {
1434 sink->BeginFigure(D2D1::Point2F(pts[0].x + 0.5f, pts[0].y + 0.5f), D2D1_FIGURE_BEGIN_FILLED);
1435 for (size_t i=1; i<static_cast<size_t>(npts); i++) {
1436 sink->AddLine(D2D1::Point2F(pts[i].x + 0.5f, pts[i].y + 0.5f));
1438 sink->EndFigure(D2D1_FIGURE_END_CLOSED);
1439 sink->Close();
1440 sink->Release();
1442 D2DPenColour(back);
1443 pRenderTarget->FillGeometry(geometry,pBrush);
1444 D2DPenColour(fore);
1445 pRenderTarget->DrawGeometry(geometry,pBrush);
1448 geometry->Release();
1453 void SurfaceD2D::RectangleDraw(PRectangle rc, ColourDesired fore, ColourDesired back) {
1454 if (pRenderTarget) {
1455 D2D1_RECT_F rectangle1 = D2D1::RectF(RoundFloat(rc.left) + 0.5f, rc.top+0.5f, RoundFloat(rc.right) - 0.5f, rc.bottom-0.5f);
1456 D2DPenColour(back);
1457 pRenderTarget->FillRectangle(&rectangle1, pBrush);
1458 D2DPenColour(fore);
1459 pRenderTarget->DrawRectangle(&rectangle1, pBrush);
1463 void SurfaceD2D::FillRectangle(PRectangle rc, ColourDesired back) {
1464 if (pRenderTarget) {
1465 D2DPenColour(back);
1466 D2D1_RECT_F rectangle1 = D2D1::RectF(RoundFloat(rc.left), rc.top, RoundFloat(rc.right), rc.bottom);
1467 pRenderTarget->FillRectangle(&rectangle1, pBrush);
1471 void SurfaceD2D::FillRectangle(PRectangle rc, Surface &surfacePattern) {
1472 SurfaceD2D &surfOther = static_cast<SurfaceD2D &>(surfacePattern);
1473 surfOther.FlushDrawing();
1474 ID2D1Bitmap *pBitmap = NULL;
1475 ID2D1BitmapRenderTarget *pCompatibleRenderTarget = reinterpret_cast<ID2D1BitmapRenderTarget *>(
1476 surfOther.pRenderTarget);
1477 HRESULT hr = pCompatibleRenderTarget->GetBitmap(&pBitmap);
1478 if (SUCCEEDED(hr)) {
1479 ID2D1BitmapBrush *pBitmapBrush = NULL;
1480 D2D1_BITMAP_BRUSH_PROPERTIES brushProperties =
1481 D2D1::BitmapBrushProperties(D2D1_EXTEND_MODE_WRAP, D2D1_EXTEND_MODE_WRAP,
1482 D2D1_BITMAP_INTERPOLATION_MODE_NEAREST_NEIGHBOR);
1483 // Create the bitmap brush.
1484 hr = pRenderTarget->CreateBitmapBrush(pBitmap, brushProperties, &pBitmapBrush);
1485 pBitmap->Release();
1486 if (SUCCEEDED(hr)) {
1487 pRenderTarget->FillRectangle(
1488 D2D1::RectF(rc.left, rc.top, rc.right, rc.bottom),
1489 pBitmapBrush);
1490 pBitmapBrush->Release();
1495 void SurfaceD2D::RoundedRectangle(PRectangle rc, ColourDesired fore, ColourDesired back) {
1496 if (pRenderTarget) {
1497 D2D1_ROUNDED_RECT roundedRectFill = {
1498 D2D1::RectF(rc.left+1.0f, rc.top+1.0f, rc.right-1.0f, rc.bottom-1.0f),
1499 4, 4};
1500 D2DPenColour(back);
1501 pRenderTarget->FillRoundedRectangle(roundedRectFill, pBrush);
1503 D2D1_ROUNDED_RECT roundedRect = {
1504 D2D1::RectF(rc.left + 0.5f, rc.top+0.5f, rc.right - 0.5f, rc.bottom-0.5f),
1505 4, 4};
1506 D2DPenColour(fore);
1507 pRenderTarget->DrawRoundedRectangle(roundedRect, pBrush);
1511 void SurfaceD2D::AlphaRectangle(PRectangle rc, int cornerSize, ColourDesired fill, int alphaFill,
1512 ColourDesired outline, int alphaOutline, int /* flags*/ ) {
1513 if (pRenderTarget) {
1514 if (cornerSize == 0) {
1515 // When corner size is zero, draw square rectangle to prevent blurry pixels at corners
1516 D2D1_RECT_F rectFill = D2D1::RectF(RoundFloat(rc.left) + 1.0f, rc.top + 1.0f, RoundFloat(rc.right) - 1.0f, rc.bottom - 1.0f);
1517 D2DPenColour(fill, alphaFill);
1518 pRenderTarget->FillRectangle(rectFill, pBrush);
1520 D2D1_RECT_F rectOutline = D2D1::RectF(RoundFloat(rc.left) + 0.5f, rc.top + 0.5f, RoundFloat(rc.right) - 0.5f, rc.bottom - 0.5f);
1521 D2DPenColour(outline, alphaOutline);
1522 pRenderTarget->DrawRectangle(rectOutline, pBrush);
1523 } else {
1524 const float cornerSizeF = static_cast<float>(cornerSize);
1525 D2D1_ROUNDED_RECT roundedRectFill = {
1526 D2D1::RectF(RoundFloat(rc.left) + 1.0f, rc.top + 1.0f, RoundFloat(rc.right) - 1.0f, rc.bottom - 1.0f),
1527 cornerSizeF, cornerSizeF};
1528 D2DPenColour(fill, alphaFill);
1529 pRenderTarget->FillRoundedRectangle(roundedRectFill, pBrush);
1531 D2D1_ROUNDED_RECT roundedRect = {
1532 D2D1::RectF(RoundFloat(rc.left) + 0.5f, rc.top + 0.5f, RoundFloat(rc.right) - 0.5f, rc.bottom - 0.5f),
1533 cornerSizeF, cornerSizeF};
1534 D2DPenColour(outline, alphaOutline);
1535 pRenderTarget->DrawRoundedRectangle(roundedRect, pBrush);
1540 void SurfaceD2D::DrawRGBAImage(PRectangle rc, int width, int height, const unsigned char *pixelsImage) {
1541 if (pRenderTarget) {
1542 if (rc.Width() > width)
1543 rc.left += static_cast<int>((rc.Width() - width) / 2);
1544 rc.right = rc.left + width;
1545 if (rc.Height() > height)
1546 rc.top += static_cast<int>((rc.Height() - height) / 2);
1547 rc.bottom = rc.top + height;
1549 std::vector<unsigned char> image(height * width * 4);
1550 for (int yPixel=0; yPixel<height; yPixel++) {
1551 for (int xPixel = 0; xPixel<width; xPixel++) {
1552 unsigned char *pixel = &image[0] + (yPixel*width + xPixel) * 4;
1553 unsigned char alpha = pixelsImage[3];
1554 // Input is RGBA, output is BGRA with premultiplied alpha
1555 pixel[2] = (*pixelsImage++) * alpha / 255;
1556 pixel[1] = (*pixelsImage++) * alpha / 255;
1557 pixel[0] = (*pixelsImage++) * alpha / 255;
1558 pixel[3] = *pixelsImage++;
1562 ID2D1Bitmap *bitmap = 0;
1563 D2D1_SIZE_U size = D2D1::SizeU(width, height);
1564 D2D1_BITMAP_PROPERTIES props = {{DXGI_FORMAT_B8G8R8A8_UNORM,
1565 D2D1_ALPHA_MODE_PREMULTIPLIED}, 72.0, 72.0};
1566 HRESULT hr = pRenderTarget->CreateBitmap(size, &image[0],
1567 width * 4, &props, &bitmap);
1568 if (SUCCEEDED(hr)) {
1569 D2D1_RECT_F rcDestination = {rc.left, rc.top, rc.right, rc.bottom};
1570 pRenderTarget->DrawBitmap(bitmap, rcDestination);
1571 bitmap->Release();
1576 void SurfaceD2D::Ellipse(PRectangle rc, ColourDesired fore, ColourDesired back) {
1577 if (pRenderTarget) {
1578 FLOAT radius = rc.Width() / 2.0f;
1579 D2D1_ELLIPSE ellipse = {
1580 D2D1::Point2F((rc.left + rc.right) / 2.0f, (rc.top + rc.bottom) / 2.0f),
1581 radius,radius};
1583 PenColour(back);
1584 pRenderTarget->FillEllipse(ellipse, pBrush);
1585 PenColour(fore);
1586 pRenderTarget->DrawEllipse(ellipse, pBrush);
1590 void SurfaceD2D::Copy(PRectangle rc, Point from, Surface &surfaceSource) {
1591 SurfaceD2D &surfOther = static_cast<SurfaceD2D &>(surfaceSource);
1592 surfOther.FlushDrawing();
1593 ID2D1BitmapRenderTarget *pCompatibleRenderTarget = reinterpret_cast<ID2D1BitmapRenderTarget *>(
1594 surfOther.pRenderTarget);
1595 ID2D1Bitmap *pBitmap = NULL;
1596 HRESULT hr = pCompatibleRenderTarget->GetBitmap(&pBitmap);
1597 if (SUCCEEDED(hr)) {
1598 D2D1_RECT_F rcDestination = {rc.left, rc.top, rc.right, rc.bottom};
1599 D2D1_RECT_F rcSource = {from.x, from.y, from.x + rc.Width(), from.y + rc.Height()};
1600 pRenderTarget->DrawBitmap(pBitmap, rcDestination, 1.0f,
1601 D2D1_BITMAP_INTERPOLATION_MODE_NEAREST_NEIGHBOR, rcSource);
1602 hr = pRenderTarget->Flush();
1603 if (FAILED(hr)) {
1604 Platform::DebugPrintf("Failed Flush 0x%x\n", hr);
1606 pBitmap->Release();
1610 void SurfaceD2D::DrawTextCommon(PRectangle rc, Font &font_, XYPOSITION ybase, const char *s, int len, UINT fuOptions) {
1611 SetFont(font_);
1613 // Use Unicode calls
1614 const TextWide tbuf(s, len, unicodeMode, codePageText);
1615 if (pRenderTarget && pTextFormat && pBrush) {
1616 if (fuOptions & ETO_CLIPPED) {
1617 D2D1_RECT_F rcClip = {rc.left, rc.top, rc.right, rc.bottom};
1618 pRenderTarget->PushAxisAlignedClip(rcClip, D2D1_ANTIALIAS_MODE_ALIASED);
1621 // Explicitly creating a text layout appears a little faster
1622 IDWriteTextLayout *pTextLayout;
1623 HRESULT hr = pIDWriteFactory->CreateTextLayout(tbuf.buffer, tbuf.tlen, pTextFormat,
1624 rc.Width(), rc.Height(), &pTextLayout);
1625 if (SUCCEEDED(hr)) {
1626 D2D1_POINT_2F origin = {rc.left, ybase-yAscent};
1627 pRenderTarget->DrawTextLayout(origin, pTextLayout, pBrush, D2D1_DRAW_TEXT_OPTIONS_NONE);
1628 pTextLayout->Release();
1631 if (fuOptions & ETO_CLIPPED) {
1632 pRenderTarget->PopAxisAlignedClip();
1637 void SurfaceD2D::DrawTextNoClip(PRectangle rc, Font &font_, XYPOSITION ybase, const char *s, int len,
1638 ColourDesired fore, ColourDesired back) {
1639 if (pRenderTarget) {
1640 FillRectangle(rc, back);
1641 D2DPenColour(fore);
1642 DrawTextCommon(rc, font_, ybase, s, len, ETO_OPAQUE);
1646 void SurfaceD2D::DrawTextClipped(PRectangle rc, Font &font_, XYPOSITION ybase, const char *s, int len,
1647 ColourDesired fore, ColourDesired back) {
1648 if (pRenderTarget) {
1649 FillRectangle(rc, back);
1650 D2DPenColour(fore);
1651 DrawTextCommon(rc, font_, ybase, s, len, ETO_OPAQUE | ETO_CLIPPED);
1655 void SurfaceD2D::DrawTextTransparent(PRectangle rc, Font &font_, XYPOSITION ybase, const char *s, int len,
1656 ColourDesired fore) {
1657 // Avoid drawing spaces in transparent mode
1658 for (int i=0; i<len; i++) {
1659 if (s[i] != ' ') {
1660 if (pRenderTarget) {
1661 D2DPenColour(fore);
1662 DrawTextCommon(rc, font_, ybase, s, len, 0);
1664 return;
1669 XYPOSITION SurfaceD2D::WidthText(Font &font_, const char *s, int len) {
1670 FLOAT width = 1.0;
1671 SetFont(font_);
1672 const TextWide tbuf(s, len, unicodeMode, codePageText);
1673 if (pIDWriteFactory && pTextFormat) {
1674 // Create a layout
1675 IDWriteTextLayout *pTextLayout = 0;
1676 HRESULT hr = pIDWriteFactory->CreateTextLayout(tbuf.buffer, tbuf.tlen, pTextFormat, 1000.0, 1000.0, &pTextLayout);
1677 if (SUCCEEDED(hr)) {
1678 DWRITE_TEXT_METRICS textMetrics;
1679 if (SUCCEEDED(pTextLayout->GetMetrics(&textMetrics)))
1680 width = textMetrics.widthIncludingTrailingWhitespace;
1681 pTextLayout->Release();
1684 return width;
1687 void SurfaceD2D::MeasureWidths(Font &font_, const char *s, int len, XYPOSITION *positions) {
1688 SetFont(font_);
1689 int fit = 0;
1690 const TextWide tbuf(s, len, unicodeMode, codePageText);
1691 TextPositions poses(tbuf.tlen);
1692 fit = tbuf.tlen;
1693 const int clusters = 1000;
1694 DWRITE_CLUSTER_METRICS clusterMetrics[clusters];
1695 UINT32 count = 0;
1696 if (pIDWriteFactory && pTextFormat) {
1697 SetFont(font_);
1698 // Create a layout
1699 IDWriteTextLayout *pTextLayout = 0;
1700 HRESULT hr = pIDWriteFactory->CreateTextLayout(tbuf.buffer, tbuf.tlen, pTextFormat, 10000.0, 1000.0, &pTextLayout);
1701 if (!SUCCEEDED(hr))
1702 return;
1703 // For now, assuming WCHAR == cluster
1704 if (!SUCCEEDED(pTextLayout->GetClusterMetrics(clusterMetrics, clusters, &count)))
1705 return;
1706 FLOAT position = 0.0f;
1707 size_t ti=0;
1708 for (size_t ci=0; ci<count; ci++) {
1709 position += clusterMetrics[ci].width;
1710 for (size_t inCluster=0; inCluster<clusterMetrics[ci].length; inCluster++) {
1711 //poses.buffer[ti++] = int(position + 0.5);
1712 poses.buffer[ti++] = position;
1715 PLATFORM_ASSERT(ti == static_cast<size_t>(tbuf.tlen));
1716 pTextLayout->Release();
1718 if (unicodeMode) {
1719 // Map the widths given for UTF-16 characters back onto the UTF-8 input string
1720 int ui=0;
1721 const unsigned char *us = reinterpret_cast<const unsigned char *>(s);
1722 int i=0;
1723 while (ui<fit) {
1724 unsigned char uch = us[i];
1725 unsigned int lenChar = 1;
1726 if (uch >= (0x80 + 0x40 + 0x20 + 0x10)) {
1727 lenChar = 4;
1728 ui++;
1729 } else if (uch >= (0x80 + 0x40 + 0x20)) {
1730 lenChar = 3;
1731 } else if (uch >= (0x80)) {
1732 lenChar = 2;
1734 for (unsigned int bytePos=0; (bytePos<lenChar) && (i<len); bytePos++) {
1735 positions[i++] = poses.buffer[ui];
1737 ui++;
1739 XYPOSITION lastPos = 0.0f;
1740 if (i > 0)
1741 lastPos = positions[i-1];
1742 while (i<len) {
1743 positions[i++] = lastPos;
1745 } else if (codePageText == 0) {
1747 // One character per position
1748 PLATFORM_ASSERT(len == tbuf.tlen);
1749 for (size_t kk=0; kk<static_cast<size_t>(len); kk++) {
1750 positions[kk] = poses.buffer[kk];
1753 } else {
1755 // May be more than one byte per position
1756 unsigned int ui = 0;
1757 FLOAT position = 0.0f;
1758 for (int i=0; i<len;) {
1759 if (ui < count)
1760 position = poses.buffer[ui];
1761 if (Platform::IsDBCSLeadByte(codePageText, s[i])) {
1762 positions[i] = position;
1763 positions[i+1] = position;
1764 i += 2;
1765 } else {
1766 positions[i] = position;
1767 i++;
1770 ui++;
1775 XYPOSITION SurfaceD2D::WidthChar(Font &font_, char ch) {
1776 FLOAT width = 1.0;
1777 SetFont(font_);
1778 if (pIDWriteFactory && pTextFormat) {
1779 // Create a layout
1780 IDWriteTextLayout *pTextLayout = 0;
1781 const WCHAR wch = ch;
1782 HRESULT hr = pIDWriteFactory->CreateTextLayout(&wch, 1, pTextFormat, 1000.0, 1000.0, &pTextLayout);
1783 if (SUCCEEDED(hr)) {
1784 DWRITE_TEXT_METRICS textMetrics;
1785 if (SUCCEEDED(pTextLayout->GetMetrics(&textMetrics)))
1786 width = textMetrics.widthIncludingTrailingWhitespace;
1787 pTextLayout->Release();
1790 return width;
1793 XYPOSITION SurfaceD2D::Ascent(Font &font_) {
1794 SetFont(font_);
1795 return ceil(yAscent);
1798 XYPOSITION SurfaceD2D::Descent(Font &font_) {
1799 SetFont(font_);
1800 return ceil(yDescent);
1803 XYPOSITION SurfaceD2D::InternalLeading(Font &font_) {
1804 SetFont(font_);
1805 return floor(yInternalLeading);
1808 XYPOSITION SurfaceD2D::ExternalLeading(Font &) {
1809 // Not implemented, always return one
1810 return 1;
1813 XYPOSITION SurfaceD2D::Height(Font &font_) {
1814 return Ascent(font_) + Descent(font_);
1817 XYPOSITION SurfaceD2D::AverageCharWidth(Font &font_) {
1818 FLOAT width = 1.0;
1819 SetFont(font_);
1820 if (pIDWriteFactory && pTextFormat) {
1821 // Create a layout
1822 IDWriteTextLayout *pTextLayout = 0;
1823 const WCHAR wszAllAlpha[] = L"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
1824 HRESULT hr = pIDWriteFactory->CreateTextLayout(wszAllAlpha, static_cast<UINT32>(wcslen(wszAllAlpha)),
1825 pTextFormat, 1000.0, 1000.0, &pTextLayout);
1826 if (SUCCEEDED(hr)) {
1827 DWRITE_TEXT_METRICS textMetrics;
1828 if (SUCCEEDED(pTextLayout->GetMetrics(&textMetrics)))
1829 width = textMetrics.width / wcslen(wszAllAlpha);
1830 pTextLayout->Release();
1833 return width;
1836 void SurfaceD2D::SetClip(PRectangle rc) {
1837 if (pRenderTarget) {
1838 D2D1_RECT_F rcClip = {rc.left, rc.top, rc.right, rc.bottom};
1839 pRenderTarget->PushAxisAlignedClip(rcClip, D2D1_ANTIALIAS_MODE_ALIASED);
1840 clipsActive++;
1844 void SurfaceD2D::FlushCachedState() {
1847 void SurfaceD2D::SetUnicodeMode(bool unicodeMode_) {
1848 unicodeMode=unicodeMode_;
1851 void SurfaceD2D::SetDBCSMode(int codePage_) {
1852 // No action on window as automatically handled by system.
1853 codePage = codePage_;
1855 #endif
1857 Surface *Surface::Allocate(int technology) {
1858 #if defined(USE_D2D)
1859 if (technology == SCWIN_TECH_GDI)
1860 return new SurfaceGDI;
1861 else
1862 return new SurfaceD2D;
1863 #else
1864 return new SurfaceGDI;
1865 #endif
1868 Window::~Window() {
1871 void Window::Destroy() {
1872 if (wid)
1873 ::DestroyWindow(reinterpret_cast<HWND>(wid));
1874 wid = 0;
1877 bool Window::HasFocus() {
1878 return ::GetFocus() == wid;
1881 PRectangle Window::GetPosition() {
1882 RECT rc;
1883 ::GetWindowRect(reinterpret_cast<HWND>(wid), &rc);
1884 return PRectangle::FromInts(rc.left, rc.top, rc.right, rc.bottom);
1887 void Window::SetPosition(PRectangle rc) {
1888 ::SetWindowPos(reinterpret_cast<HWND>(wid),
1889 0, static_cast<int>(rc.left), static_cast<int>(rc.top),
1890 static_cast<int>(rc.Width()), static_cast<int>(rc.Height()), SWP_NOZORDER | SWP_NOACTIVATE);
1893 static RECT RectFromMonitor(HMONITOR hMonitor) {
1894 if (GetMonitorInfoFn) {
1895 MONITORINFO mi = {0};
1896 mi.cbSize = sizeof(mi);
1897 if (GetMonitorInfoFn(hMonitor, &mi)) {
1898 return mi.rcWork;
1901 RECT rc = {0, 0, 0, 0};
1902 if (::SystemParametersInfoA(SPI_GETWORKAREA, 0, &rc, 0) == 0) {
1903 rc.left = 0;
1904 rc.top = 0;
1905 rc.right = 0;
1906 rc.bottom = 0;
1908 return rc;
1911 void Window::SetPositionRelative(PRectangle rc, Window w) {
1912 LONG style = ::GetWindowLong(reinterpret_cast<HWND>(wid), GWL_STYLE);
1913 if (style & WS_POPUP) {
1914 POINT ptOther = {0, 0};
1915 ::ClientToScreen(reinterpret_cast<HWND>(w.GetID()), &ptOther);
1916 rc.Move(static_cast<XYPOSITION>(ptOther.x), static_cast<XYPOSITION>(ptOther.y));
1918 RECT rcMonitor = RectFromPRectangle(rc);
1920 HMONITOR hMonitor = NULL;
1921 if (MonitorFromRectFn)
1922 hMonitor = MonitorFromRectFn(&rcMonitor, MONITOR_DEFAULTTONEAREST);
1923 // If hMonitor is NULL, that's just the main screen anyways.
1924 //::GetMonitorInfo(hMonitor, &mi);
1925 RECT rcWork = RectFromMonitor(hMonitor);
1927 if (rcWork.left < rcWork.right) {
1928 // Now clamp our desired rectangle to fit inside the work area
1929 // This way, the menu will fit wholly on one screen. An improvement even
1930 // if you don't have a second monitor on the left... Menu's appears half on
1931 // one screen and half on the other are just U.G.L.Y.!
1932 if (rc.right > rcWork.right)
1933 rc.Move(rcWork.right - rc.right, 0);
1934 if (rc.bottom > rcWork.bottom)
1935 rc.Move(0, rcWork.bottom - rc.bottom);
1936 if (rc.left < rcWork.left)
1937 rc.Move(rcWork.left - rc.left, 0);
1938 if (rc.top < rcWork.top)
1939 rc.Move(0, rcWork.top - rc.top);
1942 SetPosition(rc);
1945 PRectangle Window::GetClientPosition() {
1946 RECT rc={0,0,0,0};
1947 if (wid)
1948 ::GetClientRect(reinterpret_cast<HWND>(wid), &rc);
1949 return PRectangle::FromInts(rc.left, rc.top, rc.right, rc.bottom);
1952 void Window::Show(bool show) {
1953 if (show)
1954 ::ShowWindow(reinterpret_cast<HWND>(wid), SW_SHOWNOACTIVATE);
1955 else
1956 ::ShowWindow(reinterpret_cast<HWND>(wid), SW_HIDE);
1959 void Window::InvalidateAll() {
1960 ::InvalidateRect(reinterpret_cast<HWND>(wid), NULL, FALSE);
1963 void Window::InvalidateRectangle(PRectangle rc) {
1964 RECT rcw = RectFromPRectangle(rc);
1965 ::InvalidateRect(reinterpret_cast<HWND>(wid), &rcw, FALSE);
1968 static LRESULT Window_SendMessage(Window *w, UINT msg, WPARAM wParam=0, LPARAM lParam=0) {
1969 return ::SendMessage(reinterpret_cast<HWND>(w->GetID()), msg, wParam, lParam);
1972 void Window::SetFont(Font &font) {
1973 Window_SendMessage(this, WM_SETFONT,
1974 reinterpret_cast<WPARAM>(font.GetID()), 0);
1977 static void FlipBitmap(HBITMAP bitmap, int width, int height) {
1978 HDC hdc = ::CreateCompatibleDC(NULL);
1979 if (hdc != NULL) {
1980 HGDIOBJ prevBmp = ::SelectObject(hdc, bitmap);
1981 ::StretchBlt(hdc, width - 1, 0, -width, height, hdc, 0, 0, width, height, SRCCOPY);
1982 ::SelectObject(hdc, prevBmp);
1983 ::DeleteDC(hdc);
1987 static HCURSOR GetReverseArrowCursor() {
1988 if (reverseArrowCursor != NULL)
1989 return reverseArrowCursor;
1991 ::EnterCriticalSection(&crPlatformLock);
1992 HCURSOR cursor = reverseArrowCursor;
1993 if (cursor == NULL) {
1994 cursor = ::LoadCursor(NULL, IDC_ARROW);
1995 ICONINFO info;
1996 if (::GetIconInfo(cursor, &info)) {
1997 BITMAP bmp;
1998 if (::GetObject(info.hbmMask, sizeof(bmp), &bmp)) {
1999 FlipBitmap(info.hbmMask, bmp.bmWidth, bmp.bmHeight);
2000 if (info.hbmColor != NULL)
2001 FlipBitmap(info.hbmColor, bmp.bmWidth, bmp.bmHeight);
2002 info.xHotspot = (DWORD)bmp.bmWidth - 1 - info.xHotspot;
2004 reverseArrowCursor = ::CreateIconIndirect(&info);
2005 if (reverseArrowCursor != NULL)
2006 cursor = reverseArrowCursor;
2009 ::DeleteObject(info.hbmMask);
2010 if (info.hbmColor != NULL)
2011 ::DeleteObject(info.hbmColor);
2014 ::LeaveCriticalSection(&crPlatformLock);
2015 return cursor;
2018 void Window::SetCursor(Cursor curs) {
2019 switch (curs) {
2020 case cursorText:
2021 ::SetCursor(::LoadCursor(NULL,IDC_IBEAM));
2022 break;
2023 case cursorUp:
2024 ::SetCursor(::LoadCursor(NULL,IDC_UPARROW));
2025 break;
2026 case cursorWait:
2027 ::SetCursor(::LoadCursor(NULL,IDC_WAIT));
2028 break;
2029 case cursorHoriz:
2030 ::SetCursor(::LoadCursor(NULL,IDC_SIZEWE));
2031 break;
2032 case cursorVert:
2033 ::SetCursor(::LoadCursor(NULL,IDC_SIZENS));
2034 break;
2035 case cursorHand:
2036 ::SetCursor(::LoadCursor(NULL,IDC_HAND));
2037 break;
2038 case cursorReverseArrow:
2039 ::SetCursor(GetReverseArrowCursor());
2040 break;
2041 case cursorArrow:
2042 case cursorInvalid: // Should not occur, but just in case.
2043 ::SetCursor(::LoadCursor(NULL,IDC_ARROW));
2044 break;
2048 void Window::SetTitle(const char *s) {
2049 ::SetWindowTextA(reinterpret_cast<HWND>(wid), s);
2052 /* Returns rectangle of monitor pt is on, both rect and pt are in Window's
2053 coordinates */
2054 PRectangle Window::GetMonitorRect(Point pt) {
2055 // MonitorFromPoint and GetMonitorInfo are not available on Windows 95 and NT 4.
2056 PRectangle rcPosition = GetPosition();
2057 POINT ptDesktop = {static_cast<LONG>(pt.x + rcPosition.left),
2058 static_cast<LONG>(pt.y + rcPosition.top)};
2059 HMONITOR hMonitor = NULL;
2060 if (MonitorFromPointFn)
2061 hMonitor = MonitorFromPointFn(ptDesktop, MONITOR_DEFAULTTONEAREST);
2063 RECT rcWork = RectFromMonitor(hMonitor);
2064 if (rcWork.left < rcWork.right) {
2065 PRectangle rcMonitor(
2066 rcWork.left - rcPosition.left,
2067 rcWork.top - rcPosition.top,
2068 rcWork.right - rcPosition.left,
2069 rcWork.bottom - rcPosition.top);
2070 return rcMonitor;
2071 } else {
2072 return PRectangle();
2076 struct ListItemData {
2077 const char *text;
2078 int pixId;
2081 class LineToItem {
2082 std::vector<char> words;
2084 std::vector<ListItemData> data;
2086 public:
2087 LineToItem() {
2089 ~LineToItem() {
2090 Clear();
2092 void Clear() {
2093 words.clear();
2094 data.clear();
2097 ListItemData Get(int index) const {
2098 if (index >= 0 && index < static_cast<int>(data.size())) {
2099 return data[index];
2100 } else {
2101 ListItemData missing = {"", -1};
2102 return missing;
2105 int Count() const {
2106 return static_cast<int>(data.size());
2109 void AllocItem(const char *text, int pixId) {
2110 ListItemData lid = { text, pixId };
2111 data.push_back(lid);
2114 char *SetWords(const char *s) {
2115 words = std::vector<char>(s, s+strlen(s)+1);
2116 return &words[0];
2120 const TCHAR ListBoxX_ClassName[] = TEXT("ListBoxX");
2122 ListBox::ListBox() {
2125 ListBox::~ListBox() {
2128 class ListBoxX : public ListBox {
2129 int lineHeight;
2130 FontID fontCopy;
2131 int technology;
2132 RGBAImageSet images;
2133 LineToItem lti;
2134 HWND lb;
2135 bool unicodeMode;
2136 int desiredVisibleRows;
2137 unsigned int maxItemCharacters;
2138 unsigned int aveCharWidth;
2139 Window *parent;
2140 int ctrlID;
2141 CallBackAction doubleClickAction;
2142 void *doubleClickActionData;
2143 const char *widestItem;
2144 unsigned int maxCharWidth;
2145 int resizeHit;
2146 PRectangle rcPreSize;
2147 Point dragOffset;
2148 Point location; // Caret location at which the list is opened
2149 int wheelDelta; // mouse wheel residue
2151 HWND GetHWND() const;
2152 void AppendListItem(const char *text, const char *numword);
2153 static void AdjustWindowRect(PRectangle *rc);
2154 int ItemHeight() const;
2155 int MinClientWidth() const;
2156 int TextOffset() const;
2157 POINT GetClientExtent() const;
2158 POINT MinTrackSize() const;
2159 POINT MaxTrackSize() const;
2160 void SetRedraw(bool on);
2161 void OnDoubleClick();
2162 void ResizeToCursor();
2163 void StartResize(WPARAM);
2164 LRESULT NcHitTest(WPARAM, LPARAM) const;
2165 void CentreItem(int n);
2166 void Paint(HDC);
2167 static LRESULT PASCAL ControlWndProc(HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam);
2169 static const Point ItemInset; // Padding around whole item
2170 static const Point TextInset; // Padding around text
2171 static const Point ImageInset; // Padding around image
2173 public:
2174 ListBoxX() : lineHeight(10), fontCopy(0), technology(0), lb(0), unicodeMode(false),
2175 desiredVisibleRows(5), maxItemCharacters(0), aveCharWidth(8),
2176 parent(NULL), ctrlID(0), doubleClickAction(NULL), doubleClickActionData(NULL),
2177 widestItem(NULL), maxCharWidth(1), resizeHit(0), wheelDelta(0) {
2179 virtual ~ListBoxX() {
2180 if (fontCopy) {
2181 ::DeleteObject(fontCopy);
2182 fontCopy = 0;
2185 virtual void SetFont(Font &font);
2186 virtual void Create(Window &parent_, int ctrlID_, Point location_, int lineHeight_, bool unicodeMode_, int technology_);
2187 virtual void SetAverageCharWidth(int width);
2188 virtual void SetVisibleRows(int rows);
2189 virtual int GetVisibleRows() const;
2190 virtual PRectangle GetDesiredRect();
2191 virtual int CaretFromEdge();
2192 virtual void Clear();
2193 virtual void Append(char *s, int type = -1);
2194 virtual int Length();
2195 virtual void Select(int n);
2196 virtual int GetSelection();
2197 virtual int Find(const char *prefix);
2198 virtual void GetValue(int n, char *value, int len);
2199 virtual void RegisterImage(int type, const char *xpm_data);
2200 virtual void RegisterRGBAImage(int type, int width, int height, const unsigned char *pixelsImage);
2201 virtual void ClearRegisteredImages();
2202 virtual void SetDoubleClickAction(CallBackAction action, void *data) {
2203 doubleClickAction = action;
2204 doubleClickActionData = data;
2206 virtual void SetList(const char *list, char separator, char typesep);
2207 void Draw(DRAWITEMSTRUCT *pDrawItem);
2208 LRESULT WndProc(HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam);
2209 static LRESULT PASCAL StaticWndProc(HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam);
2212 const Point ListBoxX::ItemInset(0, 0);
2213 const Point ListBoxX::TextInset(2, 0);
2214 const Point ListBoxX::ImageInset(1, 0);
2216 ListBox *ListBox::Allocate() {
2217 ListBoxX *lb = new ListBoxX();
2218 return lb;
2221 void ListBoxX::Create(Window &parent_, int ctrlID_, Point location_, int lineHeight_, bool unicodeMode_, int technology_) {
2222 parent = &parent_;
2223 ctrlID = ctrlID_;
2224 location = location_;
2225 lineHeight = lineHeight_;
2226 unicodeMode = unicodeMode_;
2227 technology = technology_;
2228 HWND hwndParent = reinterpret_cast<HWND>(parent->GetID());
2229 HINSTANCE hinstanceParent = GetWindowInstance(hwndParent);
2230 // Window created as popup so not clipped within parent client area
2231 wid = ::CreateWindowEx(
2232 WS_EX_WINDOWEDGE, ListBoxX_ClassName, TEXT(""),
2233 WS_POPUP | WS_THICKFRAME,
2234 100,100, 150,80, hwndParent,
2235 NULL,
2236 hinstanceParent,
2237 this);
2239 POINT locationw = {static_cast<LONG>(location.x), static_cast<LONG>(location.y)};
2240 ::MapWindowPoints(hwndParent, NULL, &locationw, 1);
2241 location = Point::FromInts(locationw.x, locationw.y);
2244 void ListBoxX::SetFont(Font &font) {
2245 if (font.GetID()) {
2246 if (fontCopy) {
2247 ::DeleteObject(fontCopy);
2248 fontCopy = 0;
2250 FormatAndMetrics *pfm = reinterpret_cast<FormatAndMetrics *>(font.GetID());
2251 fontCopy = pfm->HFont();
2252 ::SendMessage(lb, WM_SETFONT, reinterpret_cast<WPARAM>(fontCopy), 0);
2256 void ListBoxX::SetAverageCharWidth(int width) {
2257 aveCharWidth = width;
2260 void ListBoxX::SetVisibleRows(int rows) {
2261 desiredVisibleRows = rows;
2264 int ListBoxX::GetVisibleRows() const {
2265 return desiredVisibleRows;
2268 HWND ListBoxX::GetHWND() const {
2269 return reinterpret_cast<HWND>(GetID());
2272 PRectangle ListBoxX::GetDesiredRect() {
2273 PRectangle rcDesired = GetPosition();
2275 int rows = Length();
2276 if ((rows == 0) || (rows > desiredVisibleRows))
2277 rows = desiredVisibleRows;
2278 rcDesired.bottom = rcDesired.top + ItemHeight() * rows;
2280 int width = MinClientWidth();
2281 HDC hdc = ::GetDC(lb);
2282 HFONT oldFont = SelectFont(hdc, fontCopy);
2283 SIZE textSize = {0, 0};
2284 int len = 0;
2285 if (widestItem) {
2286 len = static_cast<int>(strlen(widestItem));
2287 if (unicodeMode) {
2288 const TextWide tbuf(widestItem, len, unicodeMode);
2289 ::GetTextExtentPoint32W(hdc, tbuf.buffer, tbuf.tlen, &textSize);
2290 } else {
2291 ::GetTextExtentPoint32A(hdc, widestItem, len, &textSize);
2294 TEXTMETRIC tm;
2295 ::GetTextMetrics(hdc, &tm);
2296 maxCharWidth = tm.tmMaxCharWidth;
2297 SelectFont(hdc, oldFont);
2298 ::ReleaseDC(lb, hdc);
2300 int widthDesired = Platform::Maximum(textSize.cx, (len + 1) * tm.tmAveCharWidth);
2301 if (width < widthDesired)
2302 width = widthDesired;
2304 rcDesired.right = rcDesired.left + TextOffset() + width + (TextInset.x * 2);
2305 if (Length() > rows)
2306 rcDesired.right += ::GetSystemMetrics(SM_CXVSCROLL);
2308 AdjustWindowRect(&rcDesired);
2309 return rcDesired;
2312 int ListBoxX::TextOffset() const {
2313 int pixWidth = images.GetWidth();
2314 return static_cast<int>(pixWidth == 0 ? ItemInset.x : ItemInset.x + pixWidth + (ImageInset.x * 2));
2317 int ListBoxX::CaretFromEdge() {
2318 PRectangle rc;
2319 AdjustWindowRect(&rc);
2320 return TextOffset() + static_cast<int>(TextInset.x + (0 - rc.left) - 1);
2323 void ListBoxX::Clear() {
2324 ::SendMessage(lb, LB_RESETCONTENT, 0, 0);
2325 maxItemCharacters = 0;
2326 widestItem = NULL;
2327 lti.Clear();
2330 void ListBoxX::Append(char *, int) {
2331 // This method is no longer called in Scintilla
2332 PLATFORM_ASSERT(false);
2335 int ListBoxX::Length() {
2336 return lti.Count();
2339 void ListBoxX::Select(int n) {
2340 // We are going to scroll to centre on the new selection and then select it, so disable
2341 // redraw to avoid flicker caused by a painting new selection twice in unselected and then
2342 // selected states
2343 SetRedraw(false);
2344 CentreItem(n);
2345 ::SendMessage(lb, LB_SETCURSEL, n, 0);
2346 SetRedraw(true);
2349 int ListBoxX::GetSelection() {
2350 return static_cast<int>(::SendMessage(lb, LB_GETCURSEL, 0, 0));
2353 // This is not actually called at present
2354 int ListBoxX::Find(const char *) {
2355 return LB_ERR;
2358 void ListBoxX::GetValue(int n, char *value, int len) {
2359 ListItemData item = lti.Get(n);
2360 strncpy(value, item.text, len);
2361 value[len-1] = '\0';
2364 void ListBoxX::RegisterImage(int type, const char *xpm_data) {
2365 XPM xpmImage(xpm_data);
2366 images.Add(type, new RGBAImage(xpmImage));
2369 void ListBoxX::RegisterRGBAImage(int type, int width, int height, const unsigned char *pixelsImage) {
2370 images.Add(type, new RGBAImage(width, height, 1.0, pixelsImage));
2373 void ListBoxX::ClearRegisteredImages() {
2374 images.Clear();
2377 void ListBoxX::Draw(DRAWITEMSTRUCT *pDrawItem) {
2378 if ((pDrawItem->itemAction == ODA_SELECT) || (pDrawItem->itemAction == ODA_DRAWENTIRE)) {
2379 RECT rcBox = pDrawItem->rcItem;
2380 rcBox.left += TextOffset();
2381 if (pDrawItem->itemState & ODS_SELECTED) {
2382 RECT rcImage = pDrawItem->rcItem;
2383 rcImage.right = rcBox.left;
2384 // The image is not highlighted
2385 ::FillRect(pDrawItem->hDC, &rcImage, reinterpret_cast<HBRUSH>(COLOR_WINDOW+1));
2386 ::FillRect(pDrawItem->hDC, &rcBox, reinterpret_cast<HBRUSH>(COLOR_HIGHLIGHT+1));
2387 ::SetBkColor(pDrawItem->hDC, ::GetSysColor(COLOR_HIGHLIGHT));
2388 ::SetTextColor(pDrawItem->hDC, ::GetSysColor(COLOR_HIGHLIGHTTEXT));
2389 } else {
2390 ::FillRect(pDrawItem->hDC, &pDrawItem->rcItem, reinterpret_cast<HBRUSH>(COLOR_WINDOW+1));
2391 ::SetBkColor(pDrawItem->hDC, ::GetSysColor(COLOR_WINDOW));
2392 ::SetTextColor(pDrawItem->hDC, ::GetSysColor(COLOR_WINDOWTEXT));
2395 ListItemData item = lti.Get(pDrawItem->itemID);
2396 int pixId = item.pixId;
2397 const char *text = item.text;
2398 int len = static_cast<int>(strlen(text));
2400 RECT rcText = rcBox;
2401 ::InsetRect(&rcText, static_cast<int>(TextInset.x), static_cast<int>(TextInset.y));
2403 if (unicodeMode) {
2404 const TextWide tbuf(text, len, unicodeMode);
2405 ::DrawTextW(pDrawItem->hDC, tbuf.buffer, tbuf.tlen, &rcText, DT_NOPREFIX|DT_END_ELLIPSIS|DT_SINGLELINE|DT_NOCLIP);
2406 } else {
2407 ::DrawTextA(pDrawItem->hDC, text, len, &rcText, DT_NOPREFIX|DT_END_ELLIPSIS|DT_SINGLELINE|DT_NOCLIP);
2409 if (pDrawItem->itemState & ODS_SELECTED) {
2410 ::DrawFocusRect(pDrawItem->hDC, &rcBox);
2413 // Draw the image, if any
2414 RGBAImage *pimage = images.Get(pixId);
2415 if (pimage) {
2416 Surface *surfaceItem = Surface::Allocate(technology);
2417 if (surfaceItem) {
2418 if (technology == SCWIN_TECH_GDI) {
2419 surfaceItem->Init(pDrawItem->hDC, pDrawItem->hwndItem);
2420 long left = pDrawItem->rcItem.left + static_cast<int>(ItemInset.x + ImageInset.x);
2421 PRectangle rcImage = PRectangle::FromInts(left, pDrawItem->rcItem.top,
2422 left + images.GetWidth(), pDrawItem->rcItem.bottom);
2423 surfaceItem->DrawRGBAImage(rcImage,
2424 pimage->GetWidth(), pimage->GetHeight(), pimage->Pixels());
2425 delete surfaceItem;
2426 ::SetTextAlign(pDrawItem->hDC, TA_TOP);
2427 } else {
2428 #if defined(USE_D2D)
2429 D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties(
2430 D2D1_RENDER_TARGET_TYPE_DEFAULT,
2431 D2D1::PixelFormat(
2432 DXGI_FORMAT_B8G8R8A8_UNORM,
2433 D2D1_ALPHA_MODE_IGNORE),
2436 D2D1_RENDER_TARGET_USAGE_NONE,
2437 D2D1_FEATURE_LEVEL_DEFAULT
2439 ID2D1DCRenderTarget *pDCRT = 0;
2440 HRESULT hr = pD2DFactory->CreateDCRenderTarget(&props, &pDCRT);
2441 if (SUCCEEDED(hr)) {
2442 RECT rcWindow;
2443 GetClientRect(pDrawItem->hwndItem, &rcWindow);
2444 hr = pDCRT->BindDC(pDrawItem->hDC, &rcWindow);
2445 if (SUCCEEDED(hr)) {
2446 surfaceItem->Init(pDCRT, pDrawItem->hwndItem);
2447 pDCRT->BeginDraw();
2448 long left = pDrawItem->rcItem.left + static_cast<long>(ItemInset.x + ImageInset.x);
2449 PRectangle rcImage = PRectangle::FromInts(left, pDrawItem->rcItem.top,
2450 left + images.GetWidth(), pDrawItem->rcItem.bottom);
2451 surfaceItem->DrawRGBAImage(rcImage,
2452 pimage->GetWidth(), pimage->GetHeight(), pimage->Pixels());
2453 delete surfaceItem;
2454 pDCRT->EndDraw();
2455 pDCRT->Release();
2456 } else {
2457 delete surfaceItem;
2459 } else {
2460 delete surfaceItem;
2462 #endif
2469 void ListBoxX::AppendListItem(const char *text, const char *numword) {
2470 int pixId = -1;
2471 if (numword) {
2472 pixId = 0;
2473 char ch;
2474 while ((ch = *++numword) != '\0') {
2475 pixId = 10 * pixId + (ch - '0');
2479 lti.AllocItem(text, pixId);
2480 unsigned int len = static_cast<unsigned int>(strlen(text));
2481 if (maxItemCharacters < len) {
2482 maxItemCharacters = len;
2483 widestItem = text;
2487 void ListBoxX::SetList(const char *list, char separator, char typesep) {
2488 // Turn off redraw while populating the list - this has a significant effect, even if
2489 // the listbox is not visible.
2490 SetRedraw(false);
2491 Clear();
2492 size_t size = strlen(list);
2493 char *words = lti.SetWords(list);
2494 char *startword = words;
2495 char *numword = NULL;
2496 for (size_t i=0; i < size; i++) {
2497 if (words[i] == separator) {
2498 words[i] = '\0';
2499 if (numword)
2500 *numword = '\0';
2501 AppendListItem(startword, numword);
2502 startword = words + i + 1;
2503 numword = NULL;
2504 } else if (words[i] == typesep) {
2505 numword = words + i;
2508 if (startword) {
2509 if (numword)
2510 *numword = '\0';
2511 AppendListItem(startword, numword);
2514 // Finally populate the listbox itself with the correct number of items
2515 int count = lti.Count();
2516 ::SendMessage(lb, LB_INITSTORAGE, count, 0);
2517 for (int j=0; j<count; j++) {
2518 ::SendMessage(lb, LB_ADDSTRING, 0, j+1);
2520 SetRedraw(true);
2523 void ListBoxX::AdjustWindowRect(PRectangle *rc) {
2524 RECT rcw = RectFromPRectangle(*rc);
2525 ::AdjustWindowRectEx(&rcw, WS_THICKFRAME, false, WS_EX_WINDOWEDGE);
2526 *rc = PRectangle::FromInts(rcw.left, rcw.top, rcw.right, rcw.bottom);
2529 int ListBoxX::ItemHeight() const {
2530 int itemHeight = lineHeight + (static_cast<int>(TextInset.y) * 2);
2531 int pixHeight = images.GetHeight() + (static_cast<int>(ImageInset.y) * 2);
2532 if (itemHeight < pixHeight) {
2533 itemHeight = pixHeight;
2535 return itemHeight;
2538 int ListBoxX::MinClientWidth() const {
2539 return 12 * (aveCharWidth+aveCharWidth/3);
2542 POINT ListBoxX::MinTrackSize() const {
2543 PRectangle rc = PRectangle::FromInts(0, 0, MinClientWidth(), ItemHeight());
2544 AdjustWindowRect(&rc);
2545 POINT ret = {static_cast<LONG>(rc.Width()), static_cast<LONG>(rc.Height())};
2546 return ret;
2549 POINT ListBoxX::MaxTrackSize() const {
2550 PRectangle rc = PRectangle::FromInts(0, 0,
2551 Platform::Maximum(MinClientWidth(),
2552 maxCharWidth * maxItemCharacters + static_cast<int>(TextInset.x) * 2 +
2553 TextOffset() + ::GetSystemMetrics(SM_CXVSCROLL)),
2554 ItemHeight() * lti.Count());
2555 AdjustWindowRect(&rc);
2556 POINT ret = {static_cast<LONG>(rc.Width()), static_cast<LONG>(rc.Height())};
2557 return ret;
2560 void ListBoxX::SetRedraw(bool on) {
2561 ::SendMessage(lb, WM_SETREDRAW, static_cast<BOOL>(on), 0);
2562 if (on)
2563 ::InvalidateRect(lb, NULL, TRUE);
2566 static XYPOSITION XYMinimum(XYPOSITION a, XYPOSITION b) {
2567 if (a < b)
2568 return a;
2569 else
2570 return b;
2573 static XYPOSITION XYMaximum(XYPOSITION a, XYPOSITION b) {
2574 if (a > b)
2575 return a;
2576 else
2577 return b;
2580 void ListBoxX::ResizeToCursor() {
2581 PRectangle rc = GetPosition();
2582 POINT ptw;
2583 ::GetCursorPos(&ptw);
2584 Point pt = Point::FromInts(ptw.x, ptw.y);
2585 pt.x += dragOffset.x;
2586 pt.y += dragOffset.y;
2588 switch (resizeHit) {
2589 case HTLEFT:
2590 rc.left = pt.x;
2591 break;
2592 case HTRIGHT:
2593 rc.right = pt.x;
2594 break;
2595 case HTTOP:
2596 rc.top = pt.y;
2597 break;
2598 case HTTOPLEFT:
2599 rc.top = pt.y;
2600 rc.left = pt.x;
2601 break;
2602 case HTTOPRIGHT:
2603 rc.top = pt.y;
2604 rc.right = pt.x;
2605 break;
2606 case HTBOTTOM:
2607 rc.bottom = pt.y;
2608 break;
2609 case HTBOTTOMLEFT:
2610 rc.bottom = pt.y;
2611 rc.left = pt.x;
2612 break;
2613 case HTBOTTOMRIGHT:
2614 rc.bottom = pt.y;
2615 rc.right = pt.x;
2616 break;
2619 POINT ptMin = MinTrackSize();
2620 POINT ptMax = MaxTrackSize();
2621 // We don't allow the left edge to move at present, but just in case
2622 rc.left = XYMaximum(XYMinimum(rc.left, rcPreSize.right - ptMin.x), rcPreSize.right - ptMax.x);
2623 rc.top = XYMaximum(XYMinimum(rc.top, rcPreSize.bottom - ptMin.y), rcPreSize.bottom - ptMax.y);
2624 rc.right = XYMaximum(XYMinimum(rc.right, rcPreSize.left + ptMax.x), rcPreSize.left + ptMin.x);
2625 rc.bottom = XYMaximum(XYMinimum(rc.bottom, rcPreSize.top + ptMax.y), rcPreSize.top + ptMin.y);
2627 SetPosition(rc);
2630 void ListBoxX::StartResize(WPARAM hitCode) {
2631 rcPreSize = GetPosition();
2632 POINT cursorPos;
2633 ::GetCursorPos(&cursorPos);
2635 switch (hitCode) {
2636 case HTRIGHT:
2637 case HTBOTTOM:
2638 case HTBOTTOMRIGHT:
2639 dragOffset.x = rcPreSize.right - cursorPos.x;
2640 dragOffset.y = rcPreSize.bottom - cursorPos.y;
2641 break;
2643 case HTTOPRIGHT:
2644 dragOffset.x = rcPreSize.right - cursorPos.x;
2645 dragOffset.y = rcPreSize.top - cursorPos.y;
2646 break;
2648 // Note that the current hit test code prevents the left edge cases ever firing
2649 // as we don't want the left edge to be moveable
2650 case HTLEFT:
2651 case HTTOP:
2652 case HTTOPLEFT:
2653 dragOffset.x = rcPreSize.left - cursorPos.x;
2654 dragOffset.y = rcPreSize.top - cursorPos.y;
2655 break;
2656 case HTBOTTOMLEFT:
2657 dragOffset.x = rcPreSize.left - cursorPos.x;
2658 dragOffset.y = rcPreSize.bottom - cursorPos.y;
2659 break;
2661 default:
2662 return;
2665 ::SetCapture(GetHWND());
2666 resizeHit = static_cast<int>(hitCode);
2669 LRESULT ListBoxX::NcHitTest(WPARAM wParam, LPARAM lParam) const {
2670 LRESULT hit = ::DefWindowProc(GetHWND(), WM_NCHITTEST, wParam, lParam);
2671 // There is an apparent bug in the DefWindowProc hit test code whereby it will
2672 // return HTTOPXXX if the window in question is shorter than the default
2673 // window caption height + frame, even if one is hovering over the bottom edge of
2674 // the frame, so workaround that here
2675 if (hit >= HTTOP && hit <= HTTOPRIGHT) {
2676 int minHeight = GetSystemMetrics(SM_CYMINTRACK);
2677 PRectangle rc = const_cast<ListBoxX*>(this)->GetPosition();
2678 int yPos = GET_Y_LPARAM(lParam);
2679 if ((rc.Height() < minHeight) && (yPos > ((rc.top + rc.bottom)/2))) {
2680 hit += HTBOTTOM - HTTOP;
2684 // Nerver permit resizing that moves the left edge. Allow movement of top or bottom edge
2685 // depending on whether the list is above or below the caret
2686 switch (hit) {
2687 case HTLEFT:
2688 case HTTOPLEFT:
2689 case HTBOTTOMLEFT:
2690 hit = HTERROR;
2691 break;
2693 case HTTOP:
2694 case HTTOPRIGHT: {
2695 PRectangle rc = const_cast<ListBoxX*>(this)->GetPosition();
2696 // Valid only if caret below list
2697 if (location.y < rc.top)
2698 hit = HTERROR;
2700 break;
2702 case HTBOTTOM:
2703 case HTBOTTOMRIGHT: {
2704 PRectangle rc = const_cast<ListBoxX*>(this)->GetPosition();
2705 // Valid only if caret above list
2706 if (rc.bottom < location.y)
2707 hit = HTERROR;
2709 break;
2712 return hit;
2715 void ListBoxX::OnDoubleClick() {
2717 if (doubleClickAction != NULL) {
2718 doubleClickAction(doubleClickActionData);
2722 POINT ListBoxX::GetClientExtent() const {
2723 PRectangle rc = const_cast<ListBoxX*>(this)->GetClientPosition();
2724 POINT ret;
2725 ret.x = static_cast<LONG>(rc.Width());
2726 ret.y = static_cast<LONG>(rc.Height());
2727 return ret;
2730 void ListBoxX::CentreItem(int n) {
2731 // If below mid point, scroll up to centre, but with more items below if uneven
2732 if (n >= 0) {
2733 POINT extent = GetClientExtent();
2734 int visible = extent.y/ItemHeight();
2735 if (visible < Length()) {
2736 LRESULT top = ::SendMessage(lb, LB_GETTOPINDEX, 0, 0);
2737 int half = (visible - 1) / 2;
2738 if (n > (top + half))
2739 ::SendMessage(lb, LB_SETTOPINDEX, n - half , 0);
2744 // Performs a double-buffered paint operation to avoid flicker
2745 void ListBoxX::Paint(HDC hDC) {
2746 POINT extent = GetClientExtent();
2747 HBITMAP hBitmap = ::CreateCompatibleBitmap(hDC, extent.x, extent.y);
2748 HDC bitmapDC = ::CreateCompatibleDC(hDC);
2749 HBITMAP hBitmapOld = SelectBitmap(bitmapDC, hBitmap);
2750 // The list background is mainly erased during painting, but can be a small
2751 // unpainted area when at the end of a non-integrally sized list with a
2752 // vertical scroll bar
2753 RECT rc = { 0, 0, extent.x, extent.y };
2754 ::FillRect(bitmapDC, &rc, reinterpret_cast<HBRUSH>(COLOR_WINDOW+1));
2755 // Paint the entire client area and vertical scrollbar
2756 ::SendMessage(lb, WM_PRINT, reinterpret_cast<WPARAM>(bitmapDC), PRF_CLIENT|PRF_NONCLIENT);
2757 ::BitBlt(hDC, 0, 0, extent.x, extent.y, bitmapDC, 0, 0, SRCCOPY);
2758 // Select a stock brush to prevent warnings from BoundsChecker
2759 ::SelectObject(bitmapDC, GetStockFont(WHITE_BRUSH));
2760 SelectBitmap(bitmapDC, hBitmapOld);
2761 ::DeleteDC(bitmapDC);
2762 ::DeleteObject(hBitmap);
2765 LRESULT PASCAL ListBoxX::ControlWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
2766 try {
2767 switch (uMsg) {
2768 case WM_ERASEBKGND:
2769 return TRUE;
2771 case WM_PAINT: {
2772 PAINTSTRUCT ps;
2773 HDC hDC = ::BeginPaint(hWnd, &ps);
2774 ListBoxX *lbx = reinterpret_cast<ListBoxX *>(PointerFromWindow(::GetParent(hWnd)));
2775 if (lbx)
2776 lbx->Paint(hDC);
2777 ::EndPaint(hWnd, &ps);
2779 return 0;
2781 case WM_MOUSEACTIVATE:
2782 // This prevents the view activating when the scrollbar is clicked
2783 return MA_NOACTIVATE;
2785 case WM_LBUTTONDOWN: {
2786 // We must take control of selection to prevent the ListBox activating
2787 // the popup
2788 LRESULT lResult = ::SendMessage(hWnd, LB_ITEMFROMPOINT, 0, lParam);
2789 int item = LOWORD(lResult);
2790 if (HIWORD(lResult) == 0 && item >= 0) {
2791 ::SendMessage(hWnd, LB_SETCURSEL, item, 0);
2794 return 0;
2796 case WM_LBUTTONUP:
2797 return 0;
2799 case WM_LBUTTONDBLCLK: {
2800 ListBoxX *lbx = reinterpret_cast<ListBoxX *>(PointerFromWindow(::GetParent(hWnd)));
2801 if (lbx) {
2802 lbx->OnDoubleClick();
2805 return 0;
2807 case WM_MBUTTONDOWN:
2808 // disable the scroll wheel button click action
2809 return 0;
2812 WNDPROC prevWndProc = reinterpret_cast<WNDPROC>(GetWindowLongPtr(hWnd, GWLP_USERDATA));
2813 if (prevWndProc) {
2814 return ::CallWindowProc(prevWndProc, hWnd, uMsg, wParam, lParam);
2815 } else {
2816 return ::DefWindowProc(hWnd, uMsg, wParam, lParam);
2818 } catch (...) {
2820 return ::DefWindowProc(hWnd, uMsg, wParam, lParam);
2823 LRESULT ListBoxX::WndProc(HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam) {
2824 switch (iMessage) {
2825 case WM_CREATE: {
2826 HINSTANCE hinstanceParent = GetWindowInstance(reinterpret_cast<HWND>(parent->GetID()));
2827 // Note that LBS_NOINTEGRALHEIGHT is specified to fix cosmetic issue when resizing the list
2828 // but has useful side effect of speeding up list population significantly
2829 lb = ::CreateWindowEx(
2830 0, TEXT("listbox"), TEXT(""),
2831 WS_CHILD | WS_VSCROLL | WS_VISIBLE |
2832 LBS_OWNERDRAWFIXED | LBS_NODATA | LBS_NOINTEGRALHEIGHT,
2833 0, 0, 150,80, hWnd,
2834 reinterpret_cast<HMENU>(ctrlID),
2835 hinstanceParent,
2837 WNDPROC prevWndProc = reinterpret_cast<WNDPROC>(::SetWindowLongPtr(lb, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(ControlWndProc)));
2838 ::SetWindowLongPtr(lb, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(prevWndProc));
2840 break;
2842 case WM_SIZE:
2843 if (lb) {
2844 SetRedraw(false);
2845 ::SetWindowPos(lb, 0, 0,0, LOWORD(lParam), HIWORD(lParam), SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOMOVE);
2846 // Ensure the selection remains visible
2847 CentreItem(GetSelection());
2848 SetRedraw(true);
2850 break;
2852 case WM_PAINT: {
2853 PAINTSTRUCT ps;
2854 ::BeginPaint(hWnd, &ps);
2855 ::EndPaint(hWnd, &ps);
2857 break;
2859 case WM_COMMAND:
2860 // This is not actually needed now - the registered double click action is used
2861 // directly to action a choice from the list.
2862 ::SendMessage(reinterpret_cast<HWND>(parent->GetID()), iMessage, wParam, lParam);
2863 break;
2865 case WM_MEASUREITEM: {
2866 MEASUREITEMSTRUCT *pMeasureItem = reinterpret_cast<MEASUREITEMSTRUCT *>(lParam);
2867 pMeasureItem->itemHeight = static_cast<unsigned int>(ItemHeight());
2869 break;
2871 case WM_DRAWITEM:
2872 Draw(reinterpret_cast<DRAWITEMSTRUCT *>(lParam));
2873 break;
2875 case WM_DESTROY:
2876 lb = 0;
2877 ::SetWindowLong(hWnd, 0, 0);
2878 return ::DefWindowProc(hWnd, iMessage, wParam, lParam);
2880 case WM_ERASEBKGND:
2881 // To reduce flicker we can elide background erasure since this window is
2882 // completely covered by its child.
2883 return TRUE;
2885 case WM_GETMINMAXINFO: {
2886 MINMAXINFO *minMax = reinterpret_cast<MINMAXINFO*>(lParam);
2887 minMax->ptMaxTrackSize = MaxTrackSize();
2888 minMax->ptMinTrackSize = MinTrackSize();
2890 break;
2892 case WM_MOUSEACTIVATE:
2893 return MA_NOACTIVATE;
2895 case WM_NCHITTEST:
2896 return NcHitTest(wParam, lParam);
2898 case WM_NCLBUTTONDOWN:
2899 // We have to implement our own window resizing because the DefWindowProc
2900 // implementation insists on activating the resized window
2901 StartResize(wParam);
2902 return 0;
2904 case WM_MOUSEMOVE: {
2905 if (resizeHit == 0) {
2906 return ::DefWindowProc(hWnd, iMessage, wParam, lParam);
2907 } else {
2908 ResizeToCursor();
2911 break;
2913 case WM_LBUTTONUP:
2914 case WM_CANCELMODE:
2915 if (resizeHit != 0) {
2916 resizeHit = 0;
2917 ::ReleaseCapture();
2919 return ::DefWindowProc(hWnd, iMessage, wParam, lParam);
2921 case WM_MOUSEWHEEL:
2922 wheelDelta -= static_cast<short>(HIWORD(wParam));
2923 if (abs(wheelDelta) >= WHEEL_DELTA) {
2924 int nRows = GetVisibleRows();
2925 int linesToScroll = 1;
2926 if (nRows > 1) {
2927 linesToScroll = nRows - 1;
2929 if (linesToScroll > 3) {
2930 linesToScroll = 3;
2932 linesToScroll *= (wheelDelta / WHEEL_DELTA);
2933 LRESULT top = ::SendMessage(lb, LB_GETTOPINDEX, 0, 0) + linesToScroll;
2934 if (top < 0) {
2935 top = 0;
2937 ::SendMessage(lb, LB_SETTOPINDEX, top, 0);
2938 // update wheel delta residue
2939 if (wheelDelta >= 0)
2940 wheelDelta = wheelDelta % WHEEL_DELTA;
2941 else
2942 wheelDelta = - (-wheelDelta % WHEEL_DELTA);
2944 break;
2946 default:
2947 return ::DefWindowProc(hWnd, iMessage, wParam, lParam);
2950 return 0;
2953 LRESULT PASCAL ListBoxX::StaticWndProc(
2954 HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam) {
2955 if (iMessage == WM_CREATE) {
2956 CREATESTRUCT *pCreate = reinterpret_cast<CREATESTRUCT *>(lParam);
2957 SetWindowPointer(hWnd, pCreate->lpCreateParams);
2959 // Find C++ object associated with window.
2960 ListBoxX *lbx = reinterpret_cast<ListBoxX *>(PointerFromWindow(hWnd));
2961 if (lbx) {
2962 return lbx->WndProc(hWnd, iMessage, wParam, lParam);
2963 } else {
2964 return ::DefWindowProc(hWnd, iMessage, wParam, lParam);
2968 static bool ListBoxX_Register() {
2969 WNDCLASSEX wndclassc;
2970 wndclassc.cbSize = sizeof(wndclassc);
2971 // We need CS_HREDRAW and CS_VREDRAW because of the ellipsis that might be drawn for
2972 // truncated items in the list and the appearance/disappearance of the vertical scroll bar.
2973 // The list repaint is double-buffered to avoid the flicker this would otherwise cause.
2974 wndclassc.style = CS_GLOBALCLASS | CS_HREDRAW | CS_VREDRAW;
2975 wndclassc.cbClsExtra = 0;
2976 wndclassc.cbWndExtra = sizeof(ListBoxX *);
2977 wndclassc.hInstance = hinstPlatformRes;
2978 wndclassc.hIcon = NULL;
2979 wndclassc.hbrBackground = NULL;
2980 wndclassc.lpszMenuName = NULL;
2981 wndclassc.lpfnWndProc = ListBoxX::StaticWndProc;
2982 wndclassc.hCursor = ::LoadCursor(NULL, IDC_ARROW);
2983 wndclassc.lpszClassName = ListBoxX_ClassName;
2984 wndclassc.hIconSm = 0;
2986 return ::RegisterClassEx(&wndclassc) != 0;
2989 bool ListBoxX_Unregister() {
2990 return ::UnregisterClass(ListBoxX_ClassName, hinstPlatformRes) != 0;
2993 Menu::Menu() : mid(0) {
2996 void Menu::CreatePopUp() {
2997 Destroy();
2998 mid = ::CreatePopupMenu();
3001 void Menu::Destroy() {
3002 if (mid)
3003 ::DestroyMenu(reinterpret_cast<HMENU>(mid));
3004 mid = 0;
3007 void Menu::Show(Point pt, Window &w) {
3008 ::TrackPopupMenu(reinterpret_cast<HMENU>(mid),
3009 TPM_RIGHTBUTTON, static_cast<int>(pt.x - 4), static_cast<int>(pt.y), 0,
3010 reinterpret_cast<HWND>(w.GetID()), NULL);
3011 Destroy();
3014 static bool initialisedET = false;
3015 static bool usePerformanceCounter = false;
3016 static LARGE_INTEGER frequency;
3018 ElapsedTime::ElapsedTime() {
3019 if (!initialisedET) {
3020 usePerformanceCounter = ::QueryPerformanceFrequency(&frequency) != 0;
3021 initialisedET = true;
3023 if (usePerformanceCounter) {
3024 LARGE_INTEGER timeVal;
3025 ::QueryPerformanceCounter(&timeVal);
3026 bigBit = timeVal.HighPart;
3027 littleBit = timeVal.LowPart;
3028 } else {
3029 bigBit = clock();
3030 littleBit = 0;
3034 double ElapsedTime::Duration(bool reset) {
3035 double result;
3036 long endBigBit;
3037 long endLittleBit;
3039 if (usePerformanceCounter) {
3040 LARGE_INTEGER lEnd;
3041 ::QueryPerformanceCounter(&lEnd);
3042 endBigBit = lEnd.HighPart;
3043 endLittleBit = lEnd.LowPart;
3044 LARGE_INTEGER lBegin;
3045 lBegin.HighPart = bigBit;
3046 lBegin.LowPart = littleBit;
3047 double elapsed = static_cast<double>(lEnd.QuadPart - lBegin.QuadPart);
3048 result = elapsed / static_cast<double>(frequency.QuadPart);
3049 } else {
3050 endBigBit = clock();
3051 endLittleBit = 0;
3052 double elapsed = endBigBit - bigBit;
3053 result = elapsed / CLOCKS_PER_SEC;
3055 if (reset) {
3056 bigBit = endBigBit;
3057 littleBit = endLittleBit;
3059 return result;
3062 class DynamicLibraryImpl : public DynamicLibrary {
3063 protected:
3064 HMODULE h;
3065 public:
3066 explicit DynamicLibraryImpl(const char *modulePath) {
3067 h = ::LoadLibraryA(modulePath);
3070 virtual ~DynamicLibraryImpl() {
3071 if (h != NULL)
3072 ::FreeLibrary(h);
3075 // Use GetProcAddress to get a pointer to the relevant function.
3076 virtual Function FindFunction(const char *name) {
3077 if (h != NULL) {
3078 // C++ standard doesn't like casts betwen function pointers and void pointers so use a union
3079 union {
3080 FARPROC fp;
3081 Function f;
3082 } fnConv;
3083 fnConv.fp = ::GetProcAddress(h, name);
3084 return fnConv.f;
3085 } else {
3086 return NULL;
3090 virtual bool IsValid() {
3091 return h != NULL;
3095 DynamicLibrary *DynamicLibrary::Load(const char *modulePath) {
3096 return static_cast<DynamicLibrary *>(new DynamicLibraryImpl(modulePath));
3099 ColourDesired Platform::Chrome() {
3100 return ::GetSysColor(COLOR_3DFACE);
3103 ColourDesired Platform::ChromeHighlight() {
3104 return ::GetSysColor(COLOR_3DHIGHLIGHT);
3107 const char *Platform::DefaultFont() {
3108 return "Verdana";
3111 int Platform::DefaultFontSize() {
3112 return 8;
3115 unsigned int Platform::DoubleClickTime() {
3116 return ::GetDoubleClickTime();
3119 bool Platform::MouseButtonBounce() {
3120 return false;
3123 void Platform::DebugDisplay(const char *s) {
3124 ::OutputDebugStringA(s);
3127 bool Platform::IsKeyDown(int key) {
3128 return (::GetKeyState(key) & 0x80000000) != 0;
3131 long Platform::SendScintilla(WindowID w, unsigned int msg, unsigned long wParam, long lParam) {
3132 // This should never be called - its here to satisfy an old interface
3133 return static_cast<long>(::SendMessage(reinterpret_cast<HWND>(w), msg, wParam, lParam));
3136 long Platform::SendScintillaPointer(WindowID w, unsigned int msg, unsigned long wParam, void *lParam) {
3137 // This should never be called - its here to satisfy an old interface
3138 return static_cast<long>(::SendMessage(reinterpret_cast<HWND>(w), msg, wParam,
3139 reinterpret_cast<LPARAM>(lParam)));
3142 bool Platform::IsDBCSLeadByte(int codePage, char ch) {
3143 // Byte ranges found in Wikipedia articles with relevant search strings in each case
3144 unsigned char uch = static_cast<unsigned char>(ch);
3145 switch (codePage) {
3146 case 932:
3147 // Shift_jis
3148 return ((uch >= 0x81) && (uch <= 0x9F)) ||
3149 ((uch >= 0xE0) && (uch <= 0xEF));
3150 case 936:
3151 // GBK
3152 return (uch >= 0x81) && (uch <= 0xFE);
3153 case 949:
3154 // Korean Wansung KS C-5601-1987
3155 return (uch >= 0x81) && (uch <= 0xFE);
3156 case 950:
3157 // Big5
3158 return (uch >= 0x81) && (uch <= 0xFE);
3159 case 1361:
3160 // Korean Johab KS C-5601-1992
3161 return
3162 ((uch >= 0x84) && (uch <= 0xD3)) ||
3163 ((uch >= 0xD8) && (uch <= 0xDE)) ||
3164 ((uch >= 0xE0) && (uch <= 0xF9));
3166 return false;
3169 int Platform::DBCSCharLength(int codePage, const char *s) {
3170 if (codePage == 932 || codePage == 936 || codePage == 949 ||
3171 codePage == 950 || codePage == 1361) {
3172 return Platform::IsDBCSLeadByte(codePage, s[0]) ? 2 : 1;
3173 } else {
3174 return 1;
3178 int Platform::DBCSCharMaxLength() {
3179 return 2;
3182 // These are utility functions not really tied to a platform
3184 int Platform::Minimum(int a, int b) {
3185 if (a < b)
3186 return a;
3187 else
3188 return b;
3191 int Platform::Maximum(int a, int b) {
3192 if (a > b)
3193 return a;
3194 else
3195 return b;
3198 //#define TRACE
3200 #ifdef TRACE
3201 void Platform::DebugPrintf(const char *format, ...) {
3202 char buffer[2000];
3203 va_list pArguments;
3204 va_start(pArguments, format);
3205 vsprintf(buffer,format,pArguments);
3206 va_end(pArguments);
3207 Platform::DebugDisplay(buffer);
3209 #else
3210 void Platform::DebugPrintf(const char *, ...) {
3212 #endif
3214 static bool assertionPopUps = true;
3216 bool Platform::ShowAssertionPopUps(bool assertionPopUps_) {
3217 bool ret = assertionPopUps;
3218 assertionPopUps = assertionPopUps_;
3219 return ret;
3222 void Platform::Assert(const char *c, const char *file, int line) {
3223 char buffer[2000];
3224 sprintf(buffer, "Assertion [%s] failed at %s %d%s", c, file, line, assertionPopUps ? "" : "\r\n");
3225 if (assertionPopUps) {
3226 int idButton = ::MessageBoxA(0, buffer, "Assertion failure",
3227 MB_ABORTRETRYIGNORE|MB_ICONHAND|MB_SETFOREGROUND|MB_TASKMODAL);
3228 if (idButton == IDRETRY) {
3229 ::DebugBreak();
3230 } else if (idButton == IDIGNORE) {
3231 // all OK
3232 } else {
3233 abort();
3235 } else {
3236 Platform::DebugDisplay(buffer);
3237 ::DebugBreak();
3238 abort();
3242 int Platform::Clamp(int val, int minVal, int maxVal) {
3243 if (val > maxVal)
3244 val = maxVal;
3245 if (val < minVal)
3246 val = minVal;
3247 return val;
3250 #ifdef _MSC_VER
3251 // GetVersionEx has been deprecated fro Windows 8.1 but called here to determine if Windows 9x.
3252 // Too dangerous to find alternate check.
3253 #pragma warning(disable: 4996)
3254 #endif
3256 void Platform_Initialise(void *hInstance) {
3257 OSVERSIONINFO osv = {sizeof(OSVERSIONINFO),0,0,0,0,TEXT("")};
3258 ::GetVersionEx(&osv);
3259 onNT = osv.dwPlatformId == VER_PLATFORM_WIN32_NT;
3260 ::InitializeCriticalSection(&crPlatformLock);
3261 hinstPlatformRes = reinterpret_cast<HINSTANCE>(hInstance);
3262 // This may be called from DllMain, in which case the call to LoadLibrary
3263 // is bad because it can upset the DLL load order.
3264 if (!hDLLImage) {
3265 hDLLImage = ::LoadLibrary(TEXT("Msimg32"));
3267 if (hDLLImage) {
3268 AlphaBlendFn = (AlphaBlendSig)::GetProcAddress(hDLLImage, "AlphaBlend");
3270 if (!hDLLUser32) {
3271 hDLLUser32 = ::LoadLibrary(TEXT("User32"));
3273 if (hDLLUser32) {
3274 MonitorFromPointFn = (MonitorFromPointSig)::GetProcAddress(hDLLUser32, "MonitorFromPoint");
3275 MonitorFromRectFn = (MonitorFromRectSig)::GetProcAddress(hDLLUser32, "MonitorFromRect");
3276 GetMonitorInfoFn = (GetMonitorInfoSig)::GetProcAddress(hDLLUser32, "GetMonitorInfoA");
3279 ListBoxX_Register();
3282 #ifdef _MSC_VER
3283 #pragma warning(default: 4996)
3284 #endif
3286 void Platform_Finalise(bool fromDllMain) {
3287 #if defined(USE_D2D)
3288 if (!fromDllMain) {
3289 if (defaultRenderingParams) {
3290 defaultRenderingParams->Release();
3291 defaultRenderingParams = 0;
3293 if (customClearTypeRenderingParams) {
3294 customClearTypeRenderingParams->Release();
3295 customClearTypeRenderingParams = 0;
3297 if (pIDWriteFactory) {
3298 pIDWriteFactory->Release();
3299 pIDWriteFactory = 0;
3301 if (pD2DFactory) {
3302 pD2DFactory->Release();
3303 pD2DFactory = 0;
3305 if (hDLLDWrite) {
3306 FreeLibrary(hDLLDWrite);
3307 hDLLDWrite = NULL;
3309 if (hDLLD2D) {
3310 FreeLibrary(hDLLD2D);
3311 hDLLD2D = NULL;
3314 #endif
3315 if (reverseArrowCursor != NULL)
3316 ::DestroyCursor(reverseArrowCursor);
3317 ListBoxX_Unregister();
3318 ::DeleteCriticalSection(&crPlatformLock);
3319 if (hDLLUser32) {
3320 FreeLibrary(hDLLUser32);
3321 hDLLUser32 = NULL;
3323 if (hDLLImage) {
3324 FreeLibrary(hDLLImage);
3325 hDLLImage = NULL;
3329 #ifdef SCI_NAMESPACE
3331 #endif