18#include "IGraphicsWin.h"
19#include "IGraphicsWin_dnd.h"
24#include <VersionHelpers.h>
28#define CCSIZEOF_STRUCT(structname, member) (__builtin_offsetof(structname, member) + sizeof(((structname*)0)->member))
32using namespace igraphics;
34#ifdef IGRAPHICS_ACCESSKIT
37#pragma comment(lib, "accesskit.lib")
38#pragma comment(lib, "bcrypt.lib")
39#pragma comment(lib, "ntdll.lib")
40#pragma comment(lib, "propsys.lib")
41#pragma comment(lib, "runtimeobject.lib")
42#pragma comment(lib, "uiautomationcore.lib")
43#pragma comment(lib, "userenv.lib")
44#pragma comment(lib, "ws2_32.lib")
47BEGIN_IGRAPHICS_NAMESPACE
50class IGraphicsAccessibilityWin :
public IGraphicsAccessibility
53 IGraphicsAccessibilityWin(
IGraphics& graphics, HWND hWnd)
54 : IGraphicsAccessibility(graphics)
56 mAdapter = accesskit_windows_adapter_new(hWnd, GetFocus() == hWnd, ActionHandler,
this);
59 ~IGraphicsAccessibilityWin()
61 accesskit_windows_adapter_free(mAdapter);
64 void SetWindowFocused(
bool focused)
66 if (accesskit_windows_queued_events* pEvents = accesskit_windows_adapter_update_window_focus_state(mAdapter, focused))
67 accesskit_windows_queued_events_raise(pEvents);
70 bool HandleGetObject(WPARAM wParam, LPARAM lParam, LRESULT& result)
72 accesskit_opt_lresult optResult = accesskit_windows_adapter_handle_wm_getobject(mAdapter, wParam, lParam, ActivationHandler,
this);
74 if (optResult.has_value)
75 result = optResult.value;
77 return optResult.has_value;
81 void UpdateIfActive(accesskit_tree_update_factory factory,
void* pUserData)
override
83 if (accesskit_windows_queued_events* pEvents = accesskit_windows_adapter_update_if_active(mAdapter, factory, pUserData))
84 accesskit_windows_queued_events_raise(pEvents);
88 accesskit_windows_adapter* mAdapter =
nullptr;
91END_IGRAPHICS_NAMESPACE
95#pragma warning(disable:4244)
96#pragma warning(disable:4312)
97#pragma warning(disable:4311)
99static int nWndClassReg = 0;
100static const wchar_t* wndClassName = L
"IPlugWndClass";
101static double sFPS = 0.0;
103#define PARAM_EDIT_ID 99
104#define IPLUG_TIMER_ID 2
106#define TOOLTIPWND_MAXWIDTH 250
108#define WM_VBLANK (WM_USER+1)
111typedef HGLRC(WINAPI* PFNWGLCREATECONTEXTATTRIBSARBPROC) (HDC hDC, HGLRC hShareContext,
const int* attribList);
112#define WGL_CONTEXT_MAJOR_VERSION_ARB 0x2091
113#define WGL_CONTEXT_MINOR_VERSION_ARB 0x2092
114#define WGL_CONTEXT_PROFILE_MASK_ARB 0x9126
115#define WGL_CONTEXT_CORE_PROFILE_BIT_ARB 0x00000001
118#pragma mark - Static storage
120StaticStorage<IGraphicsWin::InstalledFont> IGraphicsWin::sPlatformFontCache;
121StaticStorage<HFontHolder> IGraphicsWin::sHFontCache;
123#pragma mark - Mouse and tablet helpers
125extern float GetScaleForHWND(HWND hWnd);
127inline IMouseInfo IGraphicsWin::GetMouseInfo(LPARAM lParam, WPARAM wParam)
130 const float scale = GetTotalScale();
131 info.x = mCursorX = GET_X_LPARAM(lParam) / scale;
132 info.y = mCursorY = GET_Y_LPARAM(lParam) / scale;
133 info.ms =
IMouseMod((wParam & MK_LBUTTON), (wParam & MK_RBUTTON), (wParam & MK_SHIFT), (wParam & MK_CONTROL),
135 GetAsyncKeyState(VK_MENU) < 0
137 GetKeyState(VK_MENU) < 0
144void IGraphicsWin::CheckTabletInput(UINT msg)
146 if ((msg == WM_LBUTTONDOWN) || (msg == WM_RBUTTONDOWN) || (msg == WM_MBUTTONDOWN) || (msg == WM_MOUSEMOVE)
147 || (msg == WM_RBUTTONDBLCLK) || (msg == WM_LBUTTONDBLCLK) || (msg == WM_MBUTTONDBLCLK)
148 || (msg == WM_RBUTTONUP) || (msg == WM_LBUTTONUP) || (msg == WM_MBUTTONUP)
149 || (msg == WM_MOUSEHOVER) || (msg == WM_MOUSELEAVE))
151 const LONG_PTR c_SIGNATURE_MASK = 0xFFFFFF00;
152 const LONG_PTR c_MOUSEEVENTF_FROMTOUCH = 0xFF515700;
154 LONG_PTR extraInfo = GetMessageExtraInfo();
155 SetTabletInput(((extraInfo & c_SIGNATURE_MASK) == c_MOUSEEVENTF_FROMTOUCH));
156 mCursorLock &= !mTabletInput;
160void IGraphicsWin::DestroyEditWindow()
164 SetWindowLongPtrW(mParamEditWnd, GWLP_WNDPROC, (LPARAM) mDefEditProc);
165 DestroyWindow(mParamEditWnd);
166 mParamEditWnd =
nullptr;
167 mDefEditProc =
nullptr;
168 DeleteObject(mEditFont);
173void IGraphicsWin::OnDisplayTimer(
int vBlankCount)
176 DWORD msgCount = vBlankCount;
177 DWORD curCount = mVBlankCount;
182 if (mVBlankSkipUntil != 0 && mVBlankSkipUntil > mVBlankCount)
187 mVBlankSkipUntil = 0;
189 if (msgCount != curCount)
197 if (mParamEditWnd && mParamEditMsg != kNone)
199 switch (mParamEditMsg)
203 WCHAR strWide[MAX_WIN32_PARAM_LEN];
204 SendMessageW(mParamEditWnd, WM_GETTEXT, MAX_WIN32_PARAM_LEN, (LPARAM) strWide);
205 SetControlValueAfterTextEdit(UTF16AsUTF8(strWide).Get());
211 ClearInTextEntryControl();
215 mParamEditMsg = kNone;
223 float scale = GetScaleForHWND(mPlugWnd);
224 if (scale != GetScreenScale())
225 SetScreenScale(scale);
231 const float totalScale = GetTotalScale();
234 SetAllControlsClean();
236 for (
int i = 0; i < rects.
Size(); i++)
239 dirtyR.
Scale(totalScale);
241 RECT r = { (LONG)dirtyR.L, (LONG)dirtyR.T, (LONG)dirtyR.R, (LONG)dirtyR.B };
242 InvalidateRect(mPlugWnd, &r, FALSE);
247 IRECT notDirtyR = mEditRECT;
248 notDirtyR.
Scale(totalScale);
250 RECT r2 = { (LONG)notDirtyR.L, (LONG)notDirtyR.T, (LONG)notDirtyR.R, (LONG)notDirtyR.B };
251 ValidateRect(mPlugWnd, &r2);
252 UpdateWindow(mPlugWnd);
253 mParamEditMsg = kUpdate;
258 UpdateWindow(mPlugWnd);
263 curCount = mVBlankCount;
264 if (msgCount != curCount)
267 mVBlankSkipUntil = curCount+1;
277LRESULT CALLBACK IGraphicsWin::WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
279 if (msg == WM_CREATE)
281 CREATESTRUCTW* lpcs = (CREATESTRUCTW *) lParam;
282 SetWindowLongPtrW(hWnd, GWLP_USERDATA, (LPARAM) lpcs->lpCreateParams);
285 if (pGraphics->mVSYNCEnabled)
287 assert((pGraphics->FPS() == 60) &&
"If you want to run at frame rates other than 60FPS");
288 pGraphics->StartVBlankThread(hWnd);
292 int mSec =
static_cast<int>(std::floorf(1000.0f / (pGraphics->FPS())));
293 if (mSec < 20) mSec = 15;
294 SetTimer(hWnd, IPLUG_TIMER_ID, mSec, NULL);
298 DragAcceptFiles(hWnd,
true);
304 if (!pGraphics || hWnd != pGraphics->mPlugWnd)
306 return DefWindowProcW(hWnd, msg, wParam, lParam);
309#ifdef IGRAPHICS_ACCESSKIT
310 if (msg == WM_GETOBJECT && pGraphics->mAccessibility)
314 if (
static_cast<IGraphicsAccessibilityWin*
>(pGraphics->mAccessibility.get())->HandleGetObject(wParam, lParam, result))
317 return DefWindowProcW(hWnd, msg, wParam, lParam);
321 if (pGraphics->mParamEditWnd && pGraphics->mParamEditMsg == kEditing)
323 if (msg == WM_RBUTTONDOWN || (msg == WM_LBUTTONDOWN))
325 pGraphics->mParamEditMsg = kCancel;
328 return DefWindowProcW(hWnd, msg, wParam, lParam);
331 auto IsTouchEvent = []() {
332 const LONG_PTR c_SIGNATURE_MASK = 0xFFFFFF00;
333 const LONG_PTR c_MOUSEEVENTF_FROMTOUCH = 0xFF515700;
334 LONG_PTR extraInfo = GetMessageExtraInfo();
335 return ((extraInfo & c_SIGNATURE_MASK) == c_MOUSEEVENTF_FROMTOUCH);
338 pGraphics->CheckTabletInput(msg);
343 pGraphics->OnDisplayTimer(wParam);
347 if (wParam == IPLUG_TIMER_ID)
348 pGraphics->OnDisplayTimer(0);
362 pGraphics->HideTooltip();
363 if (pGraphics->mParamEditWnd)
365 pGraphics->mParamEditMsg = kCommit;
370 IMouseInfo info = pGraphics->GetMouseInfo(lParam, wParam);
371 std::vector<IMouseInfo> list{ info };
372 pGraphics->OnMouseDown(list);
377 pGraphics->OnSetCursor();
385 if (!(wParam & (MK_LBUTTON | MK_RBUTTON)))
387 IMouseInfo info = pGraphics->GetMouseInfo(lParam, wParam);
388 if (pGraphics->OnMouseOver(info.x, info.y, info.ms))
390 TRACKMOUSEEVENT eventTrack = {
sizeof(TRACKMOUSEEVENT), TME_LEAVE, hWnd, HOVER_DEFAULT };
391 if (pGraphics->TooltipsEnabled())
393 int c = pGraphics->GetMouseOver();
394 if (c != pGraphics->mTooltipIdx)
396 if (c >= 0) eventTrack.dwFlags |= TME_HOVER;
397 pGraphics->mTooltipIdx = c;
398 pGraphics->HideTooltip();
402 TrackMouseEvent(&eventTrack);
405 else if (GetCapture() == hWnd && !pGraphics->IsInPlatformTextEntry())
407 float oldX = pGraphics->mCursorX;
408 float oldY = pGraphics->mCursorY;
410 IMouseInfo info = pGraphics->GetMouseInfo(lParam, wParam);
412 info.dX = info.x - oldX;
413 info.dY = info.y - oldY;
415 if (info.dX || info.dY)
417 std::vector<IMouseInfo> list{ info };
418 pGraphics->OnMouseDrag(list);
420 if (pGraphics->MouseCursorIsLocked())
422 const float x = pGraphics->mHiddenCursorX;
423 const float y = pGraphics->mHiddenCursorY;
425 pGraphics->MoveMouseCursor(x, y);
426 pGraphics->mHiddenCursorX = x;
427 pGraphics->mHiddenCursorY = y;
436 pGraphics->ShowTooltip();
441 pGraphics->HideTooltip();
442 pGraphics->OnMouseOut();
449 IMouseInfo info = pGraphics->GetMouseInfo(lParam, wParam);
450 std::vector<IMouseInfo> list{ info };
451 pGraphics->OnMouseUp(list);
454 case WM_LBUTTONDBLCLK:
455 case WM_RBUTTONDBLCLK:
460 IMouseInfo info = pGraphics->GetMouseInfo(lParam, wParam);
461 if (pGraphics->OnMouseDblClick(info.x, info.y, info.ms))
469 if (pGraphics->mParamEditWnd)
471 pGraphics->mParamEditMsg = kCancel;
476 IMouseInfo info = pGraphics->GetMouseInfo(lParam, wParam);
477 float d = GET_WHEEL_DELTA_WPARAM(wParam) / WHEEL_DELTA;
478 const float scale = pGraphics->GetTotalScale();
480 GetWindowRect(hWnd, &r);
481 pGraphics->OnMouseWheel(info.x - (r.left / scale), info.y - (r.top / scale), info.ms, d);
487 UINT nTouches = LOWORD(wParam);
491 WDL_TypedBuf<TOUCHINPUT> touches;
492 touches.Resize(nTouches);
493 HTOUCHINPUT hTouchInput = (HTOUCHINPUT) lParam;
494 std::vector<IMouseInfo> downlist;
495 std::vector<IMouseInfo> uplist;
496 std::vector<IMouseInfo> movelist;
497 const float scale = pGraphics->GetTotalScale();
499 GetTouchInputInfo(hTouchInput, nTouches, touches.Get(),
sizeof(TOUCHINPUT));
501 for (
int i = 0; i < nTouches; i++)
503 TOUCHINPUT* pTI = touches.Get() +i;
506 pt.x = TOUCH_COORD_TO_PIXEL(pTI->x);
507 pt.y = TOUCH_COORD_TO_PIXEL(pTI->y);
508 ScreenToClient(pGraphics->mPlugWnd, &pt);
511 info.x =
static_cast<float>(pt.x) / scale;
512 info.y =
static_cast<float>(pt.y) / scale;
515 info.ms.touchRadius = 0;
517 if (pTI->dwMask & TOUCHINPUTMASKF_CONTACTAREA)
519 info.ms.touchRadius = pTI->cxContact;
522 info.ms.touchID =
static_cast<ITouchID
>(pTI->dwID);
524 if (pTI->dwFlags & TOUCHEVENTF_DOWN)
526 downlist.push_back(info);
527 pGraphics->mDeltaCapture.insert(std::make_pair(info.ms.touchID, info));
529 else if (pTI->dwFlags & TOUCHEVENTF_UP)
531 pGraphics->mDeltaCapture.erase(info.ms.touchID);
532 uplist.push_back(info);
534 else if (pTI->dwFlags & TOUCHEVENTF_MOVE)
536 IMouseInfo previous = pGraphics->mDeltaCapture.find(info.ms.touchID)->second;
537 info.dX = info.x - previous.x;
538 info.dY = info.y - previous.y;
539 movelist.push_back(info);
540 pGraphics->mDeltaCapture[info.ms.touchID] = info;
545 pGraphics->OnMouseDown(downlist);
548 pGraphics->OnMouseUp(uplist);
551 pGraphics->OnMouseDrag(movelist);
553 CloseTouchInputHandle(hTouchInput);
558 return DLGC_WANTALLKEYS;
564 ScreenToClient(hWnd, &p);
566 BYTE keyboardState[256] = {};
567 GetKeyboardState(keyboardState);
568 const int keyboardScanCode = (lParam >> 16) & 0x00ff;
570 const int len = ToAscii(wParam, keyboardScanCode, keyboardState, &character, 0);
575 if (len == 0 || len == 1)
578 str[0] =
static_cast<char>(character);
581 IKeyPress keyPress{ str,
static_cast<int>(wParam),
582 static_cast<bool>(GetKeyState(VK_SHIFT) & 0x8000),
583 static_cast<bool>(GetKeyState(VK_CONTROL) & 0x8000),
584 static_cast<bool>(GetKeyState(VK_MENU) & 0x8000) };
586 const float scale = pGraphics->GetTotalScale();
588 if (msg == WM_KEYDOWN)
589 handle = pGraphics->OnKeyDown(p.x / scale, p.y / scale, keyPress);
591 handle = pGraphics->OnKeyUp(p.x / scale, p.y / scale, keyPress);
596 HWND rootHWnd = GetAncestor( hWnd, GA_ROOT);
597 SendMessageW(rootHWnd, msg, wParam, lParam);
598 return DefWindowProcW(hWnd, msg, wParam, lParam);
605 const float scale = pGraphics->GetTotalScale();
606 auto addDrawRect = [pGraphics, scale](
IRECTList& rects, RECT r) {
607 IRECT ir(r.left, r.top, r.right, r.bottom);
613 HRGN region = CreateRectRgn(0, 0, 0, 0);
614 int regionType = GetUpdateRgn(hWnd, region, FALSE);
616 if ((regionType == COMPLEXREGION) || (regionType == SIMPLEREGION))
619 const int bufferSize =
sizeof(RECT) * 64;
620 unsigned char stackBuffer[
sizeof(RGNDATA) + bufferSize];
621 RGNDATA* regionData = (RGNDATA*)stackBuffer;
623 if (regionType == COMPLEXREGION && GetRegionData(region, bufferSize, regionData))
625 for (
int i = 0; i < regionData->rdh.nCount; i++)
626 addDrawRect(rects, *(((RECT*)regionData->Buffer) + i));
631 GetRgnBox(region, &r);
632 addDrawRect(rects, r);
635#if defined IGRAPHICS_GL
637 BeginPaint(hWnd, &ps);
641 ScopedGLContext scopedGLCtx {pGraphics};
642 pGraphics->Draw(rects);
643 SwapBuffers((HDC) pGraphics->GetPlatformContext());
646#if defined IGRAPHICS_GL || IGRAPHICS_D2D
654 ValidateRect(hWnd, 0);
656 DeleteObject(region);
661 case WM_CTLCOLOREDIT:
663 if (!pGraphics->mParamEditWnd)
666 const IText& text = pGraphics->mEditText;
667 HDC dc = (HDC) wParam;
668 SetBkColor(dc, RGB(text.mTextEntryBGColor.R, text.mTextEntryBGColor.G, text.mTextEntryBGColor.B));
669 SetTextColor(dc, RGB(text.mTextEntryFGColor.R, text.mTextEntryFGColor.G, text.mTextEntryFGColor.B));
670 SetBkMode(dc, OPAQUE);
671 SetDCBrushColor(dc, RGB(text.mTextEntryBGColor.R, text.mTextEntryBGColor.G, text.mTextEntryBGColor.B));
672 return (LRESULT)GetStockObject(DC_BRUSH);
676 HDROP hdrop = (HDROP) wParam;
678 int numDroppedFiles = DragQueryFileW(hdrop, -1,
nullptr, 0);
680 std::vector<std::vector<char>> pathBuffers(numDroppedFiles, std::vector<char>(1025, 0));
681 std::vector<const char*> pathPtrs(numDroppedFiles);
683 for (
int i = 0; i < numDroppedFiles; i++)
685 wchar_t pathBufferW[1025] = {
'\0'};
686 DragQueryFileW(hdrop, i, pathBufferW, 1024);
687 strncpy(pathBuffers[i].data(), UTF16AsUTF8(pathBufferW).Get(), 1024);
688 pathPtrs[i] = pathBuffers[i].data();
691 DragQueryPoint(hdrop, &p);
693 const float scale = pGraphics->GetTotalScale();
695 if (numDroppedFiles==1)
697 pGraphics->OnDrop(&pathPtrs[0][0], p.x / scale, p.y / scale);
701 pGraphics->OnDropMultiple(pathPtrs, p.x / scale, p.y / scale);
708 pGraphics->CloseWindow();
713#ifdef IGRAPHICS_ACCESSKIT
714 if (pGraphics->mAccessibility)
715 static_cast<IGraphicsAccessibilityWin*
>(pGraphics->mAccessibility.get())->SetWindowFocused(
true);
721#ifdef IGRAPHICS_ACCESSKIT
722 if (pGraphics->mAccessibility)
723 static_cast<IGraphicsAccessibilityWin*
>(pGraphics->mAccessibility.get())->SetWindowFocused(
false);
728 return DefWindowProcW(hWnd, msg, wParam, lParam);
732LRESULT CALLBACK IGraphicsWin::ParamEditProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
736 if (pGraphics && pGraphics->mParamEditWnd && pGraphics->mParamEditWnd == hWnd)
738 pGraphics->HideTooltip();
745 if (pGraphics->mEditParam)
749 if (c == 0x08)
break;
751 switch (pGraphics->mEditParam->
Type())
753 case IParam::kTypeEnum:
754 case IParam::kTypeInt:
755 case IParam::kTypeBool:
756 if (c >=
'0' && c <=
'9')
break;
757 else if (c ==
'-')
break;
758 else if (c ==
'+')
break;
760 case IParam::kTypeDouble:
761 if (c >=
'0' && c <=
'9')
break;
762 else if (c ==
'-')
break;
763 else if (c ==
'+')
break;
764 else if (c ==
'.')
break;
774 if (wParam == VK_RETURN)
776 pGraphics->mParamEditMsg = kCommit;
779 else if (wParam == VK_ESCAPE)
781 pGraphics->mParamEditMsg = kCancel;
788 pGraphics->mParamEditMsg = kEditing;
793 pGraphics->mParamEditMsg = kCommit;
802 lres = CallWindowProcW(pGraphics->mDefEditProc, hWnd, WM_GETDLGCODE, wParam, lParam);
804 if (lParam && ((MSG*)lParam)->message == WM_KEYDOWN && wParam == VK_RETURN)
806 lres |= DLGC_WANTMESSAGE;
812 switch HIWORD(wParam)
816 if (pGraphics->mParamEditWnd)
818 pGraphics->mParamEditMsg = kCommit;
827 return CallWindowProcW(pGraphics->mDefEditProc, hWnd, msg, wParam, lParam);
829 return DefWindowProcW(hWnd, msg, wParam, lParam);
832IGraphicsWin::IGraphicsWin(
IGEditorDelegate& dlg,
int w,
int h,
int fps,
float scale)
833 : IGRAPHICS_DRAW_CLASS(dlg, w, h, fps, scale)
835 StaticStorage<InstalledFont>::Accessor fontStorage(sPlatformFontCache);
836 StaticStorage<HFontHolder>::Accessor hfontStorage(sHFontCache);
837 fontStorage.Retain();
838 hfontStorage.Retain();
840#ifndef IGRAPHICS_DISABLE_VSYNC
841 mVSYNCEnabled = IsWindows8OrGreater();
845IGraphicsWin::~IGraphicsWin()
847 StaticStorage<InstalledFont>::Accessor fontStorage(sPlatformFontCache);
848 StaticStorage<HFontHolder>::Accessor hfontStorage(sHFontCache);
849 fontStorage.Release();
850 hfontStorage.Release();
855static void GetWindowSize(HWND pWnd,
int* pW,
int* pH)
860 GetWindowRect(pWnd, &r);
861 *pW = r.right - r.left;
862 *pH = r.bottom - r.top;
870static bool IsChildWindow(HWND pWnd)
874 int style = GetWindowLongW(pWnd, GWL_STYLE);
875 int exStyle = GetWindowLongW(pWnd, GWL_EXSTYLE);
876 return ((style & WS_CHILD) && !(exStyle & WS_EX_MDICHILD));
881void IGraphicsWin::ForceEndUserEdit()
883 mParamEditMsg = kCancel;
886static UINT SETPOS_FLAGS = SWP_NOZORDER | SWP_NOMOVE | SWP_NOACTIVATE;
888void IGraphicsWin::PlatformResize(
bool parentHasResized)
892 HWND pParent = 0, pGrandparent = 0;
893 int dlgW = 0, dlgH = 0, parentW = 0, parentH = 0, grandparentW = 0, grandparentH = 0;
894 GetWindowSize(mPlugWnd, &dlgW, &dlgH);
895 int dw = (WindowWidth() * GetScreenScale()) - dlgW, dh = (WindowHeight()* GetScreenScale()) - dlgH;
897 if (IsChildWindow(mPlugWnd))
899 pParent = GetParent(mPlugWnd);
900 GetWindowSize(pParent, &parentW, &parentH);
902 if (IsChildWindow(pParent))
904 pGrandparent = GetParent(pParent);
905 GetWindowSize(pGrandparent, &grandparentW, &grandparentH);
912 SetWindowPos(mPlugWnd, 0, 0, 0, dlgW + dw, dlgH + dh, SETPOS_FLAGS);
914 if (pParent && !parentHasResized)
916 SetWindowPos(pParent, 0, 0, 0, parentW + dw, parentH + dh, SETPOS_FLAGS);
919 if (pGrandparent && !parentHasResized)
921 SetWindowPos(pGrandparent, 0, 0, 0, grandparentW + dw, grandparentH + dh, SETPOS_FLAGS);
926void IGraphicsWin::HideMouseCursor(
bool hide,
bool lock)
928 if (mCursorHidden == hide)
933 mHiddenCursorX = mCursorX;
934 mHiddenCursorY = mCursorY;
937 mCursorHidden =
true;
938 mCursorLock = lock && !mTabletInput;
943 MoveMouseCursor(mHiddenCursorX, mHiddenCursorY);
946 mCursorHidden =
false;
951void IGraphicsWin::MoveMouseCursor(
float x,
float y)
956 const float scale = GetTotalScale();
959 p.x = std::round(x * scale);
960 p.y = std::round(y * scale);
962 ::ClientToScreen(mPlugWnd, &p);
964 if (SetCursorPos(p.x, p.y))
967 ScreenToClient(mPlugWnd, &p);
969 mHiddenCursorX = mCursorX = p.x / scale;
970 mHiddenCursorY = mCursorY = p.y / scale;
974ECursor IGraphicsWin::SetMouseCursor(ECursor cursorType)
980 case ECursor::ARROW: cursor = LoadCursor(NULL, IDC_ARROW);
break;
981 case ECursor::IBEAM: cursor = LoadCursor(NULL, IDC_IBEAM);
break;
982 case ECursor::WAIT: cursor = LoadCursor(NULL, IDC_WAIT);
break;
983 case ECursor::CROSS: cursor = LoadCursor(NULL, IDC_CROSS);
break;
984 case ECursor::UPARROW: cursor = LoadCursor(NULL, IDC_UPARROW);
break;
985 case ECursor::SIZENWSE: cursor = LoadCursor(NULL, IDC_SIZENWSE);
break;
986 case ECursor::SIZENESW: cursor = LoadCursor(NULL, IDC_SIZENESW);
break;
987 case ECursor::SIZEWE: cursor = LoadCursor(NULL, IDC_SIZEWE);
break;
988 case ECursor::SIZENS: cursor = LoadCursor(NULL, IDC_SIZENS);
break;
989 case ECursor::SIZEALL: cursor = LoadCursor(NULL, IDC_SIZEALL);
break;
990 case ECursor::INO: cursor = LoadCursor(NULL, IDC_NO);
break;
991 case ECursor::HAND: cursor = LoadCursor(NULL, IDC_HAND);
break;
992 case ECursor::APPSTARTING: cursor = LoadCursor(NULL, IDC_APPSTARTING);
break;
993 case ECursor::HELP: cursor = LoadCursor(NULL, IDC_HELP);
break;
995 cursor = LoadCursor(NULL, IDC_ARROW);
1002bool IGraphicsWin::MouseCursorIsLocked()
1007void IGraphicsWin::GetMouseLocation(
float& x,
float&y)
const
1011 ScreenToClient(mPlugWnd, &p);
1013 const float scale = GetTotalScale();
1020void IGraphicsWin::CreateGLContext()
1022 PIXELFORMATDESCRIPTOR pfd =
1024 sizeof(PIXELFORMATDESCRIPTOR),
1026 PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
1042 HDC dc = GetDC(mPlugWnd);
1043 int fmt = ChoosePixelFormat(dc, &pfd);
1044 SetPixelFormat(dc, fmt, &pfd);
1045 mHGLRC = wglCreateContext(dc);
1046 wglMakeCurrent(dc, mHGLRC);
1051 auto wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC) wglGetProcAddress(
"wglCreateContextAttribsARB");
1053 if (wglCreateContextAttribsARB)
1055 wglDeleteContext(mHGLRC);
1057 const int attribList[] = {
1058 WGL_CONTEXT_MAJOR_VERSION_ARB, 3,
1059 WGL_CONTEXT_MINOR_VERSION_ARB, 3,
1060 WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
1064 mHGLRC = wglCreateContextAttribsARB(dc, 0, attribList);
1065 wglMakeCurrent(dc, mHGLRC);
1072 DBGMSG(
"Error initializing glad");
1076 ReleaseDC(mPlugWnd, dc);
1079void IGraphicsWin::DestroyGLContext()
1081 wglMakeCurrent(NULL, NULL);
1082 wglDeleteContext(mHGLRC);
1086void IGraphicsWin::ActivateGLContext()
1089 mStartHDC = wglGetCurrentDC();
1090 mStartHGLRC = wglGetCurrentContext();
1091 HDC dc = GetDC(mPlugWnd);
1092 wglMakeCurrent(dc, mHGLRC);
1096void IGraphicsWin::DeactivateGLContext()
1099 ReleaseDC(mPlugWnd, (HDC) GetPlatformContext());
1100 wglMakeCurrent(mStartHDC, mStartHGLRC);
1104EMsgBoxResult IGraphicsWin::ShowMessageBox(
const char* str,
const char* title, EMsgBoxType type, IMsgBoxCompletionHandlerFunc completionHandler)
1106 ReleaseMouseCapture();
1108 EMsgBoxResult result =
static_cast<EMsgBoxResult
>(MessageBoxW(GetMainWnd(), UTF8AsUTF16(str).Get(), UTF8AsUTF16(title).Get(),
static_cast<int>(type)));
1110 if (completionHandler)
1111 completionHandler(result);
1116void* IGraphicsWin::OpenWindow(
void* pParent)
1118 mParentWnd = (HWND) pParent;
1119 int screenScale = GetScaleForHWND(mParentWnd);
1120 int x = 0, y = 0, w = WindowWidth() * screenScale, h = WindowHeight() * screenScale;
1125 GetWindowRect((HWND) pParent, &pR);
1126 GetWindowRect(mPlugWnd, &cR);
1128 x = cR.left - pR.left;
1129 y = cR.top - pR.top;
1130 w = cR.right - cR.left;
1131 h = cR.bottom - cR.top;
1134 if (nWndClassReg++ == 0)
1136 WNDCLASSW wndClass = { CS_DBLCLKS | CS_OWNDC, WndProc, 0, 0, mHInstance, 0, 0, 0, 0, wndClassName };
1137 RegisterClassW(&wndClass);
1140 mPlugWnd = CreateWindowW(wndClassName, L
"IPlug", WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS, x, y, w, h, mParentWnd, 0, mHInstance,
this);
1142#ifdef IGRAPHICS_ACCESSKIT
1143 mAccessibility = std::make_unique<IGraphicsAccessibilityWin>(*
this, mPlugWnd);
1146 HDC dc = GetDC(mPlugWnd);
1147 SetPlatformContext(dc);
1148 ReleaseDC(mPlugWnd, dc);
1154 OnViewInitialized((
void*) dc);
1156 SetScreenScale(screenScale);
1158 GetDelegate()->LayoutUI(
this);
1160 if (MultiTouchEnabled() && GetSystemMetrics(SM_DIGITIZER) & NID_MULTI_INPUT)
1162 RegisterTouchWindow(mPlugWnd, 0);
1165 if (!mPlugWnd && --nWndClassReg == 0)
1167 UnregisterClassW(wndClassName, mHInstance);
1171 SetAllControlsDirty();
1174 if (mPlugWnd && TooltipsEnabled())
1176 static const INITCOMMONCONTROLSEX iccex = {
sizeof(INITCOMMONCONTROLSEX), ICC_TAB_CLASSES };
1178 if (InitCommonControlsEx(&iccex))
1180 mTooltipWnd = CreateWindowExW(0, TOOLTIPS_CLASSW, NULL, WS_POPUP | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | TTS_NOPREFIX | TTS_ALWAYSTIP,
1181 CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, mPlugWnd, NULL, mHInstance, NULL);
1184 SetWindowPos(mTooltipWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
1185 TOOLINFOW ti = { TTTOOLINFOW_V2_SIZE, TTF_IDISHWND | TTF_SUBCLASS, mPlugWnd, (UINT_PTR) mPlugWnd, {0, 0, 0, 0}, NULL, NULL, 0, NULL };
1186 SendMessageW(mTooltipWnd, TTM_ADDTOOLW, 0, (LPARAM) &ti);
1187 SendMessageW(mTooltipWnd, TTM_SETMAXTIPWIDTH, 0, TOOLTIPWND_MAXWIDTH);
1192 EnableTooltips(
false);
1195 wglMakeCurrent(NULL, NULL);
1199 GetDelegate()->OnUIOpen();
1204static void GetWndClassName(HWND hWnd, WDL_String* pStr)
1206 wchar_t cStrW[MAX_CLASSNAME_LEN] = {
'\0'};
1207 GetClassNameW(hWnd, cStrW, MAX_CLASSNAME_LEN);
1208 pStr->Set(UTF16AsUTF8(cStrW).Get());
1211BOOL CALLBACK IGraphicsWin::FindMainWindow(HWND hWnd, LPARAM lParam)
1217 GetWindowThreadProcessId(hWnd, &wPID);
1219 GetWndClassName(hWnd, &str);
1220 if (wPID == pGraphics->mPID && !strcmp(str.Get(), pGraphics->mMainWndClassName.Get()))
1222 pGraphics->mMainWnd = hWnd;
1229HWND IGraphicsWin::GetMainWnd()
1235 HWND parentWnd = mParentWnd;
1238 mMainWnd = parentWnd;
1239 parentWnd = GetParent(mMainWnd);
1242 GetWndClassName(mMainWnd, &mMainWndClassName);
1244 else if (CStringHasContents(mMainWndClassName.Get()))
1246 mPID = GetCurrentProcessId();
1247 EnumWindows(FindMainWindow, (LPARAM)
this);
1253IRECT IGraphicsWin::GetWindowRECT()
1258 GetWindowRect(mPlugWnd, &r);
1259 r.right -= TOOLWIN_BORDER_W;
1260 r.bottom -= TOOLWIN_BORDER_H;
1261 return IRECT(r.left, r.top, r.right, r.bottom);
1266void IGraphicsWin::CloseWindow()
1270#ifdef IGRAPHICS_ACCESSKIT
1271 mAccessibility =
nullptr;
1277 KillTimer(mPlugWnd, IPLUG_TIMER_ID);
1280 ScopedGLContext scopedGLCtx {
this};
1288 SetPlatformContext(
nullptr);
1292 DestroyWindow(mTooltipWnd);
1294 mShowingTooltip =
false;
1298 DestroyWindow(mPlugWnd);
1301 if (--nWndClassReg == 0)
1303 UnregisterClassW(wndClassName, mHInstance);
1308bool IGraphicsWin::PlatformSupportsMultiTouch()
const
1310 return GetSystemMetrics(SM_DIGITIZER) & NID_MULTI_INPUT;
1313IPopupMenu* IGraphicsWin::GetItemMenu(
long idx,
long& idxInMenu,
long& offsetIdx,
IPopupMenu& baseMenu)
1315 long oldIDx = offsetIdx;
1316 offsetIdx += baseMenu.NItems();
1318 if (idx < offsetIdx)
1320 idxInMenu = idx - oldIDx;
1326 for (
int i = 0; i< baseMenu.NItems(); i++)
1329 if (pMenuItem->GetSubmenu())
1331 pMenu = GetItemMenu(idx, idxInMenu, offsetIdx, *pMenuItem->GetSubmenu());
1341HMENU IGraphicsWin::CreateMenu(
IPopupMenu& menu,
long* pOffsetIdx)
1343 HMENU hMenu = ::CreatePopupMenu();
1345 WDL_String escapedText;
1348 long offset = *pOffsetIdx;
1349 long nItems = menu.NItems();
1350 *pOffsetIdx += nItems;
1353 for (
int i = 0; i < nItems; i++)
1357 if (pMenuItem->GetIsSeparator())
1359 AppendMenuW(hMenu, MF_SEPARATOR, 0, 0);
1363 const char* str = pMenuItem->GetText();
1364 int maxlen = strlen(str) + menu.GetPrefix() ? 50 : 0;
1365 WDL_String entryText(str);
1367 if (menu.GetPrefix())
1369 switch (menu.GetPrefix())
1373 entryText.SetFormatted(maxlen,
"%1d: %s", i+1, str);
break;
1377 entryText.SetFormatted(maxlen,
"%02d: %s", i+1, str);
break;
1381 entryText.SetFormatted(maxlen,
"%03d: %s", i+1, str);
break;
1388 if (strchr(entryText.Get(),
'&'))
1390 for (
int c = 0; c < entryText.GetLength(); c++)
1391 if (entryText.Get()[c] ==
'&')
1392 entryText.Insert(
"&", c++);
1396 if (nItems < 160 && menu.NItemsPerColumn() > 0 && inc && !(inc % menu.NItemsPerColumn()))
1397 flags |= MF_MENUBARBREAK;
1399 if (pMenuItem->GetEnabled())
1400 flags |= MF_ENABLED;
1403 if (pMenuItem->GetIsTitle())
1404 flags |= MF_DISABLED;
1405 if (pMenuItem->GetChecked())
1406 flags |= MF_CHECKED;
1408 flags |= MF_UNCHECKED;
1410 if (pMenuItem->GetSubmenu())
1412 HMENU submenu = CreateMenu(*pMenuItem->GetSubmenu(), pOffsetIdx);
1415 AppendMenuW(hMenu, flags|MF_POPUP, (UINT_PTR)submenu, UTF8AsUTF16(entryText).Get());
1420 AppendMenuW(hMenu, flags, offset + inc, UTF8AsUTF16(entryText).Get());
1432 HMENU hMenu = CreateMenu(menu, &offsetIdx);
1439 const float scale = GetTotalScale();
1441 cPos.x = bounds.L * scale;
1442 cPos.y = bounds.B * scale;
1444 ::ClientToScreen(mPlugWnd, &cPos);
1446 if (TrackPopupMenu(hMenu, TPM_LEFTALIGN, cPos.x, cPos.y, 0, mPlugWnd, 0))
1449 if (PeekMessage(&msg, mPlugWnd, WM_COMMAND, WM_COMMAND, PM_REMOVE))
1451 if (HIWORD(msg.wParam) == 0)
1453 long res = LOWORD(msg.wParam);
1458 IPopupMenu* pReturnMenu = GetItemMenu(res, idx, offsetIdx, menu);
1461 result = pReturnMenu;
1462 result->SetChosenItemIdx(idx);
1465 if (pReturnMenu && pReturnMenu->GetFunction())
1466 pReturnMenu->ExecFunction();
1474 RECT r = { 0, 0,
static_cast<LONG
>(WindowWidth() * GetScreenScale()),
static_cast<LONG
>(WindowHeight() * GetScreenScale()) };
1475 InvalidateRect(mPlugWnd, &r, FALSE);
1483void IGraphicsWin::CreatePlatformTextEntry(
int paramIdx,
const IText& text,
const IRECT& bounds,
int length,
const char* str)
1490 switch (text.mAlign)
1492 case EAlign::Near: editStyle = ES_LEFT;
break;
1493 case EAlign::Far: editStyle = ES_RIGHT;
break;
1494 case EAlign::Center:
1495 default: editStyle = ES_CENTER;
break;
1498 const float scale = GetTotalScale();
1501 mParamEditWnd = CreateWindowW(L
"EDIT", UTF8AsUTF16(str).Get(), ES_AUTOHSCROLL | WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE | ES_MULTILINE | editStyle,
1502 scaledBounds.L, scaledBounds.T, scaledBounds.
W()+1, scaledBounds.
H()+1,
1503 mPlugWnd, (HMENU) PARAM_EDIT_ID, mHInstance, 0);
1505 StaticStorage<HFontHolder>::Accessor hfontStorage(sHFontCache);
1507 LOGFONTW lFont = { 0 };
1508 HFontHolder* hfontHolder = hfontStorage.Find(text.mFont);
1509 GetObjectW(hfontHolder->mHFont,
sizeof(LOGFONTW), &lFont);
1510 lFont.lfHeight = text.mSize * scale;
1511 mEditFont = CreateFontIndirectW(&lFont);
1513 assert(hfontHolder &&
"font not found - did you forget to load it?");
1515 mEditParam = paramIdx > kNoParameter ? GetDelegate()->GetParam(paramIdx) :
nullptr;
1519 SendMessageW(mParamEditWnd, EM_LIMITTEXT, (WPARAM) length, 0);
1520 SendMessageW(mParamEditWnd, WM_SETFONT, (WPARAM) mEditFont, 0);
1521 SendMessageW(mParamEditWnd, EM_SETSEL, 0, -1);
1523 if (text.mVAlign == EVAlign::Middle)
1525 double size = text.mSize * scale;
1526 double offset = (scaledBounds.
H() - size) / 2.0;
1527 RECT formatRect{0, (LONG) offset, (LONG) scaledBounds.
W() + 1, (LONG) scaledBounds.
H() + 1};
1528 SendMessageW(mParamEditWnd, EM_SETRECT, 0, (LPARAM) &formatRect);
1531 SetFocus(mParamEditWnd);
1533 mDefEditProc = (WNDPROC) SetWindowLongPtrW(mParamEditWnd, GWLP_WNDPROC, (LONG_PTR) ParamEditProc);
1534 SetWindowLongPtrW(mParamEditWnd, GWLP_USERDATA, 0xdeadf00b);
1537bool IGraphicsWin::RevealPathInExplorerOrFinder(WDL_String& path,
bool select)
1539 bool success =
false;
1541 if (path.GetLength())
1543 WCHAR winDir[IPLUG_WIN_MAX_WIDE_PATH];
1544 UINT len = GetSystemDirectoryW(winDir, IPLUG_WIN_MAX_WIDE_PATH);
1546 if (len && !(len > MAX_PATH - 2))
1548 winDir[len] = L
'\\';
1549 winDir[++len] = L
'\0';
1551 WDL_String explorerParams;
1554 explorerParams.Append(
"/select,");
1556 explorerParams.Append(
"\"");
1557 explorerParams.Append(path.Get());
1558 explorerParams.Append(
"\\\"");
1562 if ((result=::ShellExecuteW(NULL, L
"open", L
"explorer.exe", UTF8AsUTF16(explorerParams).Get(), winDir, SW_SHOWNORMAL)) <= (HINSTANCE) 32)
1570void IGraphicsWin::PromptForFile(WDL_String& fileName, WDL_String& path, EFileAction action,
const char* ext, IFileDialogCompletionHandlerFunc completionHandler)
1572 if (!WindowIsOpen())
1578 wchar_t fileNameWide[_MAX_PATH];
1580 UTF8ToUTF16(fileNameWide, fileName.Get(), _MAX_PATH);
1585 UTF8AsUTF16 directoryWide(path);
1588 memset(&ofn, 0,
sizeof(OPENFILENAMEW));
1590 ofn.lStructSize =
sizeof(OPENFILENAMEW);
1591 ofn.hwndOwner = (HWND) GetWindow();
1592 ofn.lpstrFile = fileNameWide;
1593 ofn.nMaxFile = _MAX_PATH - 1;
1594 ofn.lpstrInitialDir = directoryWide.Get();
1595 ofn.Flags = OFN_PATHMUSTEXIST;
1597 if (CStringHasContents(ext))
1599 wchar_t extStr[256];
1600 wchar_t defExtStr[16];
1601 int i, p, n = strlen(ext);
1602 bool separator =
true;
1604 for (i = 0, p = 0; i < n; ++i)
1619 extStr[p++] = ext[i];
1623 wcscpy(&extStr[p], extStr);
1624 extStr[p + p] =
'\0';
1625 ofn.lpstrFilter = extStr;
1627 for (i = 0, p = 0; i < n && ext[i] !=
' '; ++i)
1628 defExtStr[p++] = ext[i];
1630 defExtStr[p++] =
'\0';
1631 ofn.lpstrDefExt = defExtStr;
1638 case EFileAction::Save:
1639 ofn.Flags |= OFN_OVERWRITEPROMPT;
1640 rc = GetSaveFileNameW(&ofn);
1642 case EFileAction::Open:
1644 ofn.Flags |= OFN_FILEMUSTEXIST;
1645 rc = GetOpenFileNameW(&ofn);
1651 char drive[_MAX_DRIVE];
1652 char directoryOutCStr[_MAX_PATH];
1654 UTF16AsUTF8 tempUTF8(ofn.lpstrFile);
1656 if (_splitpath_s(tempUTF8.Get(), drive,
sizeof(drive), directoryOutCStr,
sizeof(directoryOutCStr), NULL, 0, NULL, 0) == 0)
1659 path.Append(directoryOutCStr);
1662 fileName.Set(tempUTF8.Get());
1670 if (completionHandler)
1672 completionHandler(fileName, path);
1675 ReleaseMouseCapture();
1678void IGraphicsWin::PromptForDirectory(WDL_String& dir, IFileDialogCompletionHandlerFunc completionHandler)
1681 memset(&bi, 0,
sizeof(bi));
1683 bi.ulFlags = BIF_USENEWUI;
1684 bi.hwndOwner = mPlugWnd;
1685 bi.lpszTitle = L
"Choose a Directory";
1688 ::OleInitialize(NULL);
1689 LPITEMIDLIST pIDL = ::SHBrowseForFolderW(&bi);
1693 wchar_t buffer[_MAX_PATH] = {
'\0'};
1695 if (::SHGetPathFromIDListW(pIDL, buffer) != 0)
1697 dir.Set(UTF16AsUTF8(buffer).Get());
1702 CoTaskMemFree(pIDL);
1709 if (completionHandler)
1711 WDL_String fileName;
1712 completionHandler(fileName, dir);
1715 ReleaseMouseCapture();
1717 ::OleUninitialize();
1720static UINT_PTR CALLBACK CCHookProc(HWND hdlg, UINT uiMsg, WPARAM wParam, LPARAM lParam)
1722 if (uiMsg == WM_INITDIALOG && lParam)
1724 CHOOSECOLORW* cc = (CHOOSECOLORW*) lParam;
1725 if (cc && cc->lCustData)
1727 const wchar_t* strWide = (
const wchar_t*) cc->lCustData;
1728 SetWindowTextW(hdlg, strWide);
1730 uiSetRGB = RegisterWindowMessageW(SETRGBSTRINGW);
1731 SendMessageW(hdlg, uiSetRGB, 0, (LPARAM) cc->rgbResult);
1737bool IGraphicsWin::PromptForColor(
IColor& color,
const char* prompt, IColorPickerHandlerFunc func)
1739 ReleaseMouseCapture();
1744 UTF8AsUTF16 promptWide(prompt);
1746 const COLORREF w = RGB(255, 255, 255);
1747 static COLORREF customColorStorage[16] = { w, w, w, w, w, w, w, w, w, w, w, w, w, w, w, w };
1750 memset(&cc, 0,
sizeof(CHOOSECOLORW));
1751 cc.lStructSize =
sizeof(CHOOSECOLORW);
1752 cc.hwndOwner = mPlugWnd;
1753 cc.rgbResult = RGB(color.R, color.G, color.B);
1754 cc.lpCustColors = customColorStorage;
1755 cc.lCustData = (LPARAM) promptWide.Get();
1756 cc.lpfnHook = CCHookProc;
1757 cc.Flags = CC_RGBINIT | CC_ANYCOLOR | CC_FULLOPEN | CC_SOLIDCOLOR | CC_ENABLEHOOK;
1759 if (ChooseColorW(&cc))
1761 color.R = GetRValue(cc.rgbResult);
1762 color.G = GetGValue(cc.rgbResult);
1763 color.B = GetBValue(cc.rgbResult);
1773bool IGraphicsWin::OpenURL(
const char* url,
const char* msgWindowTitle,
const char* confirmMsg,
const char* errMsgOnFailure)
1775 if (confirmMsg && MessageBoxW(mPlugWnd, UTF8AsUTF16(confirmMsg).Get(), UTF8AsUTF16(msgWindowTitle).Get(), MB_YESNO) != IDYES)
1779 DWORD inetStatus = 0;
1780 if (InternetGetConnectedState(&inetStatus, 0))
1782 if (ShellExecuteW(mPlugWnd, L
"open", UTF8AsUTF16(url).Get(), 0, 0, SW_SHOWNORMAL) > HINSTANCE(32))
1787 if (errMsgOnFailure)
1789 MessageBoxW(mPlugWnd, UTF8AsUTF16(errMsgOnFailure).Get(), UTF8AsUTF16(msgWindowTitle).Get(), MB_OK);
1794void IGraphicsWin::SetTooltip(
const char* tooltip)
1796 UTF8AsUTF16 tipWide(tooltip);
1797 TOOLINFOW ti = { TTTOOLINFOW_V2_SIZE, 0, mPlugWnd, (UINT_PTR) mPlugWnd, {0, 0, 0, 0}, NULL, NULL, 0, NULL };
1798 ti.lpszText =
const_cast<wchar_t*
>(tipWide.Get());
1799 SendMessageW(mTooltipWnd, TTM_UPDATETIPTEXTW, 0, (LPARAM) &ti);
1802void IGraphicsWin::ShowTooltip()
1804 if (mTooltipIdx > -1)
1806 if (
auto* pTooltipControl = GetControl(mTooltipIdx))
1808 const char* tooltipStr = pTooltipControl->GetTooltip();
1811 SetTooltip(tooltipStr);
1812 mShowingTooltip =
true;
1818void IGraphicsWin::HideTooltip()
1820 if (mShowingTooltip)
1823 mShowingTooltip =
false;
1827bool IGraphicsWin::GetTextFromClipboard(WDL_String& str)
1829 bool result =
false;
1831 if (IsClipboardFormatAvailable(CF_UNICODETEXT))
1833 if (OpenClipboard(0))
1835 HGLOBAL hglb = GetClipboardData(CF_UNICODETEXT);
1839 WCHAR *origStr = (WCHAR*) GlobalLock(hglb);
1843 UTF16ToUTF8(str, origStr);
1859bool IGraphicsWin::SetTextInClipboard(
const char* str)
1861 if (!OpenClipboard(mMainWnd))
1871 const int lenWide = UTF8ToUTF16Len(str);
1874 HGLOBAL hglbCopy = GlobalAlloc(GMEM_MOVEABLE, lenWide*
sizeof(WCHAR));
1882 LPWSTR lpstrCopy = (LPWSTR) GlobalLock(hglbCopy);
1887 UTF8ToUTF16(lpstrCopy, str, lenWide);
1888 GlobalUnlock(hglbCopy);
1891 result = SetClipboardData(CF_UNICODETEXT, hglbCopy);
1895 GlobalFree(hglbCopy);
1904bool IGraphicsWin::SetFilePathInClipboard(
const char* path)
1906 if (!OpenClipboard(mMainWnd))
1911 UTF8AsUTF16 pathWide(path);
1915 HGLOBAL hGlobal = GlobalAlloc(GHND,
sizeof(DROPFILES) + (
sizeof(
wchar_t) * (pathWide.GetLength() + 1)));
1920 DROPFILES* pDropFiles = (DROPFILES*) GlobalLock(hGlobal);
1921 bool result =
false;
1927 pDropFiles->pFiles =
sizeof(DROPFILES);
1928 pDropFiles->pt = { 0, 0 };
1929 pDropFiles->fNC =
true;
1930 pDropFiles->fWide =
true;
1932 std::copy_n(pathWide.Get(), pathWide.GetLength(),
reinterpret_cast<wchar_t*
>(&pDropFiles[1]));
1934 GlobalUnlock(hGlobal);
1936 result = SetClipboardData(CF_HDROP, hGlobal);
1941 GlobalFree(hGlobal);
1947bool IGraphicsWin::InitiateExternalFileDragDrop(
const char* path,
const IRECT& )
1949 using namespace DragAndDropHelpers;
1950 OleInitialize(
nullptr);
1952 FORMATETC format = { CF_HDROP,
nullptr, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
1954 DataObject* dataObj =
new DataObject(&format, path);
1955 DropSource* dropSource =
new DropSource();
1958 HRESULT ret = DoDragDrop(dataObj, dropSource, DROPEFFECT_COPY, &dropEffect);
1959 bool success = SUCCEEDED(ret);
1962 dropSource->Release();
1966 ReleaseMouseCapture();
1971static HFONT GetHFont(
const char* fontName,
int weight,
bool italic,
bool underline, DWORD quality = DEFAULT_QUALITY,
bool enumerate =
false)
1973 HDC hdc = GetDC(NULL);
1974 HFONT font =
nullptr;
1979 lFont.lfEscapement = 0;
1980 lFont.lfOrientation = 0;
1981 lFont.lfWeight = weight;
1982 lFont.lfItalic = italic;
1983 lFont.lfUnderline = underline;
1984 lFont.lfStrikeOut =
false;
1985 lFont.lfCharSet = DEFAULT_CHARSET;
1986 lFont.lfOutPrecision = OUT_TT_PRECIS;
1987 lFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
1988 lFont.lfQuality = quality;
1989 lFont.lfPitchAndFamily = DEFAULT_PITCH;
1991 wcsncpy(lFont.lfFaceName, UTF8AsUTF16(fontName).Get(), LF_FACESIZE);
1993 auto enumProc = [](
const LOGFONTW* pLFont,
const TEXTMETRICW* pTextMetric, DWORD FontType, LPARAM lParam)
1998 if ((!enumerate || EnumFontFamiliesExW(hdc, &lFont, enumProc, NULL, 0) == -1))
1999 font = CreateFontIndirectW(&lFont);
2003 wchar_t selectedFontName[64] = {
'\0'};
2005 SelectFont(hdc, font);
2006 GetTextFaceW(hdc, 64, selectedFontName);
2007 if (strcmp(UTF16AsUTF8(selectedFontName).Get(), fontName))
2014 ReleaseDC(NULL, hdc);
2019PlatformFontPtr IGraphicsWin::LoadPlatformFont(
const char* fontID,
const char* fileNameOrResID)
2021 StaticStorage<InstalledFont>::Accessor fontStorage(sPlatformFontCache);
2023 void* pFontMem =
nullptr;
2025 WDL_String fullPath;
2027 const EResourceLocation fontLocation =
LocateResource(fileNameOrResID,
"ttf", fullPath, GetBundleID(), GetWinModuleHandle(),
nullptr);
2029 if (fontLocation == kNotFound)
2032 switch (fontLocation)
2036 HANDLE file = CreateFileW(UTF8AsUTF16(fullPath).Get(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
2037 PlatformFontPtr ret =
nullptr;
2040 HANDLE mapping = CreateFileMappingW(file, NULL, PAGE_READONLY, 0, 0, NULL);
2043 resSize = (int) GetFileSize(file,
nullptr);
2044 pFontMem = MapViewOfFile(mapping, FILE_MAP_READ, 0, 0, 0);
2045 ret = LoadPlatformFont(fontID, pFontMem, resSize);
2046 UnmapViewOfFile(pFontMem);
2047 CloseHandle(mapping);
2056 pFontMem =
const_cast<void *
>(
LoadWinResource(fullPath.Get(),
"ttf", resSize, GetWinModuleHandle()));
2057 return LoadPlatformFont(fontID, pFontMem, resSize);
2065PlatformFontPtr IGraphicsWin::LoadPlatformFont(
const char* fontID,
const char* fontName, ETextStyle style)
2067 int weight = style == ETextStyle::Bold ? FW_BOLD : FW_REGULAR;
2068 bool italic = style == ETextStyle::Italic;
2069 bool underline =
false;
2070 DWORD quality = DEFAULT_QUALITY;
2072 HFONT font = GetHFont(fontName, weight, italic, underline, quality,
true);
2074 return PlatformFontPtr(font ?
new Font(font,
TextStyleString(style),
true) :
nullptr);
2077PlatformFontPtr IGraphicsWin::LoadPlatformFont(
const char* fontID,
void* pData,
int dataSize)
2079 StaticStorage<InstalledFont>::Accessor fontStorage(sPlatformFontCache);
2081 std::unique_ptr<InstalledFont> pFont;
2082 void* pFontMem = pData;
2083 int resSize = dataSize;
2085 pFont = std::make_unique<InstalledFont>(pFontMem, resSize);
2087 if (pFontMem && pFont && pFont->IsValid())
2089 IFontInfo fontInfo(pFontMem, resSize, 0);
2090 WDL_String family = fontInfo.GetFamily();
2091 int weight = fontInfo.IsBold() ? FW_BOLD : FW_REGULAR;
2092 bool italic = fontInfo.IsItalic();
2093 bool underline = fontInfo.IsUnderline();
2095 HFONT font = GetHFont(family.Get(), weight, italic, underline);
2099 fontStorage.Add(pFont.release(), fontID);
2100 return PlatformFontPtr(
new Font(font,
"",
false));
2107void IGraphicsWin::CachePlatformFont(
const char* fontID,
const PlatformFontPtr& font)
2109 StaticStorage<HFontHolder>::Accessor hfontStorage(sHFontCache);
2111 HFONT hfont = font->GetDescriptor();
2113 if (!hfontStorage.Find(fontID))
2117DWORD WINAPI VBlankRun(LPVOID lpParam)
2120 return pGraphics->OnVBlankRun();
2123void IGraphicsWin::StartVBlankThread(HWND hWnd)
2125 mVBlankWindow = hWnd;
2126 mVBlankShutdown =
false;
2128 mVBlankThread = ::CreateThread(NULL, 0, VBlankRun,
this, 0, &threadId);
2131void IGraphicsWin::StopVBlankThread()
2133 if (mVBlankThread != INVALID_HANDLE_VALUE)
2135 mVBlankShutdown =
true;
2136 ::WaitForSingleObject(mVBlankThread, 10000);
2137 mVBlankThread = INVALID_HANDLE_VALUE;
2153typedef UINT32 D3DKMT_HANDLE;
2154typedef UINT D3DDDI_VIDEO_PRESENT_SOURCE_ID;
2156typedef struct _D3DKMT_OPENADAPTERFROMHDC
2159 D3DKMT_HANDLE hAdapter;
2161 D3DDDI_VIDEO_PRESENT_SOURCE_ID VidPnSourceId;
2162} D3DKMT_OPENADAPTERFROMHDC;
2164typedef struct _D3DKMT_CLOSEADAPTER
2166 D3DKMT_HANDLE hAdapter;
2167} D3DKMT_CLOSEADAPTER;
2169typedef struct _D3DKMT_WAITFORVERTICALBLANKEVENT
2171 D3DKMT_HANDLE hAdapter;
2172 D3DKMT_HANDLE hDevice;
2173 D3DDDI_VIDEO_PRESENT_SOURCE_ID VidPnSourceId;
2174} D3DKMT_WAITFORVERTICALBLANKEVENT;
2177typedef NTSTATUS(WINAPI* D3DKMTOpenAdapterFromHdc)(D3DKMT_OPENADAPTERFROMHDC* Arg1);
2178typedef NTSTATUS(WINAPI* D3DKMTCloseAdapter)(
const D3DKMT_CLOSEADAPTER* Arg1);
2179typedef NTSTATUS(WINAPI* D3DKMTWaitForVerticalBlankEvent)(
const D3DKMT_WAITFORVERTICALBLANKEVENT* Arg1);
2181DWORD IGraphicsWin::OnVBlankRun()
2183 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
2187 float rateFallback = 60.0f;
2188 int rateMS = (int)(1000.0f / rateFallback);
2196 D3DKMTOpenAdapterFromHdc pOpen =
nullptr;
2197 D3DKMTCloseAdapter pClose =
nullptr;
2198 D3DKMTWaitForVerticalBlankEvent pWait =
nullptr;
2199 HINSTANCE hInst = LoadLibraryW(L
"gdi32.dll");
2201 if (hInst !=
nullptr)
2203 pOpen = (D3DKMTOpenAdapterFromHdc) GetProcAddress((HMODULE) hInst,
"D3DKMTOpenAdapterFromHdc");
2204 pClose = (D3DKMTCloseAdapter) GetProcAddress((HMODULE) hInst,
"D3DKMTCloseAdapter");
2205 pWait = (D3DKMTWaitForVerticalBlankEvent) GetProcAddress((HMODULE) hInst,
"D3DKMTWaitForVerticalBlankEvent");
2212 if (!pOpen || !pClose || !pWait)
2214 while (mVBlankShutdown ==
false)
2224 bool adapterIsOpen =
false;
2225 DWORD adapterLastFailTime = 0;
2226 _D3DKMT_WAITFORVERTICALBLANKEVENT we = { 0 };
2228 while (mVBlankShutdown ==
false)
2233 if (adapterLastFailTime < ::GetTickCount() - 1000)
2236 D3DKMT_OPENADAPTERFROMHDC openAdapterData = { 0 };
2237 HDC hDC = GetDC(mVBlankWindow);
2238 openAdapterData.hDc = hDC;
2239 NTSTATUS status = (*pOpen)(&openAdapterData);
2243 adapterLastFailTime = 0;
2244 adapterIsOpen =
true;
2245 we.hAdapter = openAdapterData.hAdapter;
2247 we.VidPnSourceId = openAdapterData.VidPnSourceId;
2252 adapterLastFailTime = ::GetTickCount();
2261 NTSTATUS status = (*pWait)(&we);
2265 _D3DKMT_CLOSEADAPTER ca;
2266 ca.hAdapter = we.hAdapter;
2268 adapterIsOpen =
false;
2285 _D3DKMT_CLOSEADAPTER ca;
2286 ca.hAdapter = we.hAdapter;
2288 adapterIsOpen =
false;
2293 if (hInst !=
nullptr)
2295 FreeLibrary((HMODULE)hInst);
2302void IGraphicsWin::VBlankNotify()
2305 ::PostMessageW(mVBlankWindow, WM_VBLANK, mVBlankCount, 0);
2309#if defined IGRAPHICS_SKIA
2310 #include "IGraphicsSkia.cpp"
2314#elif defined IGRAPHICS_NANOVG
2315 #include "IGraphicsNanoVG.cpp"
2316#ifdef IGRAPHICS_FREETYPE
2317#define FONS_USE_FREETYPE
2318 #pragma comment(lib, "freetype.lib")
Bridges the IGraphics control hierarchy to platform accessibility APIs, via AccessKit (https://access...
Common paths useful for plug-ins.
const void * LoadWinResource(const char *resID, const char *type, int &sizeInBytes, void *pHInstance)
Load a resource from the binary (windows only).
EResourceLocation LocateResource(const char *fileNameOrResID, const char *type, WDL_String &result, const char *bundleID, void *pHInstance, const char *sharedResourcesSubPath)
Find the absolute path of a resource based on it's file name (e.g.
An editor delegate base class that uses IGraphics for the UI.
The lowest level base class of an IGraphics context.
virtual ECursor SetMouseCursor(ECursor cursorType=ECursor::ARROW)
Sets the mouse cursor to one of ECursor (implementations should return the result of the base impleme...
IGraphics platform class for Windows.
EParamType Type() const
Get the parameter's type.
Used to manage a list of rectangular areas and optimize them for drawing to the screen.
const IRECT & Get(int idx) const
Get an IRECT from the list (will crash if idx is invalid)
static const char * TextStyleString(ETextStyle style)
Helper to get a CString based on ETextStyle.
Used to group mouse coordinates with mouse modifier information.
Used to manage color data, independent of draw class/platform.
Used for key press info, such as ASCII representation, virtual key (mapped to win32 codes) and modifi...
Used to manage mouse modifiers i.e.
Used to manage a rectangular area, independent of draw class/platform.
void PixelAlign()
Pixel aligns the rect in an inclusive manner (moves all points outwards)
IRECT GetScaled(float scale) const
Get a copy of this IRECT with all values multiplied by scale.
void Scale(float scale)
Multiply each field of this IRECT by scale.
IText is used to manage font and text/text entry style for a piece of text on the UI,...