iPlug2 - C++ Audio Plug-in Framework
Loading...
Searching...
No Matches
IGraphicsWin.cpp
1/*
2 ==============================================================================
3
4 This file is part of the iPlug 2 library. Copyright (C) the iPlug 2 developers.
5
6 See LICENSE.txt for more info.
7
8 ==============================================================================
9*/
10
11
12#include <Shlobj.h>
13#include <commctrl.h>
14
15#include "heapbuf.h"
16
17#include "IPlugParameter.h"
18#include "IGraphicsWin.h"
19#include "IGraphicsWin_dnd.h"
20#include "IPopupMenuControl.h"
21#include "IPlugPaths.h"
22
23#include <wininet.h>
24#include <VersionHelpers.h>
25
26#if defined __clang__
27#undef CCSIZEOF_STRUCT
28#define CCSIZEOF_STRUCT(structname, member) (__builtin_offsetof(structname, member) + sizeof(((structname*)0)->member))
29#endif
30
31using namespace iplug;
32using namespace igraphics;
33
34#ifdef IGRAPHICS_ACCESSKIT
36
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")
45
46BEGIN_IPLUG_NAMESPACE
47BEGIN_IGRAPHICS_NAMESPACE
48
50class IGraphicsAccessibilityWin : public IGraphicsAccessibility
51{
52public:
53 IGraphicsAccessibilityWin(IGraphics& graphics, HWND hWnd)
54 : IGraphicsAccessibility(graphics)
55 {
56 mAdapter = accesskit_windows_adapter_new(hWnd, GetFocus() == hWnd, ActionHandler, this);
57 }
58
59 ~IGraphicsAccessibilityWin()
60 {
61 accesskit_windows_adapter_free(mAdapter);
62 }
63
64 void SetWindowFocused(bool focused)
65 {
66 if (accesskit_windows_queued_events* pEvents = accesskit_windows_adapter_update_window_focus_state(mAdapter, focused))
67 accesskit_windows_queued_events_raise(pEvents);
68 }
69
70 bool HandleGetObject(WPARAM wParam, LPARAM lParam, LRESULT& result)
71 {
72 accesskit_opt_lresult optResult = accesskit_windows_adapter_handle_wm_getobject(mAdapter, wParam, lParam, ActivationHandler, this);
73
74 if (optResult.has_value)
75 result = optResult.value;
76
77 return optResult.has_value;
78 }
79
80protected:
81 void UpdateIfActive(accesskit_tree_update_factory factory, void* pUserData) override
82 {
83 if (accesskit_windows_queued_events* pEvents = accesskit_windows_adapter_update_if_active(mAdapter, factory, pUserData))
84 accesskit_windows_queued_events_raise(pEvents);
85 }
86
87private:
88 accesskit_windows_adapter* mAdapter = nullptr;
89};
90
91END_IGRAPHICS_NAMESPACE
92END_IPLUG_NAMESPACE
93#endif
94
95#pragma warning(disable:4244) // Pointer size cast mismatch.
96#pragma warning(disable:4312) // Pointer size cast mismatch.
97#pragma warning(disable:4311) // Pointer size cast mismatch.
98
99static int nWndClassReg = 0;
100static const wchar_t* wndClassName = L"IPlugWndClass";
101static double sFPS = 0.0;
102
103#define PARAM_EDIT_ID 99
104#define IPLUG_TIMER_ID 2
105
106#define TOOLTIPWND_MAXWIDTH 250
107
108#define WM_VBLANK (WM_USER+1)
109
110#ifdef IGRAPHICS_GL3
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
116#endif
117
118#pragma mark - Static storage
119
120StaticStorage<IGraphicsWin::InstalledFont> IGraphicsWin::sPlatformFontCache;
121StaticStorage<HFontHolder> IGraphicsWin::sHFontCache;
122
123#pragma mark - Mouse and tablet helpers
124
125extern float GetScaleForHWND(HWND hWnd);
126
127inline IMouseInfo IGraphicsWin::GetMouseInfo(LPARAM lParam, WPARAM wParam)
128{
129 IMouseInfo info;
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),
134#ifdef AAX_API
135 GetAsyncKeyState(VK_MENU) < 0
136#else
137 GetKeyState(VK_MENU) < 0
138#endif
139 );
140
141 return info;
142}
143
144void IGraphicsWin::CheckTabletInput(UINT msg)
145{
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))
150 {
151 const LONG_PTR c_SIGNATURE_MASK = 0xFFFFFF00;
152 const LONG_PTR c_MOUSEEVENTF_FROMTOUCH = 0xFF515700;
153
154 LONG_PTR extraInfo = GetMessageExtraInfo();
155 SetTabletInput(((extraInfo & c_SIGNATURE_MASK) == c_MOUSEEVENTF_FROMTOUCH));
156 mCursorLock &= !mTabletInput;
157 }
158}
159
160void IGraphicsWin::DestroyEditWindow()
161{
162 if (mParamEditWnd)
163 {
164 SetWindowLongPtrW(mParamEditWnd, GWLP_WNDPROC, (LPARAM) mDefEditProc);
165 DestroyWindow(mParamEditWnd);
166 mParamEditWnd = nullptr;
167 mDefEditProc = nullptr;
168 DeleteObject(mEditFont);
169 mEditFont = nullptr;
170 }
171}
172
173void IGraphicsWin::OnDisplayTimer(int vBlankCount)
174{
175 // Check the message vblank with the current one to see if we are way behind. If so, then throw these away.
176 DWORD msgCount = vBlankCount;
177 DWORD curCount = mVBlankCount;
178
179 if (mVSYNCEnabled)
180 {
181 // skip until the actual vblank is at a certain number.
182 if (mVBlankSkipUntil != 0 && mVBlankSkipUntil > mVBlankCount)
183 {
184 return;
185 }
186
187 mVBlankSkipUntil = 0;
188
189 if (msgCount != curCount)
190 {
191 // we are late, just skip it until we can get a message soon after the vblank event.
192 // DBGMSG("vblank is late by %i frames. Skipping.", (mVBlankCount - msgCount));
193 return;
194 }
195 }
196
197 if (mParamEditWnd && mParamEditMsg != kNone)
198 {
199 switch (mParamEditMsg)
200 {
201 case kCommit:
202 {
203 WCHAR strWide[MAX_WIN32_PARAM_LEN];
204 SendMessageW(mParamEditWnd, WM_GETTEXT, MAX_WIN32_PARAM_LEN, (LPARAM) strWide);
205 SetControlValueAfterTextEdit(UTF16AsUTF8(strWide).Get());
206 DestroyEditWindow();
207 break;
208 }
209 case kCancel:
210 DestroyEditWindow();
211 ClearInTextEntryControl();
212 break;
213 }
214
215 mParamEditMsg = kNone;
216
217 return; // TODO: check this!
218 }
219
220 // TODO: move this... listen to the right messages in windows for screen resolution changes, etc.
221 if (!GetCapture()) // workaround Windows issues with window sizing during mouse move
222 {
223 float scale = GetScaleForHWND(mPlugWnd);
224 if (scale != GetScreenScale())
225 SetScreenScale(scale);
226 }
227
228 // TODO: this is far too aggressive for slow drawing animations and data changing. We need to
229 // gate the rate of updates to a certain percentage of the wall clock time.
230 IRECTList rects;
231 const float totalScale = GetTotalScale();
232 if (IsDirty(rects))
233 {
234 SetAllControlsClean();
235
236 for (int i = 0; i < rects.Size(); i++)
237 {
238 IRECT dirtyR = rects.Get(i);
239 dirtyR.Scale(totalScale);
240 dirtyR.PixelAlign();
241 RECT r = { (LONG)dirtyR.L, (LONG)dirtyR.T, (LONG)dirtyR.R, (LONG)dirtyR.B };
242 InvalidateRect(mPlugWnd, &r, FALSE);
243 }
244
245 if (mParamEditWnd)
246 {
247 IRECT notDirtyR = mEditRECT;
248 notDirtyR.Scale(totalScale);
249 notDirtyR.PixelAlign();
250 RECT r2 = { (LONG)notDirtyR.L, (LONG)notDirtyR.T, (LONG)notDirtyR.R, (LONG)notDirtyR.B };
251 ValidateRect(mPlugWnd, &r2); // make sure we dont redraw the edit box area
252 UpdateWindow(mPlugWnd);
253 mParamEditMsg = kUpdate;
254 }
255 else
256 {
257 // Force a redraw right now
258 UpdateWindow(mPlugWnd);
259
260 if (mVSYNCEnabled)
261 {
262 // Check and see if we are still in this frame.
263 curCount = mVBlankCount;
264 if (msgCount != curCount)
265 {
266 // we are late, skip the next vblank to give us a breather.
267 mVBlankSkipUntil = curCount+1;
268 //DBGMSG("vblank painting was late by %i frames.", (mVBlankSkipUntil - msgCount));
269 }
270 }
271 }
272 }
273 return;
274}
275
276// static
277LRESULT CALLBACK IGraphicsWin::WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
278{
279 if (msg == WM_CREATE)
280 {
281 CREATESTRUCTW* lpcs = (CREATESTRUCTW *) lParam;
282 SetWindowLongPtrW(hWnd, GWLP_USERDATA, (LPARAM) lpcs->lpCreateParams);
283 IGraphicsWin* pGraphics = (IGraphicsWin*) GetWindowLongPtrW(hWnd, GWLP_USERDATA);
284
285 if (pGraphics->mVSYNCEnabled) // use VBLANK thread
286 {
287 assert((pGraphics->FPS() == 60) && "If you want to run at frame rates other than 60FPS");
288 pGraphics->StartVBlankThread(hWnd);
289 }
290 else // use WM_TIMER -- its best to get below 16ms because the windows time quanta is slightly above 15ms.
291 {
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);
295 }
296
297 SetFocus(hWnd); // gets scroll wheel working straight away
298 DragAcceptFiles(hWnd, true);
299 return 0;
300 }
301
302 IGraphicsWin* pGraphics = (IGraphicsWin*) GetWindowLongPtrW(hWnd, GWLP_USERDATA);
303
304 if (!pGraphics || hWnd != pGraphics->mPlugWnd)
305 {
306 return DefWindowProcW(hWnd, msg, wParam, lParam);
307 }
308
309#ifdef IGRAPHICS_ACCESSKIT
310 if (msg == WM_GETOBJECT && pGraphics->mAccessibility)
311 {
312 LRESULT result = 0;
313
314 if (static_cast<IGraphicsAccessibilityWin*>(pGraphics->mAccessibility.get())->HandleGetObject(wParam, lParam, result))
315 return result;
316
317 return DefWindowProcW(hWnd, msg, wParam, lParam);
318 }
319#endif
320
321 if (pGraphics->mParamEditWnd && pGraphics->mParamEditMsg == kEditing)
322 {
323 if (msg == WM_RBUTTONDOWN || (msg == WM_LBUTTONDOWN))
324 {
325 pGraphics->mParamEditMsg = kCancel;
326 return 0;
327 }
328 return DefWindowProcW(hWnd, msg, wParam, lParam);
329 }
330
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);
336 };
337
338 pGraphics->CheckTabletInput(msg);
339
340 switch (msg)
341 {
342 case WM_VBLANK:
343 pGraphics->OnDisplayTimer(wParam);
344 return 0;
345
346 case WM_TIMER:
347 if (wParam == IPLUG_TIMER_ID)
348 pGraphics->OnDisplayTimer(0);
349
350 return 0;
351
352 case WM_ERASEBKGND:
353 return 0;
354
355 case WM_RBUTTONDOWN:
356 case WM_LBUTTONDOWN:
357 case WM_MBUTTONDOWN:
358 {
359 if (IsTouchEvent())
360 return 0;
361
362 pGraphics->HideTooltip();
363 if (pGraphics->mParamEditWnd)
364 {
365 pGraphics->mParamEditMsg = kCommit;
366 return 0;
367 }
368 SetFocus(hWnd); // Added to get keyboard focus again when user clicks in window
369 SetCapture(hWnd);
370 IMouseInfo info = pGraphics->GetMouseInfo(lParam, wParam);
371 std::vector<IMouseInfo> list{ info };
372 pGraphics->OnMouseDown(list);
373 return 0;
374 }
375 case WM_SETCURSOR:
376 {
377 pGraphics->OnSetCursor();
378 return 0;
379 }
380 case WM_MOUSEMOVE:
381 {
382 if (IsTouchEvent())
383 return 0;
384
385 if (!(wParam & (MK_LBUTTON | MK_RBUTTON)))
386 {
387 IMouseInfo info = pGraphics->GetMouseInfo(lParam, wParam);
388 if (pGraphics->OnMouseOver(info.x, info.y, info.ms))
389 {
390 TRACKMOUSEEVENT eventTrack = { sizeof(TRACKMOUSEEVENT), TME_LEAVE, hWnd, HOVER_DEFAULT };
391 if (pGraphics->TooltipsEnabled())
392 {
393 int c = pGraphics->GetMouseOver();
394 if (c != pGraphics->mTooltipIdx)
395 {
396 if (c >= 0) eventTrack.dwFlags |= TME_HOVER;
397 pGraphics->mTooltipIdx = c;
398 pGraphics->HideTooltip();
399 }
400 }
401
402 TrackMouseEvent(&eventTrack);
403 }
404 }
405 else if (GetCapture() == hWnd && !pGraphics->IsInPlatformTextEntry())
406 {
407 float oldX = pGraphics->mCursorX;
408 float oldY = pGraphics->mCursorY;
409
410 IMouseInfo info = pGraphics->GetMouseInfo(lParam, wParam);
411
412 info.dX = info.x - oldX;
413 info.dY = info.y - oldY;
414
415 if (info.dX || info.dY)
416 {
417 std::vector<IMouseInfo> list{ info };
418 pGraphics->OnMouseDrag(list);
419
420 if (pGraphics->MouseCursorIsLocked())
421 {
422 const float x = pGraphics->mHiddenCursorX;
423 const float y = pGraphics->mHiddenCursorY;
424
425 pGraphics->MoveMouseCursor(x, y);
426 pGraphics->mHiddenCursorX = x;
427 pGraphics->mHiddenCursorY = y;
428 }
429 }
430 }
431
432 return 0;
433 }
434 case WM_MOUSEHOVER:
435 {
436 pGraphics->ShowTooltip();
437 return 0;
438 }
439 case WM_MOUSELEAVE:
440 {
441 pGraphics->HideTooltip();
442 pGraphics->OnMouseOut();
443 return 0;
444 }
445 case WM_LBUTTONUP:
446 case WM_RBUTTONUP:
447 {
448 ReleaseCapture();
449 IMouseInfo info = pGraphics->GetMouseInfo(lParam, wParam);
450 std::vector<IMouseInfo> list{ info };
451 pGraphics->OnMouseUp(list);
452 return 0;
453 }
454 case WM_LBUTTONDBLCLK:
455 case WM_RBUTTONDBLCLK:
456 {
457 if (IsTouchEvent())
458 return 0;
459
460 IMouseInfo info = pGraphics->GetMouseInfo(lParam, wParam);
461 if (pGraphics->OnMouseDblClick(info.x, info.y, info.ms))
462 {
463 SetCapture(hWnd);
464 }
465 return 0;
466 }
467 case WM_MOUSEWHEEL:
468 {
469 if (pGraphics->mParamEditWnd)
470 {
471 pGraphics->mParamEditMsg = kCancel;
472 return 0;
473 }
474 else
475 {
476 IMouseInfo info = pGraphics->GetMouseInfo(lParam, wParam);
477 float d = GET_WHEEL_DELTA_WPARAM(wParam) / WHEEL_DELTA;
478 const float scale = pGraphics->GetTotalScale();
479 RECT r;
480 GetWindowRect(hWnd, &r);
481 pGraphics->OnMouseWheel(info.x - (r.left / scale), info.y - (r.top / scale), info.ms, d);
482 return 0;
483 }
484 }
485 case WM_TOUCH:
486 {
487 UINT nTouches = LOWORD(wParam);
488
489 if (nTouches > 0)
490 {
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();
498
499 GetTouchInputInfo(hTouchInput, nTouches, touches.Get(), sizeof(TOUCHINPUT));
500
501 for (int i = 0; i < nTouches; i++)
502 {
503 TOUCHINPUT* pTI = touches.Get() +i;
504
505 POINT pt;
506 pt.x = TOUCH_COORD_TO_PIXEL(pTI->x);
507 pt.y = TOUCH_COORD_TO_PIXEL(pTI->y);
508 ScreenToClient(pGraphics->mPlugWnd, &pt);
509
510 IMouseInfo info;
511 info.x = static_cast<float>(pt.x) / scale;
512 info.y = static_cast<float>(pt.y) / scale;
513 info.dX = 0.f;
514 info.dY = 0.f;
515 info.ms.touchRadius = 0;
516
517 if (pTI->dwMask & TOUCHINPUTMASKF_CONTACTAREA)
518 {
519 info.ms.touchRadius = pTI->cxContact;
520 }
521
522 info.ms.touchID = static_cast<ITouchID>(pTI->dwID);
523
524 if (pTI->dwFlags & TOUCHEVENTF_DOWN)
525 {
526 downlist.push_back(info);
527 pGraphics->mDeltaCapture.insert(std::make_pair(info.ms.touchID, info));
528 }
529 else if (pTI->dwFlags & TOUCHEVENTF_UP)
530 {
531 pGraphics->mDeltaCapture.erase(info.ms.touchID);
532 uplist.push_back(info);
533 }
534 else if (pTI->dwFlags & TOUCHEVENTF_MOVE)
535 {
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;
541 }
542 }
543
544 if (downlist.size())
545 pGraphics->OnMouseDown(downlist);
546
547 if (uplist.size())
548 pGraphics->OnMouseUp(uplist);
549
550 if (movelist.size())
551 pGraphics->OnMouseDrag(movelist);
552
553 CloseTouchInputHandle(hTouchInput);
554 }
555 return 0;
556 }
557 case WM_GETDLGCODE:
558 return DLGC_WANTALLKEYS;
559 case WM_KEYDOWN:
560 case WM_KEYUP:
561 {
562 POINT p;
563 GetCursorPos(&p);
564 ScreenToClient(hWnd, &p);
565
566 BYTE keyboardState[256] = {};
567 GetKeyboardState(keyboardState);
568 const int keyboardScanCode = (lParam >> 16) & 0x00ff;
569 WORD character = 0;
570 const int len = ToAscii(wParam, keyboardScanCode, keyboardState, &character, 0);
571 // TODO: should get unicode?
572 bool handle = false;
573
574 // send when len is 0 because wParam might be something like VK_LEFT or VK_HOME, etc.
575 if (len == 0 || len == 1)
576 {
577 char str[2];
578 str[0] = static_cast<char>(character);
579 str[1] = '\0';
580
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) };
585
586 const float scale = pGraphics->GetTotalScale();
587
588 if (msg == WM_KEYDOWN)
589 handle = pGraphics->OnKeyDown(p.x / scale, p.y / scale, keyPress);
590 else
591 handle = pGraphics->OnKeyUp(p.x / scale, p.y / scale, keyPress);
592 }
593
594 if (!handle)
595 {
596 HWND rootHWnd = GetAncestor( hWnd, GA_ROOT);
597 SendMessageW(rootHWnd, msg, wParam, lParam);
598 return DefWindowProcW(hWnd, msg, wParam, lParam);
599 }
600 else
601 return 0;
602 }
603 case WM_PAINT:
604 {
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);
608 ir.Scale(1.f/scale);
609 ir.PixelAlign();
610 rects.Add(ir);
611 };
612
613 HRGN region = CreateRectRgn(0, 0, 0, 0);
614 int regionType = GetUpdateRgn(hWnd, region, FALSE);
615
616 if ((regionType == COMPLEXREGION) || (regionType == SIMPLEREGION))
617 {
618 IRECTList rects;
619 const int bufferSize = sizeof(RECT) * 64;
620 unsigned char stackBuffer[sizeof(RGNDATA) + bufferSize];
621 RGNDATA* regionData = (RGNDATA*)stackBuffer;
622
623 if (regionType == COMPLEXREGION && GetRegionData(region, bufferSize, regionData))
624 {
625 for (int i = 0; i < regionData->rdh.nCount; i++)
626 addDrawRect(rects, *(((RECT*)regionData->Buffer) + i));
627 }
628 else
629 {
630 RECT r;
631 GetRgnBox(region, &r);
632 addDrawRect(rects, r);
633 }
634
635#if defined IGRAPHICS_GL //|| IGRAPHICS_D2D
636 PAINTSTRUCT ps;
637 BeginPaint(hWnd, &ps);
638#endif
639
640 {
641 ScopedGLContext scopedGLCtx {pGraphics};
642 pGraphics->Draw(rects);
643 SwapBuffers((HDC) pGraphics->GetPlatformContext());
644 }
645
646#if defined IGRAPHICS_GL || IGRAPHICS_D2D
647 EndPaint(hWnd, &ps);
648#endif
649 }
650
651 // For the D2D if we don't call endpaint, then you really need to call ValidateRect otherwise
652 // we are just going to get another WM_PAINT to handle. Bad! It also exibits the odd property
653 // that windows will be popped under the window.
654 ValidateRect(hWnd, 0);
655
656 DeleteObject(region);
657
658 return 0;
659 }
660
661 case WM_CTLCOLOREDIT:
662 {
663 if (!pGraphics->mParamEditWnd)
664 return 0;
665
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);
673 }
674 case WM_DROPFILES:
675 {
676 HDROP hdrop = (HDROP) wParam;
677
678 int numDroppedFiles = DragQueryFileW(hdrop, -1, nullptr, 0);
679
680 std::vector<std::vector<char>> pathBuffers(numDroppedFiles, std::vector<char>(1025, 0));
681 std::vector<const char*> pathPtrs(numDroppedFiles);
682
683 for (int i = 0; i < numDroppedFiles; i++)
684 {
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();
689 }
690 POINT p;
691 DragQueryPoint(hdrop, &p);
692
693 const float scale = pGraphics->GetTotalScale();
694
695 if (numDroppedFiles==1)
696 {
697 pGraphics->OnDrop(&pathPtrs[0][0], p.x / scale, p.y / scale);
698 }
699 else
700 {
701 pGraphics->OnDropMultiple(pathPtrs, p.x / scale, p.y / scale);
702 }
703
704 return 0;
705 }
706 case WM_CLOSE:
707 {
708 pGraphics->CloseWindow();
709 return 0;
710 }
711 case WM_SETFOCUS:
712 {
713#ifdef IGRAPHICS_ACCESSKIT
714 if (pGraphics->mAccessibility)
715 static_cast<IGraphicsAccessibilityWin*>(pGraphics->mAccessibility.get())->SetWindowFocused(true);
716#endif
717 return 0;
718 }
719 case WM_KILLFOCUS:
720 {
721#ifdef IGRAPHICS_ACCESSKIT
722 if (pGraphics->mAccessibility)
723 static_cast<IGraphicsAccessibilityWin*>(pGraphics->mAccessibility.get())->SetWindowFocused(false);
724#endif
725 return 0;
726 }
727 }
728 return DefWindowProcW(hWnd, msg, wParam, lParam);
729}
730
731// static
732LRESULT CALLBACK IGraphicsWin::ParamEditProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
733{
734 IGraphicsWin* pGraphics = (IGraphicsWin*) GetWindowLongPtrW(GetParent(hWnd), GWLP_USERDATA);
735
736 if (pGraphics && pGraphics->mParamEditWnd && pGraphics->mParamEditWnd == hWnd)
737 {
738 pGraphics->HideTooltip();
739
740 switch (msg)
741 {
742 case WM_CHAR:
743 {
744 // limit to numbers for text entry on appropriate parameters
745 if (pGraphics->mEditParam)
746 {
747 char c = wParam;
748
749 if (c == 0x08) break; // backspace
750
751 switch (pGraphics->mEditParam->Type())
752 {
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;
759 else return 0;
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;
765 else return 0;
766 default:
767 break;
768 }
769 }
770 break;
771 }
772 case WM_KEYDOWN:
773 {
774 if (wParam == VK_RETURN)
775 {
776 pGraphics->mParamEditMsg = kCommit;
777 return 0;
778 }
779 else if (wParam == VK_ESCAPE)
780 {
781 pGraphics->mParamEditMsg = kCancel;
782 return 0;
783 }
784 break;
785 }
786 case WM_SETFOCUS:
787 {
788 pGraphics->mParamEditMsg = kEditing;
789 break;
790 }
791 case WM_KILLFOCUS:
792 {
793 pGraphics->mParamEditMsg = kCommit;
794 break;
795 }
796 // handle WM_GETDLGCODE so that we can say that we want the return key message
797 // (normally single line edit boxes don't get sent return key messages)
798 case WM_GETDLGCODE:
799 {
800 LPARAM lres;
801 // find out if the original control wants it
802 lres = CallWindowProcW(pGraphics->mDefEditProc, hWnd, WM_GETDLGCODE, wParam, lParam);
803 // add in that we want it if it is a return keydown
804 if (lParam && ((MSG*)lParam)->message == WM_KEYDOWN && wParam == VK_RETURN)
805 {
806 lres |= DLGC_WANTMESSAGE;
807 }
808 return lres;
809 }
810 case WM_COMMAND:
811 {
812 switch HIWORD(wParam)
813 {
814 case CBN_SELCHANGE:
815 {
816 if (pGraphics->mParamEditWnd)
817 {
818 pGraphics->mParamEditMsg = kCommit;
819 return 0;
820 }
821 }
822
823 }
824 break; // Else let the default proc handle it.
825 }
826 }
827 return CallWindowProcW(pGraphics->mDefEditProc, hWnd, msg, wParam, lParam);
828 }
829 return DefWindowProcW(hWnd, msg, wParam, lParam);
830}
831
832IGraphicsWin::IGraphicsWin(IGEditorDelegate& dlg, int w, int h, int fps, float scale)
833 : IGRAPHICS_DRAW_CLASS(dlg, w, h, fps, scale)
834{
835 StaticStorage<InstalledFont>::Accessor fontStorage(sPlatformFontCache);
836 StaticStorage<HFontHolder>::Accessor hfontStorage(sHFontCache);
837 fontStorage.Retain();
838 hfontStorage.Retain();
839
840#ifndef IGRAPHICS_DISABLE_VSYNC
841 mVSYNCEnabled = IsWindows8OrGreater();
842#endif
843}
844
845IGraphicsWin::~IGraphicsWin()
846{
847 StaticStorage<InstalledFont>::Accessor fontStorage(sPlatformFontCache);
848 StaticStorage<HFontHolder>::Accessor hfontStorage(sHFontCache);
849 fontStorage.Release();
850 hfontStorage.Release();
851 DestroyEditWindow();
852 CloseWindow();
853}
854
855static void GetWindowSize(HWND pWnd, int* pW, int* pH)
856{
857 if (pWnd)
858 {
859 RECT r;
860 GetWindowRect(pWnd, &r);
861 *pW = r.right - r.left;
862 *pH = r.bottom - r.top;
863 }
864 else
865 {
866 *pW = *pH = 0;
867 }
868}
869
870static bool IsChildWindow(HWND pWnd)
871{
872 if (pWnd)
873 {
874 int style = GetWindowLongW(pWnd, GWL_STYLE);
875 int exStyle = GetWindowLongW(pWnd, GWL_EXSTYLE);
876 return ((style & WS_CHILD) && !(exStyle & WS_EX_MDICHILD));
877 }
878 return false;
879}
880
881void IGraphicsWin::ForceEndUserEdit()
882{
883 mParamEditMsg = kCancel;
884}
885
886static UINT SETPOS_FLAGS = SWP_NOZORDER | SWP_NOMOVE | SWP_NOACTIVATE;
887
888void IGraphicsWin::PlatformResize(bool parentHasResized)
889{
890 if (WindowIsOpen())
891 {
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;
896
897 if (IsChildWindow(mPlugWnd))
898 {
899 pParent = GetParent(mPlugWnd);
900 GetWindowSize(pParent, &parentW, &parentH);
901
902 if (IsChildWindow(pParent))
903 {
904 pGrandparent = GetParent(pParent);
905 GetWindowSize(pGrandparent, &grandparentW, &grandparentH);
906 }
907 }
908
909 if (!dw && !dh)
910 return;
911
912 SetWindowPos(mPlugWnd, 0, 0, 0, dlgW + dw, dlgH + dh, SETPOS_FLAGS);
913
914 if (pParent && !parentHasResized)
915 {
916 SetWindowPos(pParent, 0, 0, 0, parentW + dw, parentH + dh, SETPOS_FLAGS);
917 }
918
919 if (pGrandparent && !parentHasResized)
920 {
921 SetWindowPos(pGrandparent, 0, 0, 0, grandparentW + dw, grandparentH + dh, SETPOS_FLAGS);
922 }
923 }
924}
925
926void IGraphicsWin::HideMouseCursor(bool hide, bool lock)
927{
928 if (mCursorHidden == hide)
929 return;
930
931 if (hide)
932 {
933 mHiddenCursorX = mCursorX;
934 mHiddenCursorY = mCursorY;
935
936 ShowCursor(false);
937 mCursorHidden = true;
938 mCursorLock = lock && !mTabletInput;
939 }
940 else
941 {
942 if (mCursorLock)
943 MoveMouseCursor(mHiddenCursorX, mHiddenCursorY);
944
945 ShowCursor(true);
946 mCursorHidden = false;
947 mCursorLock = false;
948 }
949}
950
951void IGraphicsWin::MoveMouseCursor(float x, float y)
952{
953 if (mTabletInput)
954 return;
955
956 const float scale = GetTotalScale();
957
958 POINT p;
959 p.x = std::round(x * scale);
960 p.y = std::round(y * scale);
961
962 ::ClientToScreen(mPlugWnd, &p);
963
964 if (SetCursorPos(p.x, p.y))
965 {
966 GetCursorPos(&p);
967 ScreenToClient(mPlugWnd, &p);
968
969 mHiddenCursorX = mCursorX = p.x / scale;
970 mHiddenCursorY = mCursorY = p.y / scale;
971 }
972}
973
974ECursor IGraphicsWin::SetMouseCursor(ECursor cursorType)
975{
976 HCURSOR cursor;
977
978 switch (cursorType)
979 {
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;
994 default:
995 cursor = LoadCursor(NULL, IDC_ARROW);
996 }
997
998 SetCursor(cursor);
999 return IGraphics::SetMouseCursor(cursorType);
1000}
1001
1002bool IGraphicsWin::MouseCursorIsLocked()
1003{
1004 return mCursorLock;
1005}
1006
1007void IGraphicsWin::GetMouseLocation(float& x, float&y) const
1008{
1009 POINT p;
1010 GetCursorPos(&p);
1011 ScreenToClient(mPlugWnd, &p);
1012
1013 const float scale = GetTotalScale();
1014
1015 x = p.x / scale;
1016 y = p.y / scale;
1017}
1018
1019#ifdef IGRAPHICS_GL
1020void IGraphicsWin::CreateGLContext()
1021{
1022 PIXELFORMATDESCRIPTOR pfd =
1023 {
1024 sizeof(PIXELFORMATDESCRIPTOR),
1025 1,
1026 PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, //Flags
1027 PFD_TYPE_RGBA, // The kind of framebuffer. RGBA or palette.
1028 32, // Colordepth of the framebuffer.
1029 0, 0, 0, 0, 0, 0,
1030 0,
1031 0,
1032 0,
1033 0, 0, 0, 0,
1034 24, // Number of bits for the depthbuffer
1035 8, // Number of bits for the stencilbuffer
1036 0, // Number of Aux buffers in the framebuffer.
1037 PFD_MAIN_PLANE,
1038 0,
1039 0, 0, 0
1040 };
1041
1042 HDC dc = GetDC(mPlugWnd);
1043 int fmt = ChoosePixelFormat(dc, &pfd);
1044 SetPixelFormat(dc, fmt, &pfd);
1045 mHGLRC = wglCreateContext(dc);
1046 wglMakeCurrent(dc, mHGLRC);
1047
1048#ifdef IGRAPHICS_GL3
1049 // On windows we can't create a 3.3 context directly, since we need the wglCreateContextAttribsARB extension.
1050 // We load the extension, then re-create the context.
1051 auto wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC) wglGetProcAddress("wglCreateContextAttribsARB");
1052
1053 if (wglCreateContextAttribsARB)
1054 {
1055 wglDeleteContext(mHGLRC);
1056
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,
1061 0
1062 };
1063
1064 mHGLRC = wglCreateContextAttribsARB(dc, 0, attribList);
1065 wglMakeCurrent(dc, mHGLRC);
1066 }
1067
1068#endif
1069
1070 //TODO: return false if GL init fails?
1071 if (!gladLoadGL())
1072 DBGMSG("Error initializing glad");
1073
1074 glGetError();
1075
1076 ReleaseDC(mPlugWnd, dc);
1077}
1078
1079void IGraphicsWin::DestroyGLContext()
1080{
1081 wglMakeCurrent(NULL, NULL);
1082 wglDeleteContext(mHGLRC);
1083}
1084#endif
1085
1086void IGraphicsWin::ActivateGLContext()
1087{
1088#ifdef IGRAPHICS_GL
1089 mStartHDC = wglGetCurrentDC();
1090 mStartHGLRC = wglGetCurrentContext();
1091 HDC dc = GetDC(mPlugWnd);
1092 wglMakeCurrent(dc, mHGLRC);
1093#endif
1094}
1095
1096void IGraphicsWin::DeactivateGLContext()
1097{
1098#ifdef IGRAPHICS_GL
1099 ReleaseDC(mPlugWnd, (HDC) GetPlatformContext());
1100 wglMakeCurrent(mStartHDC, mStartHGLRC); // return current ctxt to start
1101#endif
1102}
1103
1104EMsgBoxResult IGraphicsWin::ShowMessageBox(const char* str, const char* title, EMsgBoxType type, IMsgBoxCompletionHandlerFunc completionHandler)
1105{
1106 ReleaseMouseCapture();
1107
1108 EMsgBoxResult result = static_cast<EMsgBoxResult>(MessageBoxW(GetMainWnd(), UTF8AsUTF16(str).Get(), UTF8AsUTF16(title).Get(), static_cast<int>(type)));
1109
1110 if (completionHandler)
1111 completionHandler(result);
1112
1113 return result;
1114}
1115
1116void* IGraphicsWin::OpenWindow(void* pParent)
1117{
1118 mParentWnd = (HWND) pParent;
1119 int screenScale = GetScaleForHWND(mParentWnd);
1120 int x = 0, y = 0, w = WindowWidth() * screenScale, h = WindowHeight() * screenScale;
1121
1122 if (mPlugWnd)
1123 {
1124 RECT pR, cR;
1125 GetWindowRect((HWND) pParent, &pR);
1126 GetWindowRect(mPlugWnd, &cR);
1127 CloseWindow();
1128 x = cR.left - pR.left;
1129 y = cR.top - pR.top;
1130 w = cR.right - cR.left;
1131 h = cR.bottom - cR.top;
1132 }
1133
1134 if (nWndClassReg++ == 0)
1135 {
1136 WNDCLASSW wndClass = { CS_DBLCLKS | CS_OWNDC, WndProc, 0, 0, mHInstance, 0, 0, 0, 0, wndClassName };
1137 RegisterClassW(&wndClass);
1138 }
1139
1140 mPlugWnd = CreateWindowW(wndClassName, L"IPlug", WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS, x, y, w, h, mParentWnd, 0, mHInstance, this);
1141
1142#ifdef IGRAPHICS_ACCESSKIT
1143 mAccessibility = std::make_unique<IGraphicsAccessibilityWin>(*this, mPlugWnd);
1144#endif
1145
1146 HDC dc = GetDC(mPlugWnd);
1147 SetPlatformContext(dc);
1148 ReleaseDC(mPlugWnd, dc);
1149
1150#ifdef IGRAPHICS_GL
1151 CreateGLContext();
1152#endif
1153
1154 OnViewInitialized((void*) dc);
1155
1156 SetScreenScale(screenScale); // resizes draw context
1157
1158 GetDelegate()->LayoutUI(this);
1159
1160 if (MultiTouchEnabled() && GetSystemMetrics(SM_DIGITIZER) & NID_MULTI_INPUT)
1161 {
1162 RegisterTouchWindow(mPlugWnd, 0);
1163 }
1164
1165 if (!mPlugWnd && --nWndClassReg == 0)
1166 {
1167 UnregisterClassW(wndClassName, mHInstance);
1168 }
1169 else
1170 {
1171 SetAllControlsDirty();
1172 }
1173
1174 if (mPlugWnd && TooltipsEnabled())
1175 {
1176 static const INITCOMMONCONTROLSEX iccex = { sizeof(INITCOMMONCONTROLSEX), ICC_TAB_CLASSES };
1177
1178 if (InitCommonControlsEx(&iccex))
1179 {
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);
1182 if (mTooltipWnd)
1183 {
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);
1188 }
1189 }
1190
1191 if (!mTooltipWnd)
1192 EnableTooltips(false);
1193
1194#ifdef IGRAPHICS_GL
1195 wglMakeCurrent(NULL, NULL);
1196#endif
1197 }
1198
1199 GetDelegate()->OnUIOpen();
1200
1201 return mPlugWnd;
1202}
1203
1204static void GetWndClassName(HWND hWnd, WDL_String* pStr)
1205{
1206 wchar_t cStrW[MAX_CLASSNAME_LEN] = {'\0'};
1207 GetClassNameW(hWnd, cStrW, MAX_CLASSNAME_LEN);
1208 pStr->Set(UTF16AsUTF8(cStrW).Get());
1209}
1210
1211BOOL CALLBACK IGraphicsWin::FindMainWindow(HWND hWnd, LPARAM lParam)
1212{
1213 IGraphicsWin* pGraphics = (IGraphicsWin*) lParam;
1214 if (pGraphics)
1215 {
1216 DWORD wPID;
1217 GetWindowThreadProcessId(hWnd, &wPID);
1218 WDL_String str;
1219 GetWndClassName(hWnd, &str);
1220 if (wPID == pGraphics->mPID && !strcmp(str.Get(), pGraphics->mMainWndClassName.Get()))
1221 {
1222 pGraphics->mMainWnd = hWnd;
1223 return FALSE; // Stop enumerating.
1224 }
1225 }
1226 return TRUE;
1227}
1228
1229HWND IGraphicsWin::GetMainWnd()
1230{
1231 if (!mMainWnd)
1232 {
1233 if (mParentWnd)
1234 {
1235 HWND parentWnd = mParentWnd;
1236 while (parentWnd)
1237 {
1238 mMainWnd = parentWnd;
1239 parentWnd = GetParent(mMainWnd);
1240 }
1241
1242 GetWndClassName(mMainWnd, &mMainWndClassName);
1243 }
1244 else if (CStringHasContents(mMainWndClassName.Get()))
1245 {
1246 mPID = GetCurrentProcessId();
1247 EnumWindows(FindMainWindow, (LPARAM) this);
1248 }
1249 }
1250 return mMainWnd;
1251}
1252
1253IRECT IGraphicsWin::GetWindowRECT()
1254{
1255 if (mPlugWnd)
1256 {
1257 RECT r;
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);
1262 }
1263 return IRECT();
1264}
1265
1266void IGraphicsWin::CloseWindow()
1267{
1268 if (mPlugWnd)
1269 {
1270#ifdef IGRAPHICS_ACCESSKIT
1271 mAccessibility = nullptr;
1272#endif
1273
1274 if (mVSYNCEnabled)
1275 StopVBlankThread();
1276 else
1277 KillTimer(mPlugWnd, IPLUG_TIMER_ID);
1278
1279 {
1280 ScopedGLContext scopedGLCtx {this};
1281 OnViewDestroyed();
1282 }
1283
1284#ifdef IGRAPHICS_GL
1285 DestroyGLContext();
1286#endif
1287
1288 SetPlatformContext(nullptr);
1289
1290 if (mTooltipWnd)
1291 {
1292 DestroyWindow(mTooltipWnd);
1293 mTooltipWnd = 0;
1294 mShowingTooltip = false;
1295 mTooltipIdx = -1;
1296 }
1297
1298 DestroyWindow(mPlugWnd);
1299 mPlugWnd = 0;
1300
1301 if (--nWndClassReg == 0)
1302 {
1303 UnregisterClassW(wndClassName, mHInstance);
1304 }
1305 }
1306}
1307
1308bool IGraphicsWin::PlatformSupportsMultiTouch() const
1309{
1310 return GetSystemMetrics(SM_DIGITIZER) & NID_MULTI_INPUT;
1311}
1312
1313IPopupMenu* IGraphicsWin::GetItemMenu(long idx, long& idxInMenu, long& offsetIdx, IPopupMenu& baseMenu)
1314{
1315 long oldIDx = offsetIdx;
1316 offsetIdx += baseMenu.NItems();
1317
1318 if (idx < offsetIdx)
1319 {
1320 idxInMenu = idx - oldIDx;
1321 return &baseMenu;
1322 }
1323
1324 IPopupMenu* pMenu = nullptr;
1325
1326 for (int i = 0; i< baseMenu.NItems(); i++)
1327 {
1328 IPopupMenu::Item* pMenuItem = baseMenu.GetItem(i);
1329 if (pMenuItem->GetSubmenu())
1330 {
1331 pMenu = GetItemMenu(idx, idxInMenu, offsetIdx, *pMenuItem->GetSubmenu());
1332
1333 if (pMenu)
1334 break;
1335 }
1336 }
1337
1338 return pMenu;
1339}
1340
1341HMENU IGraphicsWin::CreateMenu(IPopupMenu& menu, long* pOffsetIdx)
1342{
1343 HMENU hMenu = ::CreatePopupMenu();
1344
1345 WDL_String escapedText;
1346
1347 int flags = 0;
1348 long offset = *pOffsetIdx;
1349 long nItems = menu.NItems();
1350 *pOffsetIdx += nItems;
1351 long inc = 0;
1352
1353 for (int i = 0; i < nItems; i++)
1354 {
1355 IPopupMenu::Item* pMenuItem = menu.GetItem(i);
1356
1357 if (pMenuItem->GetIsSeparator())
1358 {
1359 AppendMenuW(hMenu, MF_SEPARATOR, 0, 0);
1360 }
1361 else
1362 {
1363 const char* str = pMenuItem->GetText();
1364 int maxlen = strlen(str) + menu.GetPrefix() ? 50 : 0;
1365 WDL_String entryText(str);
1366
1367 if (menu.GetPrefix())
1368 {
1369 switch (menu.GetPrefix())
1370 {
1371 case 1:
1372 {
1373 entryText.SetFormatted(maxlen, "%1d: %s", i+1, str); break;
1374 }
1375 case 2:
1376 {
1377 entryText.SetFormatted(maxlen, "%02d: %s", i+1, str); break;
1378 }
1379 case 3:
1380 {
1381 entryText.SetFormatted(maxlen, "%03d: %s", i+1, str); break;
1382 }
1383 }
1384 }
1385
1386 // Escape ampersands if present
1387
1388 if (strchr(entryText.Get(), '&'))
1389 {
1390 for (int c = 0; c < entryText.GetLength(); c++)
1391 if (entryText.Get()[c] == '&')
1392 entryText.Insert("&", c++);
1393 }
1394
1395 flags = MF_STRING;
1396 if (nItems < 160 && menu.NItemsPerColumn() > 0 && inc && !(inc % menu.NItemsPerColumn()))
1397 flags |= MF_MENUBARBREAK;
1398
1399 if (pMenuItem->GetEnabled())
1400 flags |= MF_ENABLED;
1401 else
1402 flags |= MF_GRAYED;
1403 if (pMenuItem->GetIsTitle())
1404 flags |= MF_DISABLED;
1405 if (pMenuItem->GetChecked())
1406 flags |= MF_CHECKED;
1407 else
1408 flags |= MF_UNCHECKED;
1409
1410 if (pMenuItem->GetSubmenu())
1411 {
1412 HMENU submenu = CreateMenu(*pMenuItem->GetSubmenu(), pOffsetIdx);
1413 if (submenu)
1414 {
1415 AppendMenuW(hMenu, flags|MF_POPUP, (UINT_PTR)submenu, UTF8AsUTF16(entryText).Get());
1416 }
1417 }
1418 else
1419 {
1420 AppendMenuW(hMenu, flags, offset + inc, UTF8AsUTF16(entryText).Get());
1421 }
1422 }
1423 inc++;
1424 }
1425
1426 return hMenu;
1427}
1428
1429IPopupMenu* IGraphicsWin::CreatePlatformPopupMenu(IPopupMenu& menu, const IRECT bounds, bool& isAsync)
1430{
1431 long offsetIdx = 0;
1432 HMENU hMenu = CreateMenu(menu, &offsetIdx);
1433
1434 if (hMenu)
1435 {
1436 IPopupMenu* result = nullptr;
1437
1438 POINT cPos;
1439 const float scale = GetTotalScale();
1440
1441 cPos.x = bounds.L * scale;
1442 cPos.y = bounds.B * scale;
1443
1444 ::ClientToScreen(mPlugWnd, &cPos);
1445
1446 if (TrackPopupMenu(hMenu, TPM_LEFTALIGN, cPos.x, cPos.y, 0, mPlugWnd, 0))
1447 {
1448 MSG msg;
1449 if (PeekMessage(&msg, mPlugWnd, WM_COMMAND, WM_COMMAND, PM_REMOVE))
1450 {
1451 if (HIWORD(msg.wParam) == 0)
1452 {
1453 long res = LOWORD(msg.wParam);
1454 if (res != -1)
1455 {
1456 long idx = 0;
1457 offsetIdx = 0;
1458 IPopupMenu* pReturnMenu = GetItemMenu(res, idx, offsetIdx, menu);
1459 if (pReturnMenu)
1460 {
1461 result = pReturnMenu;
1462 result->SetChosenItemIdx(idx);
1463
1464 //synchronous
1465 if (pReturnMenu && pReturnMenu->GetFunction())
1466 pReturnMenu->ExecFunction();
1467 }
1468 }
1469 }
1470 }
1471 }
1472 DestroyMenu(hMenu);
1473
1474 RECT r = { 0, 0, static_cast<LONG>(WindowWidth() * GetScreenScale()), static_cast<LONG>(WindowHeight() * GetScreenScale()) };
1475 InvalidateRect(mPlugWnd, &r, FALSE);
1476
1477 return result;
1478 }
1479
1480 return nullptr;
1481}
1482
1483void IGraphicsWin::CreatePlatformTextEntry(int paramIdx, const IText& text, const IRECT& bounds, int length, const char* str)
1484{
1485 if (mParamEditWnd)
1486 return;
1487
1488 DWORD editStyle;
1489
1490 switch (text.mAlign)
1491 {
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;
1496 }
1497
1498 const float scale = GetTotalScale();
1499 IRECT scaledBounds = bounds.GetScaled(scale);
1500
1501 mParamEditWnd = CreateWindowW(L"EDIT", UTF8AsUTF16(str).Get(), ES_AUTOHSCROLL /*only works for left aligned text*/ | 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);
1504
1505 StaticStorage<HFontHolder>::Accessor hfontStorage(sHFontCache);
1506
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);
1512
1513 assert(hfontHolder && "font not found - did you forget to load it?");
1514
1515 mEditParam = paramIdx > kNoParameter ? GetDelegate()->GetParam(paramIdx) : nullptr;
1516 mEditText = text;
1517 mEditRECT = bounds;
1518
1519 SendMessageW(mParamEditWnd, EM_LIMITTEXT, (WPARAM) length, 0);
1520 SendMessageW(mParamEditWnd, WM_SETFONT, (WPARAM) mEditFont, 0);
1521 SendMessageW(mParamEditWnd, EM_SETSEL, 0, -1);
1522
1523 if (text.mVAlign == EVAlign::Middle)
1524 {
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);
1529 }
1530
1531 SetFocus(mParamEditWnd);
1532
1533 mDefEditProc = (WNDPROC) SetWindowLongPtrW(mParamEditWnd, GWLP_WNDPROC, (LONG_PTR) ParamEditProc);
1534 SetWindowLongPtrW(mParamEditWnd, GWLP_USERDATA, 0xdeadf00b);
1535}
1536
1537bool IGraphicsWin::RevealPathInExplorerOrFinder(WDL_String& path, bool select)
1538{
1539 bool success = false;
1540
1541 if (path.GetLength())
1542 {
1543 WCHAR winDir[IPLUG_WIN_MAX_WIDE_PATH];
1544 UINT len = GetSystemDirectoryW(winDir, IPLUG_WIN_MAX_WIDE_PATH);
1545
1546 if (len && !(len > MAX_PATH - 2))
1547 {
1548 winDir[len] = L'\\';
1549 winDir[++len] = L'\0';
1550
1551 WDL_String explorerParams;
1552
1553 if (select)
1554 explorerParams.Append("/select,");
1555
1556 explorerParams.Append("\"");
1557 explorerParams.Append(path.Get());
1558 explorerParams.Append("\\\"");
1559
1560 HINSTANCE result;
1561
1562 if ((result=::ShellExecuteW(NULL, L"open", L"explorer.exe", UTF8AsUTF16(explorerParams).Get(), winDir, SW_SHOWNORMAL)) <= (HINSTANCE) 32)
1563 success = true;
1564 }
1565 }
1566
1567 return success;
1568}
1569
1570void IGraphicsWin::PromptForFile(WDL_String& fileName, WDL_String& path, EFileAction action, const char* ext, IFileDialogCompletionHandlerFunc completionHandler)
1571{
1572 if (!WindowIsOpen())
1573 {
1574 fileName.Set("");
1575 return;
1576 }
1577
1578 wchar_t fileNameWide[_MAX_PATH];
1579
1580 UTF8ToUTF16(fileNameWide, fileName.Get(), _MAX_PATH);
1581
1582 //if (!path.GetLength())
1583 // DesktopPath(path);
1584
1585 UTF8AsUTF16 directoryWide(path);
1586
1587 OPENFILENAMEW ofn;
1588 memset(&ofn, 0, sizeof(OPENFILENAMEW));
1589
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;
1596
1597 if (CStringHasContents(ext))
1598 {
1599 wchar_t extStr[256];
1600 wchar_t defExtStr[16];
1601 int i, p, n = strlen(ext);
1602 bool separator = true;
1603
1604 for (i = 0, p = 0; i < n; ++i)
1605 {
1606 if (separator)
1607 {
1608 if (p)
1609 extStr[p++] = ';';
1610
1611 separator = false;
1612 extStr[p++] = '*';
1613 extStr[p++] = '.';
1614 }
1615
1616 if (ext[i] == ' ')
1617 separator = true;
1618 else
1619 extStr[p++] = ext[i];
1620 }
1621 extStr[p++] = '\0';
1622
1623 wcscpy(&extStr[p], extStr);
1624 extStr[p + p] = '\0';
1625 ofn.lpstrFilter = extStr;
1626
1627 for (i = 0, p = 0; i < n && ext[i] != ' '; ++i)
1628 defExtStr[p++] = ext[i];
1629
1630 defExtStr[p++] = '\0';
1631 ofn.lpstrDefExt = defExtStr;
1632 }
1633
1634 bool rc = false;
1635
1636 switch (action)
1637 {
1638 case EFileAction::Save:
1639 ofn.Flags |= OFN_OVERWRITEPROMPT;
1640 rc = GetSaveFileNameW(&ofn);
1641 break;
1642 case EFileAction::Open:
1643 default:
1644 ofn.Flags |= OFN_FILEMUSTEXIST;
1645 rc = GetOpenFileNameW(&ofn);
1646 break;
1647 }
1648
1649 if (rc)
1650 {
1651 char drive[_MAX_DRIVE];
1652 char directoryOutCStr[_MAX_PATH];
1653
1654 UTF16AsUTF8 tempUTF8(ofn.lpstrFile);
1655
1656 if (_splitpath_s(tempUTF8.Get(), drive, sizeof(drive), directoryOutCStr, sizeof(directoryOutCStr), NULL, 0, NULL, 0) == 0)
1657 {
1658 path.Set(drive);
1659 path.Append(directoryOutCStr);
1660 }
1661
1662 fileName.Set(tempUTF8.Get());
1663 }
1664 else
1665 {
1666 fileName.Set("");
1667 }
1668
1669 // Async is not required on windows, but call the completion handler anyway
1670 if (completionHandler)
1671 {
1672 completionHandler(fileName, path);
1673 }
1674
1675 ReleaseMouseCapture();
1676}
1677
1678void IGraphicsWin::PromptForDirectory(WDL_String& dir, IFileDialogCompletionHandlerFunc completionHandler)
1679{
1680 BROWSEINFOW bi;
1681 memset(&bi, 0, sizeof(bi));
1682
1683 bi.ulFlags = BIF_USENEWUI;
1684 bi.hwndOwner = mPlugWnd;
1685 bi.lpszTitle = L"Choose a Directory";
1686
1687 // must call this if using BIF_USENEWUI
1688 ::OleInitialize(NULL);
1689 LPITEMIDLIST pIDL = ::SHBrowseForFolderW(&bi);
1690
1691 if (pIDL != NULL)
1692 {
1693 wchar_t buffer[_MAX_PATH] = {'\0'};
1694
1695 if (::SHGetPathFromIDListW(pIDL, buffer) != 0)
1696 {
1697 dir.Set(UTF16AsUTF8(buffer).Get());
1698 dir.Append("\\");
1699 }
1700
1701 // free the item id list
1702 CoTaskMemFree(pIDL);
1703 }
1704 else
1705 {
1706 dir.Set("");
1707 }
1708
1709 if (completionHandler)
1710 {
1711 WDL_String fileName; // not used
1712 completionHandler(fileName, dir);
1713 }
1714
1715 ReleaseMouseCapture();
1716
1717 ::OleUninitialize();
1718}
1719
1720static UINT_PTR CALLBACK CCHookProc(HWND hdlg, UINT uiMsg, WPARAM wParam, LPARAM lParam)
1721{
1722 if (uiMsg == WM_INITDIALOG && lParam)
1723 {
1724 CHOOSECOLORW* cc = (CHOOSECOLORW*) lParam;
1725 if (cc && cc->lCustData)
1726 {
1727 const wchar_t* strWide = (const wchar_t*) cc->lCustData;
1728 SetWindowTextW(hdlg, strWide);
1729 UINT uiSetRGB;
1730 uiSetRGB = RegisterWindowMessageW(SETRGBSTRINGW);
1731 SendMessageW(hdlg, uiSetRGB, 0, (LPARAM) cc->rgbResult);
1732 }
1733 }
1734 return 0;
1735}
1736
1737bool IGraphicsWin::PromptForColor(IColor& color, const char* prompt, IColorPickerHandlerFunc func)
1738{
1739 ReleaseMouseCapture();
1740
1741 if (!mPlugWnd)
1742 return false;
1743
1744 UTF8AsUTF16 promptWide(prompt);
1745
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 };
1748
1749 CHOOSECOLORW cc;
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;
1758
1759 if (ChooseColorW(&cc))
1760 {
1761 color.R = GetRValue(cc.rgbResult);
1762 color.G = GetGValue(cc.rgbResult);
1763 color.B = GetBValue(cc.rgbResult);
1764
1765 if (func)
1766 func(color);
1767
1768 return true;
1769 }
1770 return false;
1771}
1772
1773bool IGraphicsWin::OpenURL(const char* url, const char* msgWindowTitle, const char* confirmMsg, const char* errMsgOnFailure)
1774{
1775 if (confirmMsg && MessageBoxW(mPlugWnd, UTF8AsUTF16(confirmMsg).Get(), UTF8AsUTF16(msgWindowTitle).Get(), MB_YESNO) != IDYES)
1776 {
1777 return false;
1778 }
1779 DWORD inetStatus = 0;
1780 if (InternetGetConnectedState(&inetStatus, 0))
1781 {
1782 if (ShellExecuteW(mPlugWnd, L"open", UTF8AsUTF16(url).Get(), 0, 0, SW_SHOWNORMAL) > HINSTANCE(32))
1783 {
1784 return true;
1785 }
1786 }
1787 if (errMsgOnFailure)
1788 {
1789 MessageBoxW(mPlugWnd, UTF8AsUTF16(errMsgOnFailure).Get(), UTF8AsUTF16(msgWindowTitle).Get(), MB_OK);
1790 }
1791 return false;
1792}
1793
1794void IGraphicsWin::SetTooltip(const char* tooltip)
1795{
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);
1800}
1801
1802void IGraphicsWin::ShowTooltip()
1803{
1804 if (mTooltipIdx > -1)
1805 {
1806 if (auto* pTooltipControl = GetControl(mTooltipIdx))
1807 {
1808 const char* tooltipStr = pTooltipControl->GetTooltip();
1809 if (tooltipStr)
1810 {
1811 SetTooltip(tooltipStr);
1812 mShowingTooltip = true;
1813 }
1814 }
1815 }
1816}
1817
1818void IGraphicsWin::HideTooltip()
1819{
1820 if (mShowingTooltip)
1821 {
1822 SetTooltip(NULL);
1823 mShowingTooltip = false;
1824 }
1825}
1826
1827bool IGraphicsWin::GetTextFromClipboard(WDL_String& str)
1828{
1829 bool result = false;
1830
1831 if (IsClipboardFormatAvailable(CF_UNICODETEXT))
1832 {
1833 if (OpenClipboard(0))
1834 {
1835 HGLOBAL hglb = GetClipboardData(CF_UNICODETEXT);
1836
1837 if (hglb)
1838 {
1839 WCHAR *origStr = (WCHAR*) GlobalLock(hglb);
1840
1841 if (origStr)
1842 {
1843 UTF16ToUTF8(str, origStr);
1844 GlobalUnlock(hglb);
1845 result = true;
1846 }
1847 }
1848 }
1849
1850 CloseClipboard();
1851 }
1852
1853 if (!result)
1854 str.Set("");
1855
1856 return result;
1857}
1858
1859bool IGraphicsWin::SetTextInClipboard(const char* str)
1860{
1861 if (!OpenClipboard(mMainWnd))
1862 return false;
1863
1864 EmptyClipboard();
1865
1866 bool result = true;
1867
1868 if (strlen(str))
1869 {
1870 // figure out how many characters we need for the wide version of this string
1871 const int lenWide = UTF8ToUTF16Len(str);
1872
1873 // allocate global memory object for the text
1874 HGLOBAL hglbCopy = GlobalAlloc(GMEM_MOVEABLE, lenWide*sizeof(WCHAR));
1875 if (!hglbCopy)
1876 {
1877 CloseClipboard();
1878 return false;
1879 }
1880
1881 // lock the handle
1882 LPWSTR lpstrCopy = (LPWSTR) GlobalLock(hglbCopy);
1883
1884 if (lpstrCopy)
1885 {
1886 // copy the string into the buffer
1887 UTF8ToUTF16(lpstrCopy, str, lenWide);
1888 GlobalUnlock(hglbCopy);
1889
1890 // place the handle on the clipboard
1891 result = SetClipboardData(CF_UNICODETEXT, hglbCopy);
1892
1893 // free the handle if unsuccessful
1894 if (!result)
1895 GlobalFree(hglbCopy);
1896 }
1897 }
1898
1899 CloseClipboard();
1900
1901 return result;
1902}
1903
1904bool IGraphicsWin::SetFilePathInClipboard(const char* path)
1905{
1906 if (!OpenClipboard(mMainWnd))
1907 return false;
1908
1909 EmptyClipboard();
1910
1911 UTF8AsUTF16 pathWide(path);
1912
1913 // N.B. GHND ensures that the memory is zeroed
1914
1915 HGLOBAL hGlobal = GlobalAlloc(GHND, sizeof(DROPFILES) + (sizeof(wchar_t) * (pathWide.GetLength() + 1)));
1916
1917 if (!hGlobal)
1918 return false;
1919
1920 DROPFILES* pDropFiles = (DROPFILES*) GlobalLock(hGlobal);
1921 bool result = false;
1922
1923 if (pDropFiles)
1924 {
1925 // Populate the dropfile structure and copy the file path
1926
1927 pDropFiles->pFiles = sizeof(DROPFILES);
1928 pDropFiles->pt = { 0, 0 };
1929 pDropFiles->fNC = true;
1930 pDropFiles->fWide = true;
1931
1932 std::copy_n(pathWide.Get(), pathWide.GetLength(), reinterpret_cast<wchar_t*>(&pDropFiles[1]));
1933
1934 GlobalUnlock(hGlobal);
1935
1936 result = SetClipboardData(CF_HDROP, hGlobal);
1937 }
1938
1939 // free the handle if unsuccessful
1940 if (!result)
1941 GlobalFree(hGlobal);
1942
1943 CloseClipboard();
1944 return result;
1945}
1946
1947bool IGraphicsWin::InitiateExternalFileDragDrop(const char* path, const IRECT& /*iconBounds*/)
1948{
1949 using namespace DragAndDropHelpers;
1950 OleInitialize(nullptr);
1951
1952 FORMATETC format = { CF_HDROP, nullptr, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
1953
1954 DataObject* dataObj = new DataObject(&format, path);
1955 DropSource* dropSource = new DropSource();
1956
1957 DWORD dropEffect;
1958 HRESULT ret = DoDragDrop(dataObj, dropSource, DROPEFFECT_COPY, &dropEffect);
1959 bool success = SUCCEEDED(ret);
1960
1961 dataObj->Release();
1962 dropSource->Release();
1963
1964 OleUninitialize();
1965
1966 ReleaseMouseCapture();
1967
1968 return success;
1969}
1970
1971static HFONT GetHFont(const char* fontName, int weight, bool italic, bool underline, DWORD quality = DEFAULT_QUALITY, bool enumerate = false)
1972{
1973 HDC hdc = GetDC(NULL);
1974 HFONT font = nullptr;
1975 LOGFONTW lFont;
1976
1977 lFont.lfHeight = 0;
1978 lFont.lfWidth = 0;
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;
1990
1991 wcsncpy(lFont.lfFaceName, UTF8AsUTF16(fontName).Get(), LF_FACESIZE);
1992
1993 auto enumProc = [](const LOGFONTW* pLFont, const TEXTMETRICW* pTextMetric, DWORD FontType, LPARAM lParam)
1994 {
1995 return -1;
1996 };
1997
1998 if ((!enumerate || EnumFontFamiliesExW(hdc, &lFont, enumProc, NULL, 0) == -1))
1999 font = CreateFontIndirectW(&lFont);
2000
2001 if (font)
2002 {
2003 wchar_t selectedFontName[64] = {'\0'};
2004
2005 SelectFont(hdc, font);
2006 GetTextFaceW(hdc, 64, selectedFontName);
2007 if (strcmp(UTF16AsUTF8(selectedFontName).Get(), fontName))
2008 {
2009 DeleteObject(font);
2010 return nullptr;
2011 }
2012 }
2013
2014 ReleaseDC(NULL, hdc);
2015
2016 return font;
2017}
2018
2019PlatformFontPtr IGraphicsWin::LoadPlatformFont(const char* fontID, const char* fileNameOrResID)
2020{
2021 StaticStorage<InstalledFont>::Accessor fontStorage(sPlatformFontCache);
2022
2023 void* pFontMem = nullptr;
2024 int resSize = 0;
2025 WDL_String fullPath;
2026
2027 const EResourceLocation fontLocation = LocateResource(fileNameOrResID, "ttf", fullPath, GetBundleID(), GetWinModuleHandle(), nullptr);
2028
2029 if (fontLocation == kNotFound)
2030 return nullptr;
2031
2032 switch (fontLocation)
2033 {
2034 case kAbsolutePath:
2035 {
2036 HANDLE file = CreateFileW(UTF8AsUTF16(fullPath).Get(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
2037 PlatformFontPtr ret = nullptr;
2038 if (file)
2039 {
2040 HANDLE mapping = CreateFileMappingW(file, NULL, PAGE_READONLY, 0, 0, NULL);
2041 if (mapping)
2042 {
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);
2048 }
2049 CloseHandle(file);
2050 }
2051 return ret;
2052 }
2053 break;
2054 case kWinBinary:
2055 {
2056 pFontMem = const_cast<void *>(LoadWinResource(fullPath.Get(), "ttf", resSize, GetWinModuleHandle()));
2057 return LoadPlatformFont(fontID, pFontMem, resSize);
2058 }
2059 break;
2060 }
2061
2062 return nullptr;
2063}
2064
2065PlatformFontPtr IGraphicsWin::LoadPlatformFont(const char* fontID, const char* fontName, ETextStyle style)
2066{
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;
2071
2072 HFONT font = GetHFont(fontName, weight, italic, underline, quality, true);
2073
2074 return PlatformFontPtr(font ? new Font(font, TextStyleString(style), true) : nullptr);
2075}
2076
2077PlatformFontPtr IGraphicsWin::LoadPlatformFont(const char* fontID, void* pData, int dataSize)
2078{
2079 StaticStorage<InstalledFont>::Accessor fontStorage(sPlatformFontCache);
2080
2081 std::unique_ptr<InstalledFont> pFont;
2082 void* pFontMem = pData;
2083 int resSize = dataSize;
2084
2085 pFont = std::make_unique<InstalledFont>(pFontMem, resSize);
2086
2087 if (pFontMem && pFont && pFont->IsValid())
2088 {
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();
2094
2095 HFONT font = GetHFont(family.Get(), weight, italic, underline);
2096
2097 if (font)
2098 {
2099 fontStorage.Add(pFont.release(), fontID);
2100 return PlatformFontPtr(new Font(font, "", false));
2101 }
2102 }
2103
2104 return nullptr;
2105}
2106
2107void IGraphicsWin::CachePlatformFont(const char* fontID, const PlatformFontPtr& font)
2108{
2109 StaticStorage<HFontHolder>::Accessor hfontStorage(sHFontCache);
2110
2111 HFONT hfont = font->GetDescriptor();
2112
2113 if (!hfontStorage.Find(fontID))
2114 hfontStorage.Add(new HFontHolder(hfont), fontID);
2115}
2116
2117DWORD WINAPI VBlankRun(LPVOID lpParam)
2118{
2119 IGraphicsWin* pGraphics = (IGraphicsWin*) lpParam;
2120 return pGraphics->OnVBlankRun();
2121}
2122
2123void IGraphicsWin::StartVBlankThread(HWND hWnd)
2124{
2125 mVBlankWindow = hWnd;
2126 mVBlankShutdown = false;
2127 DWORD threadId = 0;
2128 mVBlankThread = ::CreateThread(NULL, 0, VBlankRun, this, 0, &threadId);
2129}
2130
2131void IGraphicsWin::StopVBlankThread()
2132{
2133 if (mVBlankThread != INVALID_HANDLE_VALUE)
2134 {
2135 mVBlankShutdown = true;
2136 ::WaitForSingleObject(mVBlankThread, 10000);
2137 mVBlankThread = INVALID_HANDLE_VALUE;
2138 mVBlankWindow = 0;
2139 }
2140}
2141
2142// Nasty kernel level definitions for wait for vblank. Including the
2143// proper include file requires "d3dkmthk.h" from the driver development
2144// kit. Instead we define the minimum needed to call the three methods we need.
2145// and use LoadLibrary/GetProcAddress to accomplish the same thing.
2146// See https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/d3dkmthk/
2147//
2148// Heres another link (rant) with a lot of good information about vsync on firefox
2149// https://www.vsynctester.com/firefoxisbroken.html
2150// https://bugs.chromium.org/p/chromium/issues/detail?id=467617
2151
2152// structs to use
2153typedef UINT32 D3DKMT_HANDLE;
2154typedef UINT D3DDDI_VIDEO_PRESENT_SOURCE_ID;
2155
2156typedef struct _D3DKMT_OPENADAPTERFROMHDC
2157{
2158 HDC hDc;
2159 D3DKMT_HANDLE hAdapter;
2160 LUID AdapterLuid;
2161 D3DDDI_VIDEO_PRESENT_SOURCE_ID VidPnSourceId;
2162} D3DKMT_OPENADAPTERFROMHDC;
2163
2164typedef struct _D3DKMT_CLOSEADAPTER
2165{
2166 D3DKMT_HANDLE hAdapter;
2167} D3DKMT_CLOSEADAPTER;
2168
2169typedef struct _D3DKMT_WAITFORVERTICALBLANKEVENT
2170{
2171 D3DKMT_HANDLE hAdapter;
2172 D3DKMT_HANDLE hDevice;
2173 D3DDDI_VIDEO_PRESENT_SOURCE_ID VidPnSourceId;
2174} D3DKMT_WAITFORVERTICALBLANKEVENT;
2175
2176// entry points
2177typedef NTSTATUS(WINAPI* D3DKMTOpenAdapterFromHdc)(D3DKMT_OPENADAPTERFROMHDC* Arg1);
2178typedef NTSTATUS(WINAPI* D3DKMTCloseAdapter)(const D3DKMT_CLOSEADAPTER* Arg1);
2179typedef NTSTATUS(WINAPI* D3DKMTWaitForVerticalBlankEvent)(const D3DKMT_WAITFORVERTICALBLANKEVENT* Arg1);
2180
2181DWORD IGraphicsWin::OnVBlankRun()
2182{
2183 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
2184
2185 // TODO: get expected vsync value. For now we will use a fallback
2186 // of 60Hz
2187 float rateFallback = 60.0f;
2188 int rateMS = (int)(1000.0f / rateFallback);
2189
2190 // We need to try to load the module and entry points to wait on v blank.
2191 // if anything fails, we try to gracefully fallback to sleeping for some
2192 // number of milliseconds.
2193 //
2194 // TODO: handle low power modes
2195
2196 D3DKMTOpenAdapterFromHdc pOpen = nullptr;
2197 D3DKMTCloseAdapter pClose = nullptr;
2198 D3DKMTWaitForVerticalBlankEvent pWait = nullptr;
2199 HINSTANCE hInst = LoadLibraryW(L"gdi32.dll");
2200
2201 if (hInst != nullptr)
2202 {
2203 pOpen = (D3DKMTOpenAdapterFromHdc) GetProcAddress((HMODULE) hInst, "D3DKMTOpenAdapterFromHdc");
2204 pClose = (D3DKMTCloseAdapter) GetProcAddress((HMODULE) hInst, "D3DKMTCloseAdapter");
2205 pWait = (D3DKMTWaitForVerticalBlankEvent) GetProcAddress((HMODULE) hInst, "D3DKMTWaitForVerticalBlankEvent");
2206 }
2207
2208 // if we don't get bindings to the methods we will fallback
2209 // to a crummy sleep loop for now. This is really just a last
2210 // resort and not expected on modern hardware and Windows OS
2211 // installs.
2212 if (!pOpen || !pClose || !pWait)
2213 {
2214 while (mVBlankShutdown == false)
2215 {
2216 Sleep(rateMS);
2217 VBlankNotify();
2218 }
2219 }
2220 else
2221 {
2222 // we have a good set of functions to call. We need to keep
2223 // track of the adapter and reask for it if the device is lost.
2224 bool adapterIsOpen = false;
2225 DWORD adapterLastFailTime = 0;
2226 _D3DKMT_WAITFORVERTICALBLANKEVENT we = { 0 };
2227
2228 while (mVBlankShutdown == false)
2229 {
2230 if (!adapterIsOpen)
2231 {
2232 // reacquire the adapter (at most once a second).
2233 if (adapterLastFailTime < ::GetTickCount() - 1000)
2234 {
2235 // try to get adapter
2236 D3DKMT_OPENADAPTERFROMHDC openAdapterData = { 0 };
2237 HDC hDC = GetDC(mVBlankWindow);
2238 openAdapterData.hDc = hDC;
2239 NTSTATUS status = (*pOpen)(&openAdapterData);
2240 if (status == S_OK)
2241 {
2242 // success, setup wait request parameters.
2243 adapterLastFailTime = 0;
2244 adapterIsOpen = true;
2245 we.hAdapter = openAdapterData.hAdapter;
2246 we.hDevice = 0;
2247 we.VidPnSourceId = openAdapterData.VidPnSourceId;
2248 }
2249 else
2250 {
2251 // failed
2252 adapterLastFailTime = ::GetTickCount();
2253 }
2254 DeleteDC(hDC);
2255 }
2256 }
2257
2258 if (adapterIsOpen)
2259 {
2260 // Finally we can wait on VBlank
2261 NTSTATUS status = (*pWait)(&we);
2262 if (status != S_OK)
2263 {
2264 // failed, close now and try again on the next pass.
2265 _D3DKMT_CLOSEADAPTER ca;
2266 ca.hAdapter = we.hAdapter;
2267 (*pClose)(&ca);
2268 adapterIsOpen = false;
2269 }
2270 }
2271
2272 // Temporary fallback for lost adapter or failed call.
2273 if (!adapterIsOpen)
2274 {
2275 ::Sleep(rateMS);
2276 }
2277
2278 // notify logic
2279 VBlankNotify();
2280 }
2281
2282 // cleanup adapter before leaving
2283 if (adapterIsOpen)
2284 {
2285 _D3DKMT_CLOSEADAPTER ca;
2286 ca.hAdapter = we.hAdapter;
2287 (*pClose)(&ca);
2288 adapterIsOpen = false;
2289 }
2290 }
2291
2292 // release module resource
2293 if (hInst != nullptr)
2294 {
2295 FreeLibrary((HMODULE)hInst);
2296 hInst = nullptr;
2297 }
2298
2299 return 0;
2300}
2301
2302void IGraphicsWin::VBlankNotify()
2303{
2304 mVBlankCount++;
2305 ::PostMessageW(mVBlankWindow, WM_VBLANK, mVBlankCount, 0);
2306}
2307
2308#ifndef NO_IGRAPHICS
2309#if defined IGRAPHICS_SKIA
2310 #include "IGraphicsSkia.cpp"
2311 #ifdef IGRAPHICS_GL
2312 #include "glad.c"
2313 #endif
2314#elif defined IGRAPHICS_NANOVG
2315 #include "IGraphicsNanoVG.cpp"
2316#ifdef IGRAPHICS_FREETYPE
2317#define FONS_USE_FREETYPE
2318 #pragma comment(lib, "freetype.lib")
2319#endif
2320 #include "nanovg.c"
2321 #include "glad.c"
2322#else
2323 #error
2324#endif
2325#endif
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.
Definition: IGraphics.h:87
virtual ECursor SetMouseCursor(ECursor cursorType=ECursor::ARROW)
Sets the mouse cursor to one of ECursor (implementations should return the result of the base impleme...
Definition: IGraphics.h:829
IGraphics platform class for Windows.
Definition: IGraphicsWin.h:26
EParamType Type() const
Get the parameter's type.
A class to specify an item of a pop up menu.
A class for setting the contents of a pop up menu.
Used to manage a list of rectangular areas and optimize them for drawing to the screen.
int Size() const
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...
Definition: IPlugStructs.h:615
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.
float W() const
void Scale(float scale)
Multiply each field of this IRECT by scale.
float H() const
IText is used to manage font and text/text entry style for a piece of text on the UI,...