The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

5654 lines
201KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 7 End-User License
  8. Agreement and JUCE Privacy Policy.
  9. End User License Agreement: www.juce.com/juce-7-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  19. #include <juce_audio_plugin_client/AAX/juce_AAX_Modifier_Injector.h>
  20. #endif
  21. namespace juce
  22. {
  23. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wcast-function-type")
  24. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  25. // these are in the windows SDK, but need to be repeated here for GCC..
  26. #ifndef GET_APPCOMMAND_LPARAM
  27. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  28. #define FAPPCOMMAND_MASK 0xF000
  29. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  30. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  31. #define APPCOMMAND_MEDIA_STOP 13
  32. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  33. #endif
  34. #ifndef WM_APPCOMMAND
  35. #define WM_APPCOMMAND 0x0319
  36. #endif
  37. void juce_repeatLastProcessPriority();
  38. bool juce_isRunningInWine();
  39. using CheckEventBlockedByModalComps = bool (*) (const MSG&);
  40. extern CheckEventBlockedByModalComps isEventBlockedByModalComps;
  41. static bool shouldDeactivateTitleBar = true;
  42. void* getUser32Function (const char*);
  43. #if JUCE_DEBUG
  44. int numActiveScopedDpiAwarenessDisablers = 0;
  45. static bool isInScopedDPIAwarenessDisabler() { return numActiveScopedDpiAwarenessDisablers > 0; }
  46. extern HWND juce_messageWindowHandle;
  47. #endif
  48. struct ScopedDeviceContext
  49. {
  50. explicit ScopedDeviceContext (HWND h)
  51. : hwnd (h), dc (GetDC (hwnd))
  52. {
  53. }
  54. ~ScopedDeviceContext()
  55. {
  56. ReleaseDC (hwnd, dc);
  57. }
  58. HWND hwnd;
  59. HDC dc;
  60. JUCE_DECLARE_NON_COPYABLE (ScopedDeviceContext)
  61. JUCE_DECLARE_NON_MOVEABLE (ScopedDeviceContext)
  62. };
  63. //==============================================================================
  64. #ifndef WM_TOUCH
  65. enum
  66. {
  67. WM_TOUCH = 0x0240,
  68. TOUCHEVENTF_MOVE = 0x0001,
  69. TOUCHEVENTF_DOWN = 0x0002,
  70. TOUCHEVENTF_UP = 0x0004
  71. };
  72. typedef HANDLE HTOUCHINPUT;
  73. typedef HANDLE HGESTUREINFO;
  74. struct TOUCHINPUT
  75. {
  76. LONG x;
  77. LONG y;
  78. HANDLE hSource;
  79. DWORD dwID;
  80. DWORD dwFlags;
  81. DWORD dwMask;
  82. DWORD dwTime;
  83. ULONG_PTR dwExtraInfo;
  84. DWORD cxContact;
  85. DWORD cyContact;
  86. };
  87. struct GESTUREINFO
  88. {
  89. UINT cbSize;
  90. DWORD dwFlags;
  91. DWORD dwID;
  92. HWND hwndTarget;
  93. POINTS ptsLocation;
  94. DWORD dwInstanceID;
  95. DWORD dwSequenceID;
  96. ULONGLONG ullArguments;
  97. UINT cbExtraArgs;
  98. };
  99. #endif
  100. #ifndef WM_NCPOINTERUPDATE
  101. enum
  102. {
  103. WM_NCPOINTERUPDATE = 0x241,
  104. WM_NCPOINTERDOWN = 0x242,
  105. WM_NCPOINTERUP = 0x243,
  106. WM_POINTERUPDATE = 0x245,
  107. WM_POINTERDOWN = 0x246,
  108. WM_POINTERUP = 0x247,
  109. WM_POINTERENTER = 0x249,
  110. WM_POINTERLEAVE = 0x24A,
  111. WM_POINTERACTIVATE = 0x24B,
  112. WM_POINTERCAPTURECHANGED = 0x24C,
  113. WM_TOUCHHITTESTING = 0x24D,
  114. WM_POINTERWHEEL = 0x24E,
  115. WM_POINTERHWHEEL = 0x24F,
  116. WM_POINTERHITTEST = 0x250
  117. };
  118. enum
  119. {
  120. PT_TOUCH = 0x00000002,
  121. PT_PEN = 0x00000003
  122. };
  123. enum POINTER_BUTTON_CHANGE_TYPE
  124. {
  125. POINTER_CHANGE_NONE,
  126. POINTER_CHANGE_FIRSTBUTTON_DOWN,
  127. POINTER_CHANGE_FIRSTBUTTON_UP,
  128. POINTER_CHANGE_SECONDBUTTON_DOWN,
  129. POINTER_CHANGE_SECONDBUTTON_UP,
  130. POINTER_CHANGE_THIRDBUTTON_DOWN,
  131. POINTER_CHANGE_THIRDBUTTON_UP,
  132. POINTER_CHANGE_FOURTHBUTTON_DOWN,
  133. POINTER_CHANGE_FOURTHBUTTON_UP,
  134. POINTER_CHANGE_FIFTHBUTTON_DOWN,
  135. POINTER_CHANGE_FIFTHBUTTON_UP
  136. };
  137. enum
  138. {
  139. PEN_MASK_NONE = 0x00000000,
  140. PEN_MASK_PRESSURE = 0x00000001,
  141. PEN_MASK_ROTATION = 0x00000002,
  142. PEN_MASK_TILT_X = 0x00000004,
  143. PEN_MASK_TILT_Y = 0x00000008
  144. };
  145. enum
  146. {
  147. TOUCH_MASK_NONE = 0x00000000,
  148. TOUCH_MASK_CONTACTAREA = 0x00000001,
  149. TOUCH_MASK_ORIENTATION = 0x00000002,
  150. TOUCH_MASK_PRESSURE = 0x00000004
  151. };
  152. enum
  153. {
  154. POINTER_FLAG_NONE = 0x00000000,
  155. POINTER_FLAG_NEW = 0x00000001,
  156. POINTER_FLAG_INRANGE = 0x00000002,
  157. POINTER_FLAG_INCONTACT = 0x00000004,
  158. POINTER_FLAG_FIRSTBUTTON = 0x00000010,
  159. POINTER_FLAG_SECONDBUTTON = 0x00000020,
  160. POINTER_FLAG_THIRDBUTTON = 0x00000040,
  161. POINTER_FLAG_FOURTHBUTTON = 0x00000080,
  162. POINTER_FLAG_FIFTHBUTTON = 0x00000100,
  163. POINTER_FLAG_PRIMARY = 0x00002000,
  164. POINTER_FLAG_CONFIDENCE = 0x00004000,
  165. POINTER_FLAG_CANCELED = 0x00008000,
  166. POINTER_FLAG_DOWN = 0x00010000,
  167. POINTER_FLAG_UPDATE = 0x00020000,
  168. POINTER_FLAG_UP = 0x00040000,
  169. POINTER_FLAG_WHEEL = 0x00080000,
  170. POINTER_FLAG_HWHEEL = 0x00100000,
  171. POINTER_FLAG_CAPTURECHANGED = 0x00200000,
  172. POINTER_FLAG_HASTRANSFORM = 0x00400000
  173. };
  174. typedef DWORD POINTER_INPUT_TYPE;
  175. typedef UINT32 POINTER_FLAGS;
  176. typedef UINT32 PEN_FLAGS;
  177. typedef UINT32 PEN_MASK;
  178. typedef UINT32 TOUCH_FLAGS;
  179. typedef UINT32 TOUCH_MASK;
  180. struct POINTER_INFO
  181. {
  182. POINTER_INPUT_TYPE pointerType;
  183. UINT32 pointerId;
  184. UINT32 frameId;
  185. POINTER_FLAGS pointerFlags;
  186. HANDLE sourceDevice;
  187. HWND hwndTarget;
  188. POINT ptPixelLocation;
  189. POINT ptHimetricLocation;
  190. POINT ptPixelLocationRaw;
  191. POINT ptHimetricLocationRaw;
  192. DWORD dwTime;
  193. UINT32 historyCount;
  194. INT32 InputData;
  195. DWORD dwKeyStates;
  196. UINT64 PerformanceCount;
  197. POINTER_BUTTON_CHANGE_TYPE ButtonChangeType;
  198. };
  199. struct POINTER_TOUCH_INFO
  200. {
  201. POINTER_INFO pointerInfo;
  202. TOUCH_FLAGS touchFlags;
  203. TOUCH_MASK touchMask;
  204. RECT rcContact;
  205. RECT rcContactRaw;
  206. UINT32 orientation;
  207. UINT32 pressure;
  208. };
  209. struct POINTER_PEN_INFO
  210. {
  211. POINTER_INFO pointerInfo;
  212. PEN_FLAGS penFlags;
  213. PEN_MASK penMask;
  214. UINT32 pressure;
  215. UINT32 rotation;
  216. INT32 tiltX;
  217. INT32 tiltY;
  218. };
  219. #define GET_POINTERID_WPARAM(wParam) (LOWORD(wParam))
  220. #endif
  221. #ifndef MONITOR_DPI_TYPE
  222. enum Monitor_DPI_Type
  223. {
  224. MDT_Effective_DPI = 0,
  225. MDT_Angular_DPI = 1,
  226. MDT_Raw_DPI = 2,
  227. MDT_Default = MDT_Effective_DPI
  228. };
  229. #endif
  230. #ifndef DPI_AWARENESS
  231. enum DPI_Awareness
  232. {
  233. DPI_Awareness_Invalid = -1,
  234. DPI_Awareness_Unaware = 0,
  235. DPI_Awareness_System_Aware = 1,
  236. DPI_Awareness_Per_Monitor_Aware = 2
  237. };
  238. #endif
  239. #ifndef USER_DEFAULT_SCREEN_DPI
  240. #define USER_DEFAULT_SCREEN_DPI 96
  241. #endif
  242. #ifndef _DPI_AWARENESS_CONTEXTS_
  243. typedef HANDLE DPI_AWARENESS_CONTEXT;
  244. #define DPI_AWARENESS_CONTEXT_UNAWARE ((DPI_AWARENESS_CONTEXT) - 1)
  245. #define DPI_AWARENESS_CONTEXT_SYSTEM_AWARE ((DPI_AWARENESS_CONTEXT) - 2)
  246. #define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE ((DPI_AWARENESS_CONTEXT) - 3)
  247. #define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 ((DPI_AWARENESS_CONTEXT) - 4)
  248. #endif
  249. // Some versions of the Windows 10 SDK define _DPI_AWARENESS_CONTEXTS_ but not
  250. // DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2
  251. #ifndef DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2
  252. #define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 ((DPI_AWARENESS_CONTEXT) - 4)
  253. #endif
  254. //==============================================================================
  255. using RegisterTouchWindowFunc = BOOL (WINAPI*) (HWND, ULONG);
  256. using GetTouchInputInfoFunc = BOOL (WINAPI*) (HTOUCHINPUT, UINT, TOUCHINPUT*, int);
  257. using CloseTouchInputHandleFunc = BOOL (WINAPI*) (HTOUCHINPUT);
  258. using GetGestureInfoFunc = BOOL (WINAPI*) (HGESTUREINFO, GESTUREINFO*);
  259. static RegisterTouchWindowFunc registerTouchWindow = nullptr;
  260. static GetTouchInputInfoFunc getTouchInputInfo = nullptr;
  261. static CloseTouchInputHandleFunc closeTouchInputHandle = nullptr;
  262. static GetGestureInfoFunc getGestureInfo = nullptr;
  263. static bool hasCheckedForMultiTouch = false;
  264. static bool canUseMultiTouch()
  265. {
  266. if (registerTouchWindow == nullptr && ! hasCheckedForMultiTouch)
  267. {
  268. hasCheckedForMultiTouch = true;
  269. registerTouchWindow = (RegisterTouchWindowFunc) getUser32Function ("RegisterTouchWindow");
  270. getTouchInputInfo = (GetTouchInputInfoFunc) getUser32Function ("GetTouchInputInfo");
  271. closeTouchInputHandle = (CloseTouchInputHandleFunc) getUser32Function ("CloseTouchInputHandle");
  272. getGestureInfo = (GetGestureInfoFunc) getUser32Function ("GetGestureInfo");
  273. }
  274. return registerTouchWindow != nullptr;
  275. }
  276. //==============================================================================
  277. using GetPointerTypeFunc = BOOL (WINAPI*) (UINT32, POINTER_INPUT_TYPE*);
  278. using GetPointerTouchInfoFunc = BOOL (WINAPI*) (UINT32, POINTER_TOUCH_INFO*);
  279. using GetPointerPenInfoFunc = BOOL (WINAPI*) (UINT32, POINTER_PEN_INFO*);
  280. static GetPointerTypeFunc getPointerTypeFunction = nullptr;
  281. static GetPointerTouchInfoFunc getPointerTouchInfo = nullptr;
  282. static GetPointerPenInfoFunc getPointerPenInfo = nullptr;
  283. static bool canUsePointerAPI = false;
  284. static void checkForPointerAPI()
  285. {
  286. getPointerTypeFunction = (GetPointerTypeFunc) getUser32Function ("GetPointerType");
  287. getPointerTouchInfo = (GetPointerTouchInfoFunc) getUser32Function ("GetPointerTouchInfo");
  288. getPointerPenInfo = (GetPointerPenInfoFunc) getUser32Function ("GetPointerPenInfo");
  289. canUsePointerAPI = (getPointerTypeFunction != nullptr
  290. && getPointerTouchInfo != nullptr
  291. && getPointerPenInfo != nullptr);
  292. }
  293. //==============================================================================
  294. using SetProcessDPIAwareFunc = BOOL (WINAPI*) ();
  295. using SetProcessDPIAwarenessContextFunc = BOOL (WINAPI*) (DPI_AWARENESS_CONTEXT);
  296. using SetProcessDPIAwarenessFunc = HRESULT (WINAPI*) (DPI_Awareness);
  297. using SetThreadDPIAwarenessContextFunc = DPI_AWARENESS_CONTEXT (WINAPI*) (DPI_AWARENESS_CONTEXT);
  298. using GetDPIForWindowFunc = UINT (WINAPI*) (HWND);
  299. using GetDPIForMonitorFunc = HRESULT (WINAPI*) (HMONITOR, Monitor_DPI_Type, UINT*, UINT*);
  300. using GetSystemMetricsForDpiFunc = int (WINAPI*) (int, UINT);
  301. using GetProcessDPIAwarenessFunc = HRESULT (WINAPI*) (HANDLE, DPI_Awareness*);
  302. using GetWindowDPIAwarenessContextFunc = DPI_AWARENESS_CONTEXT (WINAPI*) (HWND);
  303. using GetThreadDPIAwarenessContextFunc = DPI_AWARENESS_CONTEXT (WINAPI*) ();
  304. using GetAwarenessFromDpiAwarenessContextFunc = DPI_Awareness (WINAPI*) (DPI_AWARENESS_CONTEXT);
  305. using EnableNonClientDPIScalingFunc = BOOL (WINAPI*) (HWND);
  306. static SetProcessDPIAwareFunc setProcessDPIAware = nullptr;
  307. static SetProcessDPIAwarenessContextFunc setProcessDPIAwarenessContext = nullptr;
  308. static SetProcessDPIAwarenessFunc setProcessDPIAwareness = nullptr;
  309. static SetThreadDPIAwarenessContextFunc setThreadDPIAwarenessContext = nullptr;
  310. static GetDPIForMonitorFunc getDPIForMonitor = nullptr;
  311. static GetDPIForWindowFunc getDPIForWindow = nullptr;
  312. static GetProcessDPIAwarenessFunc getProcessDPIAwareness = nullptr;
  313. static GetWindowDPIAwarenessContextFunc getWindowDPIAwarenessContext = nullptr;
  314. static GetThreadDPIAwarenessContextFunc getThreadDPIAwarenessContext = nullptr;
  315. static GetAwarenessFromDpiAwarenessContextFunc getAwarenessFromDPIAwarenessContext = nullptr;
  316. static EnableNonClientDPIScalingFunc enableNonClientDPIScaling = nullptr;
  317. static bool hasCheckedForDPIAwareness = false;
  318. static void loadDPIAwarenessFunctions()
  319. {
  320. setProcessDPIAware = (SetProcessDPIAwareFunc) getUser32Function ("SetProcessDPIAware");
  321. constexpr auto shcore = "SHCore.dll";
  322. LoadLibraryA (shcore);
  323. const auto shcoreModule = GetModuleHandleA (shcore);
  324. if (shcoreModule == nullptr)
  325. return;
  326. getDPIForMonitor = (GetDPIForMonitorFunc) GetProcAddress (shcoreModule, "GetDpiForMonitor");
  327. setProcessDPIAwareness = (SetProcessDPIAwarenessFunc) GetProcAddress (shcoreModule, "SetProcessDpiAwareness");
  328. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  329. getDPIForWindow = (GetDPIForWindowFunc) getUser32Function ("GetDpiForWindow");
  330. getProcessDPIAwareness = (GetProcessDPIAwarenessFunc) GetProcAddress (shcoreModule, "GetProcessDpiAwareness");
  331. getWindowDPIAwarenessContext = (GetWindowDPIAwarenessContextFunc) getUser32Function ("GetWindowDpiAwarenessContext");
  332. setThreadDPIAwarenessContext = (SetThreadDPIAwarenessContextFunc) getUser32Function ("SetThreadDpiAwarenessContext");
  333. getThreadDPIAwarenessContext = (GetThreadDPIAwarenessContextFunc) getUser32Function ("GetThreadDpiAwarenessContext");
  334. getAwarenessFromDPIAwarenessContext = (GetAwarenessFromDpiAwarenessContextFunc) getUser32Function ("GetAwarenessFromDpiAwarenessContext");
  335. setProcessDPIAwarenessContext = (SetProcessDPIAwarenessContextFunc) getUser32Function ("SetProcessDpiAwarenessContext");
  336. enableNonClientDPIScaling = (EnableNonClientDPIScalingFunc) getUser32Function ("EnableNonClientDpiScaling");
  337. #endif
  338. }
  339. static void setDPIAwareness()
  340. {
  341. if (hasCheckedForDPIAwareness)
  342. return;
  343. hasCheckedForDPIAwareness = true;
  344. if (! JUCEApplicationBase::isStandaloneApp())
  345. return;
  346. loadDPIAwarenessFunctions();
  347. if (setProcessDPIAwarenessContext != nullptr
  348. && setProcessDPIAwarenessContext (DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2))
  349. return;
  350. if (setProcessDPIAwareness != nullptr && enableNonClientDPIScaling != nullptr
  351. && SUCCEEDED (setProcessDPIAwareness (DPI_Awareness::DPI_Awareness_Per_Monitor_Aware)))
  352. return;
  353. if (setProcessDPIAwareness != nullptr && getDPIForMonitor != nullptr
  354. && SUCCEEDED (setProcessDPIAwareness (DPI_Awareness::DPI_Awareness_System_Aware)))
  355. return;
  356. if (setProcessDPIAware != nullptr)
  357. setProcessDPIAware();
  358. }
  359. static bool isPerMonitorDPIAwareProcess()
  360. {
  361. #if ! JUCE_WIN_PER_MONITOR_DPI_AWARE
  362. return false;
  363. #else
  364. static bool dpiAware = []() -> bool
  365. {
  366. setDPIAwareness();
  367. if (! JUCEApplication::isStandaloneApp())
  368. return false;
  369. if (getProcessDPIAwareness == nullptr)
  370. return false;
  371. DPI_Awareness context;
  372. getProcessDPIAwareness (nullptr, &context);
  373. return context == DPI_Awareness::DPI_Awareness_Per_Monitor_Aware;
  374. }();
  375. return dpiAware;
  376. #endif
  377. }
  378. static bool isPerMonitorDPIAwareWindow ([[maybe_unused]] HWND nativeWindow)
  379. {
  380. #if ! JUCE_WIN_PER_MONITOR_DPI_AWARE
  381. return false;
  382. #else
  383. setDPIAwareness();
  384. if (getWindowDPIAwarenessContext != nullptr
  385. && getAwarenessFromDPIAwarenessContext != nullptr)
  386. {
  387. return (getAwarenessFromDPIAwarenessContext (getWindowDPIAwarenessContext (nativeWindow))
  388. == DPI_Awareness::DPI_Awareness_Per_Monitor_Aware);
  389. }
  390. return isPerMonitorDPIAwareProcess();
  391. #endif
  392. }
  393. static bool isPerMonitorDPIAwareThread (GetThreadDPIAwarenessContextFunc getThreadDPIAwarenessContextIn = getThreadDPIAwarenessContext,
  394. GetAwarenessFromDpiAwarenessContextFunc getAwarenessFromDPIAwarenessContextIn = getAwarenessFromDPIAwarenessContext)
  395. {
  396. #if ! JUCE_WIN_PER_MONITOR_DPI_AWARE
  397. return false;
  398. #else
  399. setDPIAwareness();
  400. if (getThreadDPIAwarenessContextIn != nullptr
  401. && getAwarenessFromDPIAwarenessContextIn != nullptr)
  402. {
  403. return (getAwarenessFromDPIAwarenessContextIn (getThreadDPIAwarenessContextIn())
  404. == DPI_Awareness::DPI_Awareness_Per_Monitor_Aware);
  405. }
  406. return isPerMonitorDPIAwareProcess();
  407. #endif
  408. }
  409. static double getGlobalDPI()
  410. {
  411. setDPIAwareness();
  412. ScopedDeviceContext deviceContext { nullptr };
  413. return (GetDeviceCaps (deviceContext.dc, LOGPIXELSX) + GetDeviceCaps (deviceContext.dc, LOGPIXELSY)) / 2.0;
  414. }
  415. //==============================================================================
  416. class ScopedSuspendResumeNotificationRegistration
  417. {
  418. public:
  419. ScopedSuspendResumeNotificationRegistration() = default;
  420. explicit ScopedSuspendResumeNotificationRegistration (HWND window)
  421. : handle (SystemStats::getOperatingSystemType() >= SystemStats::Windows8_0
  422. ? RegisterSuspendResumeNotification (window, DEVICE_NOTIFY_WINDOW_HANDLE)
  423. : nullptr)
  424. {}
  425. private:
  426. struct Destructor
  427. {
  428. void operator() (HPOWERNOTIFY ptr) const
  429. {
  430. if (ptr != nullptr)
  431. UnregisterSuspendResumeNotification (ptr);
  432. }
  433. };
  434. std::unique_ptr<std::remove_pointer_t<HPOWERNOTIFY>, Destructor> handle;
  435. };
  436. //==============================================================================
  437. class ScopedThreadDPIAwarenessSetter::NativeImpl
  438. {
  439. public:
  440. explicit NativeImpl (HWND nativeWindow [[maybe_unused]])
  441. {
  442. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  443. if (auto* functionSingleton = FunctionSingleton::getInstance())
  444. {
  445. if (! functionSingleton->isLoaded())
  446. return;
  447. auto dpiAwareWindow = (functionSingleton->getAwarenessFromContext (functionSingleton->getWindowAwareness (nativeWindow))
  448. == DPI_Awareness::DPI_Awareness_Per_Monitor_Aware);
  449. auto dpiAwareThread = (functionSingleton->getAwarenessFromContext (functionSingleton->getThreadAwareness())
  450. == DPI_Awareness::DPI_Awareness_Per_Monitor_Aware);
  451. if (dpiAwareWindow && ! dpiAwareThread)
  452. oldContext = functionSingleton->setThreadAwareness (DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE);
  453. else if (! dpiAwareWindow && dpiAwareThread)
  454. oldContext = functionSingleton->setThreadAwareness (DPI_AWARENESS_CONTEXT_UNAWARE);
  455. }
  456. #endif
  457. }
  458. ~NativeImpl()
  459. {
  460. if (oldContext != nullptr)
  461. if (auto* functionSingleton = FunctionSingleton::getInstance())
  462. functionSingleton->setThreadAwareness (oldContext);
  463. }
  464. private:
  465. struct FunctionSingleton : public DeletedAtShutdown
  466. {
  467. FunctionSingleton() = default;
  468. ~FunctionSingleton() override { clearSingletonInstance(); }
  469. SetThreadDPIAwarenessContextFunc setThreadAwareness = (SetThreadDPIAwarenessContextFunc) getUser32Function ("SetThreadDpiAwarenessContext");
  470. GetWindowDPIAwarenessContextFunc getWindowAwareness = (GetWindowDPIAwarenessContextFunc) getUser32Function ("GetWindowDpiAwarenessContext");
  471. GetThreadDPIAwarenessContextFunc getThreadAwareness = (GetThreadDPIAwarenessContextFunc) getUser32Function ("GetThreadDpiAwarenessContext");
  472. GetAwarenessFromDpiAwarenessContextFunc getAwarenessFromContext = (GetAwarenessFromDpiAwarenessContextFunc) getUser32Function ("GetAwarenessFromDpiAwarenessContext");
  473. bool isLoaded() const noexcept
  474. {
  475. return setThreadAwareness != nullptr
  476. && getWindowAwareness != nullptr
  477. && getThreadAwareness != nullptr
  478. && getAwarenessFromContext != nullptr;
  479. }
  480. JUCE_DECLARE_SINGLETON_SINGLETHREADED_MINIMAL (FunctionSingleton)
  481. JUCE_DECLARE_NON_COPYABLE (FunctionSingleton)
  482. JUCE_DECLARE_NON_MOVEABLE (FunctionSingleton)
  483. };
  484. DPI_AWARENESS_CONTEXT oldContext = nullptr;
  485. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NativeImpl)
  486. JUCE_DECLARE_NON_MOVEABLE (NativeImpl)
  487. };
  488. JUCE_IMPLEMENT_SINGLETON (ScopedThreadDPIAwarenessSetter::NativeImpl::FunctionSingleton)
  489. ScopedThreadDPIAwarenessSetter::ScopedThreadDPIAwarenessSetter (void* nativeWindow)
  490. {
  491. pimpl = std::make_unique<NativeImpl> ((HWND) nativeWindow);
  492. }
  493. ScopedThreadDPIAwarenessSetter::~ScopedThreadDPIAwarenessSetter() = default;
  494. ScopedDPIAwarenessDisabler::ScopedDPIAwarenessDisabler()
  495. {
  496. static auto localGetThreadDpiAwarenessContext = (GetThreadDPIAwarenessContextFunc) getUser32Function ("GetThreadDpiAwarenessContext");
  497. static auto localGetAwarenessFromDpiAwarenessContextFunc = (GetAwarenessFromDpiAwarenessContextFunc) getUser32Function ("GetAwarenessFromDpiAwarenessContext");
  498. if (! isPerMonitorDPIAwareThread (localGetThreadDpiAwarenessContext, localGetAwarenessFromDpiAwarenessContextFunc))
  499. return;
  500. static auto localSetThreadDPIAwarenessContext = (SetThreadDPIAwarenessContextFunc) getUser32Function ("SetThreadDpiAwarenessContext");
  501. if (localSetThreadDPIAwarenessContext != nullptr)
  502. {
  503. previousContext = localSetThreadDPIAwarenessContext (DPI_AWARENESS_CONTEXT_UNAWARE);
  504. #if JUCE_DEBUG
  505. ++numActiveScopedDpiAwarenessDisablers;
  506. #endif
  507. }
  508. }
  509. ScopedDPIAwarenessDisabler::~ScopedDPIAwarenessDisabler()
  510. {
  511. if (previousContext != nullptr)
  512. {
  513. static auto localSetThreadDPIAwarenessContext = (SetThreadDPIAwarenessContextFunc) getUser32Function ("SetThreadDpiAwarenessContext");
  514. if (localSetThreadDPIAwarenessContext != nullptr)
  515. localSetThreadDPIAwarenessContext ((DPI_AWARENESS_CONTEXT) previousContext);
  516. #if JUCE_DEBUG
  517. --numActiveScopedDpiAwarenessDisablers;
  518. #endif
  519. }
  520. }
  521. //==============================================================================
  522. using SettingChangeCallbackFunc = void (*)(void);
  523. extern SettingChangeCallbackFunc settingChangeCallback;
  524. //==============================================================================
  525. static Rectangle<int> rectangleFromRECT (RECT r) noexcept { return { r.left, r.top, r.right - r.left, r.bottom - r.top }; }
  526. static RECT RECTFromRectangle (Rectangle<int> r) noexcept { return { r.getX(), r.getY(), r.getRight(), r.getBottom() }; }
  527. static Point<int> pointFromPOINT (POINT p) noexcept { return { p.x, p.y }; }
  528. static POINT POINTFromPoint (Point<int> p) noexcept { return { p.x, p.y }; }
  529. //==============================================================================
  530. static const Displays::Display* getCurrentDisplayFromScaleFactor (HWND hwnd);
  531. template <typename ValueType>
  532. static Rectangle<ValueType> convertPhysicalScreenRectangleToLogical (Rectangle<ValueType> r, HWND h) noexcept
  533. {
  534. if (isPerMonitorDPIAwareWindow (h))
  535. return Desktop::getInstance().getDisplays().physicalToLogical (r, getCurrentDisplayFromScaleFactor (h));
  536. return r;
  537. }
  538. template <typename ValueType>
  539. static Rectangle<ValueType> convertLogicalScreenRectangleToPhysical (Rectangle<ValueType> r, HWND h) noexcept
  540. {
  541. if (isPerMonitorDPIAwareWindow (h))
  542. return Desktop::getInstance().getDisplays().logicalToPhysical (r, getCurrentDisplayFromScaleFactor (h));
  543. return r;
  544. }
  545. static Point<int> convertPhysicalScreenPointToLogical (Point<int> p, HWND h) noexcept
  546. {
  547. if (isPerMonitorDPIAwareWindow (h))
  548. return Desktop::getInstance().getDisplays().physicalToLogical (p, getCurrentDisplayFromScaleFactor (h));
  549. return p;
  550. }
  551. static Point<int> convertLogicalScreenPointToPhysical (Point<int> p, HWND h) noexcept
  552. {
  553. if (isPerMonitorDPIAwareWindow (h))
  554. return Desktop::getInstance().getDisplays().logicalToPhysical (p, getCurrentDisplayFromScaleFactor (h));
  555. return p;
  556. }
  557. JUCE_API double getScaleFactorForWindow (HWND h);
  558. JUCE_API double getScaleFactorForWindow (HWND h)
  559. {
  560. // NB. Using a local function here because we need to call this method from the plug-in wrappers
  561. // which don't load the DPI-awareness functions on startup
  562. static GetDPIForWindowFunc localGetDPIForWindow = nullptr;
  563. static bool hasChecked = false;
  564. if (! hasChecked)
  565. {
  566. hasChecked = true;
  567. if (localGetDPIForWindow == nullptr)
  568. localGetDPIForWindow = (GetDPIForWindowFunc) getUser32Function ("GetDpiForWindow");
  569. }
  570. if (localGetDPIForWindow != nullptr)
  571. return (double) localGetDPIForWindow (h) / USER_DEFAULT_SCREEN_DPI;
  572. return 1.0;
  573. }
  574. //==============================================================================
  575. static void setWindowPos (HWND hwnd, Rectangle<int> bounds, UINT flags, bool adjustTopLeft = false)
  576. {
  577. ScopedThreadDPIAwarenessSetter setter { hwnd };
  578. if (isPerMonitorDPIAwareWindow (hwnd))
  579. {
  580. if (adjustTopLeft)
  581. bounds = convertLogicalScreenRectangleToPhysical (bounds, hwnd)
  582. .withPosition (Desktop::getInstance().getDisplays().logicalToPhysical (bounds.getTopLeft()));
  583. else
  584. bounds = convertLogicalScreenRectangleToPhysical (bounds, hwnd);
  585. }
  586. SetWindowPos (hwnd, nullptr, bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(), flags);
  587. }
  588. static RECT getWindowScreenRect (HWND hwnd)
  589. {
  590. ScopedThreadDPIAwarenessSetter setter { hwnd };
  591. RECT rect;
  592. GetWindowRect (hwnd, &rect);
  593. return rect;
  594. }
  595. static RECT getWindowClientRect (HWND hwnd)
  596. {
  597. auto rect = getWindowScreenRect (hwnd);
  598. if (auto parentH = GetParent (hwnd))
  599. {
  600. ScopedThreadDPIAwarenessSetter setter { hwnd };
  601. MapWindowPoints (HWND_DESKTOP, parentH, (LPPOINT) &rect, 2);
  602. }
  603. return rect;
  604. }
  605. static void setWindowZOrder (HWND hwnd, HWND insertAfter)
  606. {
  607. SetWindowPos (hwnd, insertAfter, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  608. }
  609. //==============================================================================
  610. #if ! JUCE_MINGW
  611. extern RTL_OSVERSIONINFOW getWindowsVersionInfo();
  612. #endif
  613. double Desktop::getDefaultMasterScale()
  614. {
  615. if (! JUCEApplicationBase::isStandaloneApp() || isPerMonitorDPIAwareProcess())
  616. return 1.0;
  617. return getGlobalDPI() / USER_DEFAULT_SCREEN_DPI;
  618. }
  619. bool Desktop::canUseSemiTransparentWindows() noexcept
  620. {
  621. return true;
  622. }
  623. class Desktop::NativeDarkModeChangeDetectorImpl
  624. {
  625. public:
  626. NativeDarkModeChangeDetectorImpl()
  627. {
  628. #if ! JUCE_MINGW
  629. const auto winVer = getWindowsVersionInfo();
  630. if (winVer.dwMajorVersion >= 10 && winVer.dwBuildNumber >= 17763)
  631. {
  632. const auto uxtheme = "uxtheme.dll";
  633. LoadLibraryA (uxtheme);
  634. const auto uxthemeModule = GetModuleHandleA (uxtheme);
  635. if (uxthemeModule != nullptr)
  636. {
  637. shouldAppsUseDarkMode = (ShouldAppsUseDarkModeFunc) GetProcAddress (uxthemeModule, MAKEINTRESOURCEA (132));
  638. if (shouldAppsUseDarkMode != nullptr)
  639. darkModeEnabled = shouldAppsUseDarkMode() && ! isHighContrast();
  640. }
  641. }
  642. #endif
  643. }
  644. ~NativeDarkModeChangeDetectorImpl()
  645. {
  646. UnhookWindowsHookEx (hook);
  647. }
  648. bool isDarkModeEnabled() const noexcept { return darkModeEnabled; }
  649. private:
  650. static bool isHighContrast()
  651. {
  652. HIGHCONTRASTW highContrast {};
  653. if (SystemParametersInfoW (SPI_GETHIGHCONTRAST, sizeof (highContrast), &highContrast, false))
  654. return highContrast.dwFlags & HCF_HIGHCONTRASTON;
  655. return false;
  656. }
  657. static LRESULT CALLBACK callWndProc (int nCode, WPARAM wParam, LPARAM lParam)
  658. {
  659. auto* params = reinterpret_cast<CWPSTRUCT*> (lParam);
  660. if (nCode >= 0
  661. && params != nullptr
  662. && params->message == WM_SETTINGCHANGE
  663. && params->lParam != 0
  664. && CompareStringOrdinal (reinterpret_cast<LPWCH> (params->lParam), -1, L"ImmersiveColorSet", -1, true) == CSTR_EQUAL)
  665. {
  666. Desktop::getInstance().nativeDarkModeChangeDetectorImpl->colourSetChanged();
  667. }
  668. return CallNextHookEx ({}, nCode, wParam, lParam);
  669. }
  670. void colourSetChanged()
  671. {
  672. if (shouldAppsUseDarkMode != nullptr)
  673. {
  674. const auto wasDarkModeEnabled = std::exchange (darkModeEnabled, shouldAppsUseDarkMode() && ! isHighContrast());
  675. if (darkModeEnabled != wasDarkModeEnabled)
  676. Desktop::getInstance().darkModeChanged();
  677. }
  678. }
  679. using ShouldAppsUseDarkModeFunc = bool (WINAPI*)();
  680. ShouldAppsUseDarkModeFunc shouldAppsUseDarkMode = nullptr;
  681. bool darkModeEnabled = false;
  682. HHOOK hook { SetWindowsHookEx (WH_CALLWNDPROC,
  683. callWndProc,
  684. (HINSTANCE) juce::Process::getCurrentModuleInstanceHandle(),
  685. GetCurrentThreadId()) };
  686. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NativeDarkModeChangeDetectorImpl)
  687. };
  688. std::unique_ptr<Desktop::NativeDarkModeChangeDetectorImpl> Desktop::createNativeDarkModeChangeDetectorImpl()
  689. {
  690. return std::make_unique<NativeDarkModeChangeDetectorImpl>();
  691. }
  692. bool Desktop::isDarkModeActive() const
  693. {
  694. return nativeDarkModeChangeDetectorImpl->isDarkModeEnabled();
  695. }
  696. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  697. {
  698. return upright;
  699. }
  700. int64 getMouseEventTime();
  701. int64 getMouseEventTime()
  702. {
  703. static int64 eventTimeOffset = 0;
  704. static LONG lastMessageTime = 0;
  705. const LONG thisMessageTime = GetMessageTime();
  706. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  707. {
  708. lastMessageTime = thisMessageTime;
  709. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  710. }
  711. return eventTimeOffset + thisMessageTime;
  712. }
  713. //==============================================================================
  714. const int extendedKeyModifier = 0x10000;
  715. const int KeyPress::spaceKey = VK_SPACE;
  716. const int KeyPress::returnKey = VK_RETURN;
  717. const int KeyPress::escapeKey = VK_ESCAPE;
  718. const int KeyPress::backspaceKey = VK_BACK;
  719. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  720. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  721. const int KeyPress::tabKey = VK_TAB;
  722. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  723. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  724. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  725. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  726. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  727. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  728. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  729. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  730. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  731. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  732. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  733. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  734. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  735. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  736. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  737. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  738. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  739. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  740. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  741. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  742. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  743. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  744. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  745. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  746. const int KeyPress::F17Key = VK_F17 | extendedKeyModifier;
  747. const int KeyPress::F18Key = VK_F18 | extendedKeyModifier;
  748. const int KeyPress::F19Key = VK_F19 | extendedKeyModifier;
  749. const int KeyPress::F20Key = VK_F20 | extendedKeyModifier;
  750. const int KeyPress::F21Key = VK_F21 | extendedKeyModifier;
  751. const int KeyPress::F22Key = VK_F22 | extendedKeyModifier;
  752. const int KeyPress::F23Key = VK_F23 | extendedKeyModifier;
  753. const int KeyPress::F24Key = VK_F24 | extendedKeyModifier;
  754. const int KeyPress::F25Key = 0x31000; // Windows doesn't support F-keys 25 or higher
  755. const int KeyPress::F26Key = 0x31001;
  756. const int KeyPress::F27Key = 0x31002;
  757. const int KeyPress::F28Key = 0x31003;
  758. const int KeyPress::F29Key = 0x31004;
  759. const int KeyPress::F30Key = 0x31005;
  760. const int KeyPress::F31Key = 0x31006;
  761. const int KeyPress::F32Key = 0x31007;
  762. const int KeyPress::F33Key = 0x31008;
  763. const int KeyPress::F34Key = 0x31009;
  764. const int KeyPress::F35Key = 0x3100a;
  765. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  766. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  767. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  768. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  769. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  770. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  771. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  772. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  773. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  774. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  775. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  776. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  777. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  778. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  779. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  780. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  781. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  782. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  783. const int KeyPress::playKey = 0x30000;
  784. const int KeyPress::stopKey = 0x30001;
  785. const int KeyPress::fastForwardKey = 0x30002;
  786. const int KeyPress::rewindKey = 0x30003;
  787. //==============================================================================
  788. class WindowsBitmapImage : public ImagePixelData
  789. {
  790. public:
  791. WindowsBitmapImage (const Image::PixelFormat format,
  792. const int w, const int h, const bool clearImage)
  793. : ImagePixelData (format, w, h)
  794. {
  795. jassert (format == Image::RGB || format == Image::ARGB);
  796. static bool alwaysUse32Bits = isGraphicsCard32Bit(); // NB: for 32-bit cards, it's faster to use a 32-bit image.
  797. pixelStride = (alwaysUse32Bits || format == Image::ARGB) ? 4 : 3;
  798. lineStride = -((w * pixelStride + 3) & ~3);
  799. zerostruct (bitmapInfo);
  800. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  801. bitmapInfo.bV4Width = w;
  802. bitmapInfo.bV4Height = h;
  803. bitmapInfo.bV4Planes = 1;
  804. bitmapInfo.bV4CSType = 1;
  805. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  806. if (format == Image::ARGB)
  807. {
  808. bitmapInfo.bV4AlphaMask = 0xff000000;
  809. bitmapInfo.bV4RedMask = 0xff0000;
  810. bitmapInfo.bV4GreenMask = 0xff00;
  811. bitmapInfo.bV4BlueMask = 0xff;
  812. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  813. }
  814. else
  815. {
  816. bitmapInfo.bV4V4Compression = BI_RGB;
  817. }
  818. {
  819. ScopedDeviceContext deviceContext { nullptr };
  820. hdc = CreateCompatibleDC (deviceContext.dc);
  821. }
  822. SetMapMode (hdc, MM_TEXT);
  823. hBitmap = CreateDIBSection (hdc, (BITMAPINFO*) &(bitmapInfo), DIB_RGB_COLORS,
  824. (void**) &bitmapData, nullptr, 0);
  825. if (hBitmap != nullptr)
  826. previousBitmap = SelectObject (hdc, hBitmap);
  827. if (format == Image::ARGB && clearImage)
  828. zeromem (bitmapData, (size_t) std::abs (h * lineStride));
  829. imageData = bitmapData - (lineStride * (h - 1));
  830. }
  831. ~WindowsBitmapImage() override
  832. {
  833. SelectObject (hdc, previousBitmap); // Selecting the previous bitmap before deleting the DC avoids a warning in BoundsChecker
  834. DeleteDC (hdc);
  835. DeleteObject (hBitmap);
  836. }
  837. std::unique_ptr<ImageType> createType() const override { return std::make_unique<NativeImageType>(); }
  838. std::unique_ptr<LowLevelGraphicsContext> createLowLevelContext() override
  839. {
  840. sendDataChangeMessage();
  841. return std::make_unique<LowLevelGraphicsSoftwareRenderer> (Image (this));
  842. }
  843. void initialiseBitmapData (Image::BitmapData& bitmap, int x, int y, Image::BitmapData::ReadWriteMode mode) override
  844. {
  845. const auto offset = (size_t) (x * pixelStride + y * lineStride);
  846. bitmap.data = imageData + offset;
  847. bitmap.size = (size_t) (lineStride * height) - offset;
  848. bitmap.pixelFormat = pixelFormat;
  849. bitmap.lineStride = lineStride;
  850. bitmap.pixelStride = pixelStride;
  851. if (mode != Image::BitmapData::readOnly)
  852. sendDataChangeMessage();
  853. }
  854. ImagePixelData::Ptr clone() override
  855. {
  856. auto im = new WindowsBitmapImage (pixelFormat, width, height, false);
  857. for (int i = 0; i < height; ++i)
  858. memcpy (im->imageData + i * lineStride, imageData + i * lineStride, (size_t) lineStride);
  859. return im;
  860. }
  861. void blitToWindow (HWND hwnd, HDC dc, bool transparent, int x, int y, uint8 updateLayeredWindowAlpha) noexcept
  862. {
  863. SetMapMode (dc, MM_TEXT);
  864. if (transparent)
  865. {
  866. auto windowBounds = getWindowScreenRect (hwnd);
  867. POINT p = { -x, -y };
  868. POINT pos = { windowBounds.left, windowBounds.top };
  869. SIZE size = { windowBounds.right - windowBounds.left,
  870. windowBounds.bottom - windowBounds.top };
  871. BLENDFUNCTION bf;
  872. bf.AlphaFormat = 1 /*AC_SRC_ALPHA*/;
  873. bf.BlendFlags = 0;
  874. bf.BlendOp = AC_SRC_OVER;
  875. bf.SourceConstantAlpha = updateLayeredWindowAlpha;
  876. UpdateLayeredWindow (hwnd, nullptr, &pos, &size, hdc, &p, 0, &bf, 2 /*ULW_ALPHA*/);
  877. }
  878. else
  879. {
  880. StretchDIBits (dc,
  881. x, y, width, height,
  882. 0, 0, width, height,
  883. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  884. DIB_RGB_COLORS, SRCCOPY);
  885. }
  886. }
  887. HBITMAP hBitmap;
  888. HGDIOBJ previousBitmap;
  889. BITMAPV4HEADER bitmapInfo;
  890. HDC hdc;
  891. uint8* bitmapData;
  892. int pixelStride, lineStride;
  893. uint8* imageData;
  894. private:
  895. static bool isGraphicsCard32Bit()
  896. {
  897. ScopedDeviceContext deviceContext { nullptr };
  898. return GetDeviceCaps (deviceContext.dc, BITSPIXEL) > 24;
  899. }
  900. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowsBitmapImage)
  901. };
  902. //==============================================================================
  903. Image createSnapshotOfNativeWindow (void* nativeWindowHandle)
  904. {
  905. auto hwnd = (HWND) nativeWindowHandle;
  906. auto r = convertPhysicalScreenRectangleToLogical (rectangleFromRECT (getWindowScreenRect (hwnd)), hwnd);
  907. const auto w = r.getWidth();
  908. const auto h = r.getHeight();
  909. auto nativeBitmap = new WindowsBitmapImage (Image::RGB, w, h, true);
  910. Image bitmap (nativeBitmap);
  911. ScopedDeviceContext deviceContext { hwnd };
  912. if (isPerMonitorDPIAwareProcess())
  913. {
  914. auto scale = getScaleFactorForWindow (hwnd);
  915. auto prevStretchMode = SetStretchBltMode (nativeBitmap->hdc, HALFTONE);
  916. SetBrushOrgEx (nativeBitmap->hdc, 0, 0, nullptr);
  917. StretchBlt (nativeBitmap->hdc, 0, 0, w, h,
  918. deviceContext.dc, 0, 0, roundToInt (w * scale), roundToInt (h * scale),
  919. SRCCOPY);
  920. SetStretchBltMode (nativeBitmap->hdc, prevStretchMode);
  921. }
  922. else
  923. {
  924. BitBlt (nativeBitmap->hdc, 0, 0, w, h, deviceContext.dc, 0, 0, SRCCOPY);
  925. }
  926. return SoftwareImageType().convert (bitmap);
  927. }
  928. //==============================================================================
  929. namespace IconConverters
  930. {
  931. struct IconDestructor
  932. {
  933. void operator() (HICON ptr) const { if (ptr != nullptr) DestroyIcon (ptr); }
  934. };
  935. using IconPtr = std::unique_ptr<std::remove_pointer_t<HICON>, IconDestructor>;
  936. static Image createImageFromHICON (HICON icon)
  937. {
  938. if (icon == nullptr)
  939. return {};
  940. struct ScopedICONINFO : public ICONINFO
  941. {
  942. ScopedICONINFO()
  943. {
  944. hbmColor = nullptr;
  945. hbmMask = nullptr;
  946. }
  947. ~ScopedICONINFO()
  948. {
  949. if (hbmColor != nullptr)
  950. ::DeleteObject (hbmColor);
  951. if (hbmMask != nullptr)
  952. ::DeleteObject (hbmMask);
  953. }
  954. };
  955. ScopedICONINFO info;
  956. if (! ::GetIconInfo (icon, &info))
  957. return {};
  958. BITMAP bm;
  959. if (! (::GetObject (info.hbmColor, sizeof (BITMAP), &bm)
  960. && bm.bmWidth > 0 && bm.bmHeight > 0))
  961. return {};
  962. ScopedDeviceContext deviceContext { nullptr };
  963. if (auto* dc = ::CreateCompatibleDC (deviceContext.dc))
  964. {
  965. BITMAPV5HEADER header = {};
  966. header.bV5Size = sizeof (BITMAPV5HEADER);
  967. header.bV5Width = bm.bmWidth;
  968. header.bV5Height = -bm.bmHeight;
  969. header.bV5Planes = 1;
  970. header.bV5Compression = BI_RGB;
  971. header.bV5BitCount = 32;
  972. header.bV5RedMask = 0x00FF0000;
  973. header.bV5GreenMask = 0x0000FF00;
  974. header.bV5BlueMask = 0x000000FF;
  975. header.bV5AlphaMask = 0xFF000000;
  976. header.bV5CSType = 0x57696E20; // 'Win '
  977. header.bV5Intent = LCS_GM_IMAGES;
  978. uint32* bitmapImageData = nullptr;
  979. if (auto* dib = ::CreateDIBSection (deviceContext.dc, (BITMAPINFO*) &header, DIB_RGB_COLORS,
  980. (void**) &bitmapImageData, nullptr, 0))
  981. {
  982. auto oldObject = ::SelectObject (dc, dib);
  983. auto numPixels = bm.bmWidth * bm.bmHeight;
  984. auto numColourComponents = (size_t) numPixels * 4;
  985. // Windows icon data comes as two layers, an XOR mask which contains the bulk
  986. // of the image data and an AND mask which provides the transparency. Annoyingly
  987. // the XOR mask can also contain an alpha channel, in which case the transparency
  988. // mask should not be applied, but there's no way to find out a priori if the XOR
  989. // mask contains an alpha channel.
  990. HeapBlock<bool> opacityMask (numPixels);
  991. memset (bitmapImageData, 0, numColourComponents);
  992. ::DrawIconEx (dc, 0, 0, icon, bm.bmWidth, bm.bmHeight, 0, nullptr, DI_MASK);
  993. for (int i = 0; i < numPixels; ++i)
  994. opacityMask[i] = (bitmapImageData[i] == 0);
  995. Image result = Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  996. Image::BitmapData imageData (result, Image::BitmapData::readWrite);
  997. memset (bitmapImageData, 0, numColourComponents);
  998. ::DrawIconEx (dc, 0, 0, icon, bm.bmWidth, bm.bmHeight, 0, nullptr, DI_NORMAL);
  999. memcpy (imageData.data, bitmapImageData, numColourComponents);
  1000. auto imageHasAlphaChannel = [&imageData, numPixels]()
  1001. {
  1002. for (int i = 0; i < numPixels; ++i)
  1003. if (imageData.data[i * 4] != 0)
  1004. return true;
  1005. return false;
  1006. };
  1007. if (! imageHasAlphaChannel())
  1008. for (int i = 0; i < numPixels; ++i)
  1009. imageData.data[i * 4] = opacityMask[i] ? 0xff : 0x00;
  1010. ::SelectObject (dc, oldObject);
  1011. ::DeleteObject (dib);
  1012. ::DeleteDC (dc);
  1013. return result;
  1014. }
  1015. ::DeleteDC (dc);
  1016. }
  1017. return {};
  1018. }
  1019. HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY);
  1020. HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY)
  1021. {
  1022. auto nativeBitmap = new WindowsBitmapImage (Image::ARGB, image.getWidth(), image.getHeight(), true);
  1023. Image bitmap (nativeBitmap);
  1024. {
  1025. Graphics g (bitmap);
  1026. g.drawImageAt (image, 0, 0);
  1027. }
  1028. auto mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, nullptr);
  1029. ICONINFO info;
  1030. info.fIcon = isIcon;
  1031. info.xHotspot = (DWORD) hotspotX;
  1032. info.yHotspot = (DWORD) hotspotY;
  1033. info.hbmMask = mask;
  1034. info.hbmColor = nativeBitmap->hBitmap;
  1035. auto hi = CreateIconIndirect (&info);
  1036. DeleteObject (mask);
  1037. return hi;
  1038. }
  1039. } // namespace IconConverters
  1040. //==============================================================================
  1041. JUCE_IUNKNOWNCLASS (ITipInvocation, "37c994e7-432b-4834-a2f7-dce1f13b834b")
  1042. {
  1043. static CLSID getCLSID() noexcept { return { 0x4ce576fa, 0x83dc, 0x4f88, { 0x95, 0x1c, 0x9d, 0x07, 0x82, 0xb4, 0xe3, 0x76 } }; }
  1044. JUCE_COMCALL Toggle (HWND) = 0;
  1045. };
  1046. } // namespace juce
  1047. #ifdef __CRT_UUID_DECL
  1048. __CRT_UUID_DECL (juce::ITipInvocation, 0x37c994e7, 0x432b, 0x4834, 0xa2, 0xf7, 0xdc, 0xe1, 0xf1, 0x3b, 0x83, 0x4b)
  1049. #endif
  1050. namespace juce
  1051. {
  1052. //==============================================================================
  1053. struct HSTRING_PRIVATE;
  1054. typedef HSTRING_PRIVATE* HSTRING;
  1055. struct IInspectable : public IUnknown
  1056. {
  1057. JUCE_COMCALL GetIids (ULONG* ,IID**) = 0;
  1058. JUCE_COMCALL GetRuntimeClassName (HSTRING*) = 0;
  1059. JUCE_COMCALL GetTrustLevel (void*) = 0;
  1060. };
  1061. JUCE_COMCLASS (IUIViewSettingsInterop, "3694dbf9-8f68-44be-8ff5-195c98ede8a6") : public IInspectable
  1062. {
  1063. JUCE_COMCALL GetForWindow (HWND, REFIID, void**) = 0;
  1064. };
  1065. JUCE_COMCLASS (IUIViewSettings, "c63657f6-8850-470d-88f8-455e16ea2c26") : public IInspectable
  1066. {
  1067. enum UserInteractionMode
  1068. {
  1069. Mouse = 0,
  1070. Touch = 1
  1071. };
  1072. JUCE_COMCALL GetUserInteractionMode (UserInteractionMode*) = 0;
  1073. };
  1074. } // namespace juce
  1075. #ifdef __CRT_UUID_DECL
  1076. __CRT_UUID_DECL (juce::IUIViewSettingsInterop, 0x3694dbf9, 0x8f68, 0x44be, 0x8f, 0xf5, 0x19, 0x5c, 0x98, 0xed, 0xe8, 0xa6)
  1077. __CRT_UUID_DECL (juce::IUIViewSettings, 0xc63657f6, 0x8850, 0x470d, 0x88, 0xf8, 0x45, 0x5e, 0x16, 0xea, 0x2c, 0x26)
  1078. #endif
  1079. namespace juce
  1080. {
  1081. struct UWPUIViewSettings
  1082. {
  1083. UWPUIViewSettings()
  1084. {
  1085. ComBaseModule dll (L"api-ms-win-core-winrt-l1-1-0");
  1086. if (dll.h != nullptr)
  1087. {
  1088. roInitialize = (RoInitializeFuncPtr) ::GetProcAddress (dll.h, "RoInitialize");
  1089. roGetActivationFactory = (RoGetActivationFactoryFuncPtr) ::GetProcAddress (dll.h, "RoGetActivationFactory");
  1090. createHString = (WindowsCreateStringFuncPtr) ::GetProcAddress (dll.h, "WindowsCreateString");
  1091. deleteHString = (WindowsDeleteStringFuncPtr) ::GetProcAddress (dll.h, "WindowsDeleteString");
  1092. if (roInitialize == nullptr || roGetActivationFactory == nullptr
  1093. || createHString == nullptr || deleteHString == nullptr)
  1094. return;
  1095. auto status = roInitialize (1);
  1096. if (status != S_OK && status != S_FALSE && (unsigned) status != 0x80010106L)
  1097. return;
  1098. LPCWSTR uwpClassName = L"Windows.UI.ViewManagement.UIViewSettings";
  1099. HSTRING uwpClassId = nullptr;
  1100. if (createHString (uwpClassName, (::UINT32) wcslen (uwpClassName), &uwpClassId) != S_OK
  1101. || uwpClassId == nullptr)
  1102. return;
  1103. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wlanguage-extension-token")
  1104. status = roGetActivationFactory (uwpClassId, __uuidof (IUIViewSettingsInterop),
  1105. (void**) viewSettingsInterop.resetAndGetPointerAddress());
  1106. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  1107. deleteHString (uwpClassId);
  1108. if (status != S_OK || viewSettingsInterop == nullptr)
  1109. return;
  1110. // move dll into member var
  1111. comBaseDLL = std::move (dll);
  1112. }
  1113. }
  1114. private:
  1115. //==============================================================================
  1116. struct ComBaseModule
  1117. {
  1118. ComBaseModule() = default;
  1119. ComBaseModule (LPCWSTR libraryName) : h (::LoadLibrary (libraryName)) {}
  1120. ComBaseModule (ComBaseModule&& o) : h (o.h) { o.h = nullptr; }
  1121. ~ComBaseModule() { release(); }
  1122. void release() { if (h != nullptr) ::FreeLibrary (h); h = nullptr; }
  1123. ComBaseModule& operator= (ComBaseModule&& o) { release(); h = o.h; o.h = nullptr; return *this; }
  1124. HMODULE h = {};
  1125. };
  1126. using RoInitializeFuncPtr = HRESULT (WINAPI*) (int);
  1127. using RoGetActivationFactoryFuncPtr = HRESULT (WINAPI*) (HSTRING, REFIID, void**);
  1128. using WindowsCreateStringFuncPtr = HRESULT (WINAPI*) (LPCWSTR,UINT32, HSTRING*);
  1129. using WindowsDeleteStringFuncPtr = HRESULT (WINAPI*) (HSTRING);
  1130. ComBaseModule comBaseDLL;
  1131. ComSmartPtr<IUIViewSettingsInterop> viewSettingsInterop;
  1132. RoInitializeFuncPtr roInitialize;
  1133. RoGetActivationFactoryFuncPtr roGetActivationFactory;
  1134. WindowsCreateStringFuncPtr createHString;
  1135. WindowsDeleteStringFuncPtr deleteHString;
  1136. };
  1137. //==============================================================================
  1138. static HMONITOR getMonitorFromOutput (ComSmartPtr<IDXGIOutput> output)
  1139. {
  1140. DXGI_OUTPUT_DESC desc = {};
  1141. return (FAILED (output->GetDesc (&desc)) || ! desc.AttachedToDesktop)
  1142. ? nullptr
  1143. : desc.Monitor;
  1144. }
  1145. using VBlankListener = ComponentPeer::VBlankListener;
  1146. //==============================================================================
  1147. class VSyncThread : private Thread,
  1148. private AsyncUpdater
  1149. {
  1150. public:
  1151. VSyncThread (ComSmartPtr<IDXGIOutput> out,
  1152. HMONITOR mon,
  1153. VBlankListener& listener)
  1154. : Thread ("VSyncThread"),
  1155. output (out),
  1156. monitor (mon)
  1157. {
  1158. listeners.push_back (listener);
  1159. startThread (Priority::highest);
  1160. }
  1161. ~VSyncThread() override
  1162. {
  1163. stopThread (-1);
  1164. cancelPendingUpdate();
  1165. }
  1166. void updateMonitor()
  1167. {
  1168. monitor = getMonitorFromOutput (output);
  1169. }
  1170. HMONITOR getMonitor() const noexcept { return monitor; }
  1171. void addListener (VBlankListener& listener)
  1172. {
  1173. listeners.push_back (listener);
  1174. }
  1175. bool removeListener (const VBlankListener& listener)
  1176. {
  1177. auto it = std::find_if (listeners.cbegin(),
  1178. listeners.cend(),
  1179. [&listener] (const auto& l) { return &(l.get()) == &listener; });
  1180. if (it != listeners.cend())
  1181. {
  1182. listeners.erase (it);
  1183. return true;
  1184. }
  1185. return false;
  1186. }
  1187. bool hasNoListeners() const noexcept
  1188. {
  1189. return listeners.empty();
  1190. }
  1191. bool hasListener (const VBlankListener& listener) const noexcept
  1192. {
  1193. return std::any_of (listeners.cbegin(),
  1194. listeners.cend(),
  1195. [&listener] (const auto& l) { return &(l.get()) == &listener; });
  1196. }
  1197. private:
  1198. //==============================================================================
  1199. void run() override
  1200. {
  1201. while (! threadShouldExit())
  1202. {
  1203. if (output->WaitForVBlank() == S_OK)
  1204. triggerAsyncUpdate();
  1205. else
  1206. Thread::sleep (1);
  1207. }
  1208. }
  1209. void handleAsyncUpdate() override
  1210. {
  1211. for (auto& listener : listeners)
  1212. listener.get().onVBlank();
  1213. }
  1214. //==============================================================================
  1215. ComSmartPtr<IDXGIOutput> output;
  1216. HMONITOR monitor = nullptr;
  1217. std::vector<std::reference_wrapper<VBlankListener>> listeners;
  1218. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VSyncThread)
  1219. JUCE_DECLARE_NON_MOVEABLE (VSyncThread)
  1220. };
  1221. //==============================================================================
  1222. class VBlankDispatcher : public DeletedAtShutdown
  1223. {
  1224. public:
  1225. void updateDisplay (VBlankListener& listener, HMONITOR monitor)
  1226. {
  1227. if (monitor == nullptr)
  1228. {
  1229. removeListener (listener);
  1230. return;
  1231. }
  1232. auto threadWithListener = threads.end();
  1233. auto threadWithMonitor = threads.end();
  1234. for (auto it = threads.begin(); it != threads.end(); ++it)
  1235. {
  1236. if ((*it)->hasListener (listener))
  1237. threadWithListener = it;
  1238. if ((*it)->getMonitor() == monitor)
  1239. threadWithMonitor = it;
  1240. if (threadWithListener != threads.end()
  1241. && threadWithMonitor != threads.end())
  1242. {
  1243. if (threadWithListener == threadWithMonitor)
  1244. return;
  1245. (*threadWithMonitor)->addListener (listener);
  1246. // This may invalidate iterators, so be careful!
  1247. removeListener (threadWithListener, listener);
  1248. return;
  1249. }
  1250. }
  1251. if (threadWithMonitor != threads.end())
  1252. {
  1253. (*threadWithMonitor)->addListener (listener);
  1254. return;
  1255. }
  1256. if (threadWithListener != threads.end())
  1257. removeListener (threadWithListener, listener);
  1258. for (auto adapter : adapters)
  1259. {
  1260. UINT i = 0;
  1261. ComSmartPtr<IDXGIOutput> output;
  1262. while (adapter->EnumOutputs (i, output.resetAndGetPointerAddress()) != DXGI_ERROR_NOT_FOUND)
  1263. {
  1264. if (getMonitorFromOutput (output) == monitor)
  1265. {
  1266. threads.emplace_back (std::make_unique<VSyncThread> (output, monitor, listener));
  1267. return;
  1268. }
  1269. ++i;
  1270. }
  1271. }
  1272. }
  1273. void removeListener (const VBlankListener& listener)
  1274. {
  1275. for (auto it = threads.begin(); it != threads.end(); ++it)
  1276. if (removeListener (it, listener))
  1277. return;
  1278. }
  1279. void reconfigureDisplays()
  1280. {
  1281. adapters.clear();
  1282. ComSmartPtr<IDXGIFactory> factory;
  1283. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wlanguage-extension-token")
  1284. CreateDXGIFactory (__uuidof (IDXGIFactory), (void**)factory.resetAndGetPointerAddress());
  1285. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  1286. UINT i = 0;
  1287. ComSmartPtr<IDXGIAdapter> adapter;
  1288. while (factory->EnumAdapters (i, adapter.resetAndGetPointerAddress()) != DXGI_ERROR_NOT_FOUND)
  1289. {
  1290. adapters.push_back (adapter);
  1291. ++i;
  1292. }
  1293. for (auto& thread : threads)
  1294. thread->updateMonitor();
  1295. threads.erase (std::remove_if (threads.begin(),
  1296. threads.end(),
  1297. [] (const auto& thread) { return thread->getMonitor() == nullptr; }),
  1298. threads.end());
  1299. }
  1300. JUCE_DECLARE_SINGLETON_SINGLETHREADED (VBlankDispatcher, false)
  1301. private:
  1302. //==============================================================================
  1303. using Threads = std::vector<std::unique_ptr<VSyncThread>>;
  1304. VBlankDispatcher()
  1305. {
  1306. reconfigureDisplays();
  1307. }
  1308. ~VBlankDispatcher() override
  1309. {
  1310. threads.clear();
  1311. clearSingletonInstance();
  1312. }
  1313. // This may delete the corresponding thread and invalidate iterators,
  1314. // so be careful!
  1315. bool removeListener (Threads::iterator it, const VBlankListener& listener)
  1316. {
  1317. if ((*it)->removeListener (listener))
  1318. {
  1319. if ((*it)->hasNoListeners())
  1320. threads.erase (it);
  1321. return true;
  1322. }
  1323. return false;
  1324. }
  1325. //==============================================================================
  1326. std::vector<ComSmartPtr<IDXGIAdapter>> adapters;
  1327. Threads threads;
  1328. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VBlankDispatcher)
  1329. JUCE_DECLARE_NON_MOVEABLE (VBlankDispatcher)
  1330. };
  1331. JUCE_IMPLEMENT_SINGLETON (VBlankDispatcher)
  1332. //==============================================================================
  1333. class SimpleTimer : private Timer
  1334. {
  1335. public:
  1336. SimpleTimer (int intervalMs, std::function<void()> callbackIn)
  1337. : callback (std::move (callbackIn))
  1338. {
  1339. jassert (callback);
  1340. startTimer (intervalMs);
  1341. }
  1342. ~SimpleTimer() override
  1343. {
  1344. stopTimer();
  1345. }
  1346. private:
  1347. void timerCallback() override
  1348. {
  1349. callback();
  1350. }
  1351. std::function<void()> callback;
  1352. };
  1353. //==============================================================================
  1354. class HWNDComponentPeer : public ComponentPeer,
  1355. private VBlankListener,
  1356. private Timer
  1357. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  1358. , public ModifierKeyReceiver
  1359. #endif
  1360. {
  1361. public:
  1362. enum RenderingEngineType
  1363. {
  1364. softwareRenderingEngine = 0,
  1365. direct2DRenderingEngine
  1366. };
  1367. //==============================================================================
  1368. HWNDComponentPeer (Component& comp, int windowStyleFlags, HWND parent, bool nonRepainting)
  1369. : ComponentPeer (comp, windowStyleFlags),
  1370. dontRepaint (nonRepainting),
  1371. parentToAddTo (parent),
  1372. currentRenderingEngine (softwareRenderingEngine)
  1373. {
  1374. callFunctionIfNotLocked (&createWindowCallback, this);
  1375. setTitle (component.getName());
  1376. updateShadower();
  1377. getNativeRealtimeModifiers = []
  1378. {
  1379. HWNDComponentPeer::updateKeyModifiers();
  1380. int mouseMods = 0;
  1381. if (HWNDComponentPeer::isKeyDown (VK_LBUTTON)) mouseMods |= ModifierKeys::leftButtonModifier;
  1382. if (HWNDComponentPeer::isKeyDown (VK_RBUTTON)) mouseMods |= ModifierKeys::rightButtonModifier;
  1383. if (HWNDComponentPeer::isKeyDown (VK_MBUTTON)) mouseMods |= ModifierKeys::middleButtonModifier;
  1384. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  1385. return ModifierKeys::currentModifiers;
  1386. };
  1387. updateCurrentMonitorAndRefreshVBlankDispatcher();
  1388. if (parentToAddTo != nullptr)
  1389. monitorUpdateTimer.emplace (1000, [this] { updateCurrentMonitorAndRefreshVBlankDispatcher(); });
  1390. suspendResumeRegistration = ScopedSuspendResumeNotificationRegistration { hwnd };
  1391. }
  1392. ~HWNDComponentPeer() override
  1393. {
  1394. suspendResumeRegistration = {};
  1395. VBlankDispatcher::getInstance()->removeListener (*this);
  1396. // do this first to avoid messages arriving for this window before it's destroyed
  1397. JuceWindowIdentifier::setAsJUCEWindow (hwnd, false);
  1398. if (isAccessibilityActive)
  1399. WindowsAccessibility::revokeUIAMapEntriesForWindow (hwnd);
  1400. shadower = nullptr;
  1401. currentTouches.deleteAllTouchesForPeer (this);
  1402. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  1403. if (dropTarget != nullptr)
  1404. {
  1405. dropTarget->peerIsDeleted = true;
  1406. dropTarget->Release();
  1407. dropTarget = nullptr;
  1408. }
  1409. #if JUCE_DIRECT2D
  1410. direct2DContext = nullptr;
  1411. #endif
  1412. }
  1413. //==============================================================================
  1414. void* getNativeHandle() const override { return hwnd; }
  1415. void setVisible (bool shouldBeVisible) override
  1416. {
  1417. const ScopedValueSetter<bool> scope (shouldIgnoreModalDismiss, true);
  1418. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  1419. if (shouldBeVisible)
  1420. InvalidateRect (hwnd, nullptr, 0);
  1421. else
  1422. lastPaintTime = 0;
  1423. }
  1424. void setTitle (const String& title) override
  1425. {
  1426. // Unfortunately some ancient bits of win32 mean you can only perform this operation from the message thread.
  1427. JUCE_ASSERT_MESSAGE_THREAD
  1428. SetWindowText (hwnd, title.toWideCharPointer());
  1429. }
  1430. void repaintNowIfTransparent()
  1431. {
  1432. if (isUsingUpdateLayeredWindow() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  1433. handlePaintMessage();
  1434. }
  1435. void updateBorderSize()
  1436. {
  1437. WINDOWINFO info;
  1438. info.cbSize = sizeof (info);
  1439. if (GetWindowInfo (hwnd, &info))
  1440. windowBorder = BorderSize<int> (roundToInt ((info.rcClient.top - info.rcWindow.top) / scaleFactor),
  1441. roundToInt ((info.rcClient.left - info.rcWindow.left) / scaleFactor),
  1442. roundToInt ((info.rcWindow.bottom - info.rcClient.bottom) / scaleFactor),
  1443. roundToInt ((info.rcWindow.right - info.rcClient.right) / scaleFactor));
  1444. #if JUCE_DIRECT2D
  1445. if (direct2DContext != nullptr)
  1446. direct2DContext->resized();
  1447. #endif
  1448. }
  1449. void setBounds (const Rectangle<int>& bounds, bool isNowFullScreen) override
  1450. {
  1451. // If we try to set new bounds while handling an existing position change,
  1452. // Windows may get confused about our current scale and size.
  1453. // This can happen when moving a window between displays, because the mouse-move
  1454. // generator in handlePositionChanged can cause the window to move again.
  1455. if (inHandlePositionChanged)
  1456. return;
  1457. const ScopedValueSetter<bool> scope (shouldIgnoreModalDismiss, true);
  1458. fullScreen = isNowFullScreen;
  1459. auto newBounds = windowBorder.addedTo (bounds);
  1460. if (isUsingUpdateLayeredWindow())
  1461. {
  1462. if (auto parentHwnd = GetParent (hwnd))
  1463. {
  1464. auto parentRect = convertPhysicalScreenRectangleToLogical (rectangleFromRECT (getWindowScreenRect (parentHwnd)), hwnd);
  1465. newBounds.translate (parentRect.getX(), parentRect.getY());
  1466. }
  1467. }
  1468. auto oldBounds = getBounds();
  1469. const bool hasMoved = (oldBounds.getPosition() != bounds.getPosition());
  1470. const bool hasResized = (oldBounds.getWidth() != bounds.getWidth()
  1471. || oldBounds.getHeight() != bounds.getHeight());
  1472. DWORD flags = SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER;
  1473. if (! hasMoved) flags |= SWP_NOMOVE;
  1474. if (! hasResized) flags |= SWP_NOSIZE;
  1475. setWindowPos (hwnd, newBounds, flags, ! inDpiChange);
  1476. if (hasResized && isValidPeer (this))
  1477. {
  1478. updateBorderSize();
  1479. repaintNowIfTransparent();
  1480. }
  1481. }
  1482. Rectangle<int> getBounds() const override
  1483. {
  1484. auto bounds = [this]
  1485. {
  1486. if (parentToAddTo == nullptr)
  1487. return convertPhysicalScreenRectangleToLogical (rectangleFromRECT (getWindowScreenRect (hwnd)), hwnd);
  1488. auto localBounds = rectangleFromRECT (getWindowClientRect (hwnd));
  1489. if (isPerMonitorDPIAwareWindow (hwnd))
  1490. return (localBounds.toDouble() / getPlatformScaleFactor()).toNearestInt();
  1491. return localBounds;
  1492. }();
  1493. return windowBorder.subtractedFrom (bounds);
  1494. }
  1495. Point<int> getScreenPosition() const
  1496. {
  1497. auto r = convertPhysicalScreenRectangleToLogical (rectangleFromRECT (getWindowScreenRect (hwnd)), hwnd);
  1498. return { r.getX() + windowBorder.getLeft(),
  1499. r.getY() + windowBorder.getTop() };
  1500. }
  1501. Point<float> localToGlobal (Point<float> relativePosition) override { return relativePosition + getScreenPosition().toFloat(); }
  1502. Point<float> globalToLocal (Point<float> screenPosition) override { return screenPosition - getScreenPosition().toFloat(); }
  1503. using ComponentPeer::localToGlobal;
  1504. using ComponentPeer::globalToLocal;
  1505. void setAlpha (float newAlpha) override
  1506. {
  1507. const ScopedValueSetter<bool> scope (shouldIgnoreModalDismiss, true);
  1508. auto intAlpha = (uint8) jlimit (0, 255, (int) (newAlpha * 255.0f));
  1509. if (component.isOpaque())
  1510. {
  1511. if (newAlpha < 1.0f)
  1512. {
  1513. SetWindowLong (hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) | WS_EX_LAYERED);
  1514. SetLayeredWindowAttributes (hwnd, RGB (0, 0, 0), intAlpha, LWA_ALPHA);
  1515. }
  1516. else
  1517. {
  1518. SetWindowLong (hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) & ~WS_EX_LAYERED);
  1519. RedrawWindow (hwnd, nullptr, nullptr, RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN);
  1520. }
  1521. }
  1522. else
  1523. {
  1524. updateLayeredWindowAlpha = intAlpha;
  1525. component.repaint();
  1526. }
  1527. }
  1528. void setMinimised (bool shouldBeMinimised) override
  1529. {
  1530. const ScopedValueSetter<bool> scope (shouldIgnoreModalDismiss, true);
  1531. if (shouldBeMinimised != isMinimised())
  1532. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_RESTORE);
  1533. }
  1534. bool isMinimised() const override
  1535. {
  1536. WINDOWPLACEMENT wp;
  1537. wp.length = sizeof (WINDOWPLACEMENT);
  1538. GetWindowPlacement (hwnd, &wp);
  1539. return wp.showCmd == SW_SHOWMINIMIZED;
  1540. }
  1541. void setFullScreen (bool shouldBeFullScreen) override
  1542. {
  1543. const ScopedValueSetter<bool> scope (shouldIgnoreModalDismiss, true);
  1544. setMinimised (false);
  1545. if (isFullScreen() != shouldBeFullScreen)
  1546. {
  1547. if (constrainer != nullptr)
  1548. constrainer->resizeStart();
  1549. fullScreen = shouldBeFullScreen;
  1550. const WeakReference<Component> deletionChecker (&component);
  1551. if (! fullScreen)
  1552. {
  1553. auto boundsCopy = lastNonFullscreenBounds;
  1554. if (hasTitleBar())
  1555. ShowWindow (hwnd, SW_SHOWNORMAL);
  1556. if (! boundsCopy.isEmpty())
  1557. setBounds (ScalingHelpers::scaledScreenPosToUnscaled (component, boundsCopy), false);
  1558. }
  1559. else
  1560. {
  1561. if (hasTitleBar())
  1562. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  1563. else
  1564. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  1565. }
  1566. if (deletionChecker != nullptr)
  1567. handleMovedOrResized();
  1568. if (constrainer != nullptr)
  1569. constrainer->resizeEnd();
  1570. }
  1571. }
  1572. bool isFullScreen() const override
  1573. {
  1574. if (! hasTitleBar())
  1575. return fullScreen;
  1576. WINDOWPLACEMENT wp;
  1577. wp.length = sizeof (wp);
  1578. GetWindowPlacement (hwnd, &wp);
  1579. return wp.showCmd == SW_SHOWMAXIMIZED;
  1580. }
  1581. bool contains (Point<int> localPos, bool trueIfInAChildWindow) const override
  1582. {
  1583. auto r = convertPhysicalScreenRectangleToLogical (rectangleFromRECT (getWindowScreenRect (hwnd)), hwnd);
  1584. if (! r.withZeroOrigin().contains (localPos))
  1585. return false;
  1586. auto w = WindowFromPoint (POINTFromPoint (convertLogicalScreenPointToPhysical (localPos + getScreenPosition(),
  1587. hwnd)));
  1588. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  1589. }
  1590. OptionalBorderSize getFrameSizeIfPresent() const override
  1591. {
  1592. return ComponentPeer::OptionalBorderSize { windowBorder };
  1593. }
  1594. BorderSize<int> getFrameSize() const override
  1595. {
  1596. return windowBorder;
  1597. }
  1598. bool setAlwaysOnTop (bool alwaysOnTop) override
  1599. {
  1600. const bool oldDeactivate = shouldDeactivateTitleBar;
  1601. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  1602. setWindowZOrder (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST);
  1603. shouldDeactivateTitleBar = oldDeactivate;
  1604. if (shadower != nullptr)
  1605. handleBroughtToFront();
  1606. return true;
  1607. }
  1608. void toFront (bool makeActive) override
  1609. {
  1610. const ScopedValueSetter<bool> scope (shouldIgnoreModalDismiss, true);
  1611. setMinimised (false);
  1612. const bool oldDeactivate = shouldDeactivateTitleBar;
  1613. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  1614. callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
  1615. shouldDeactivateTitleBar = oldDeactivate;
  1616. if (! makeActive)
  1617. {
  1618. // in this case a broughttofront call won't have occurred, so do it now..
  1619. handleBroughtToFront();
  1620. }
  1621. }
  1622. void toBehind (ComponentPeer* other) override
  1623. {
  1624. const ScopedValueSetter<bool> scope (shouldIgnoreModalDismiss, true);
  1625. if (auto* otherPeer = dynamic_cast<HWNDComponentPeer*> (other))
  1626. {
  1627. setMinimised (false);
  1628. // Must be careful not to try to put a topmost window behind a normal one, or Windows
  1629. // promotes the normal one to be topmost!
  1630. if (component.isAlwaysOnTop() == otherPeer->getComponent().isAlwaysOnTop())
  1631. setWindowZOrder (hwnd, otherPeer->hwnd);
  1632. else if (otherPeer->getComponent().isAlwaysOnTop())
  1633. setWindowZOrder (hwnd, HWND_TOP);
  1634. }
  1635. else
  1636. {
  1637. jassertfalse; // wrong type of window?
  1638. }
  1639. }
  1640. bool isFocused() const override
  1641. {
  1642. return callFunctionIfNotLocked (&getFocusCallback, nullptr) == (void*) hwnd;
  1643. }
  1644. void grabFocus() override
  1645. {
  1646. const ScopedValueSetter<bool> scope (shouldIgnoreModalDismiss, true);
  1647. const bool oldDeactivate = shouldDeactivateTitleBar;
  1648. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  1649. callFunctionIfNotLocked (&setFocusCallback, hwnd);
  1650. shouldDeactivateTitleBar = oldDeactivate;
  1651. }
  1652. void textInputRequired (Point<int>, TextInputTarget&) override
  1653. {
  1654. if (! hasCreatedCaret)
  1655. hasCreatedCaret = CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  1656. if (hasCreatedCaret)
  1657. {
  1658. SetCaretPos (0, 0);
  1659. ShowCaret (hwnd);
  1660. }
  1661. ImmAssociateContext (hwnd, nullptr);
  1662. // MSVC complains about the nullptr argument, but the docs for this
  1663. // function say that the second argument is ignored when the third
  1664. // argument is IACE_DEFAULT.
  1665. JUCE_BEGIN_IGNORE_WARNINGS_MSVC (6387)
  1666. ImmAssociateContextEx (hwnd, nullptr, IACE_DEFAULT);
  1667. JUCE_END_IGNORE_WARNINGS_MSVC
  1668. }
  1669. void closeInputMethodContext() override
  1670. {
  1671. imeHandler.handleSetContext (hwnd, false);
  1672. }
  1673. void dismissPendingTextInput() override
  1674. {
  1675. closeInputMethodContext();
  1676. ImmAssociateContext (hwnd, nullptr);
  1677. if (std::exchange (hasCreatedCaret, false))
  1678. DestroyCaret();
  1679. }
  1680. void repaint (const Rectangle<int>& area) override
  1681. {
  1682. deferredRepaints.add ((area.toDouble() * getPlatformScaleFactor()).getSmallestIntegerContainer());
  1683. }
  1684. void dispatchDeferredRepaints()
  1685. {
  1686. for (auto deferredRect : deferredRepaints)
  1687. {
  1688. auto r = RECTFromRectangle (deferredRect);
  1689. InvalidateRect (hwnd, &r, FALSE);
  1690. }
  1691. deferredRepaints.clear();
  1692. }
  1693. void performAnyPendingRepaintsNow() override
  1694. {
  1695. if (component.isVisible())
  1696. {
  1697. dispatchDeferredRepaints();
  1698. WeakReference<Component> localRef (&component);
  1699. MSG m;
  1700. if (isUsingUpdateLayeredWindow() || PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  1701. if (localRef != nullptr) // (the PeekMessage call can dispatch messages, which may delete this comp)
  1702. handlePaintMessage();
  1703. }
  1704. }
  1705. //==============================================================================
  1706. void onVBlank() override
  1707. {
  1708. vBlankListeners.call ([] (auto& l) { l.onVBlank(); });
  1709. dispatchDeferredRepaints();
  1710. }
  1711. //==============================================================================
  1712. static HWNDComponentPeer* getOwnerOfWindow (HWND h) noexcept
  1713. {
  1714. if (h != nullptr && JuceWindowIdentifier::isJUCEWindow (h))
  1715. return (HWNDComponentPeer*) GetWindowLongPtr (h, 8);
  1716. return nullptr;
  1717. }
  1718. //==============================================================================
  1719. bool isInside (HWND h) const noexcept
  1720. {
  1721. return GetAncestor (hwnd, GA_ROOT) == h;
  1722. }
  1723. //==============================================================================
  1724. static bool isKeyDown (const int key) noexcept { return (GetAsyncKeyState (key) & 0x8000) != 0; }
  1725. static void updateKeyModifiers() noexcept
  1726. {
  1727. int keyMods = 0;
  1728. if (isKeyDown (VK_SHIFT)) keyMods |= ModifierKeys::shiftModifier;
  1729. if (isKeyDown (VK_CONTROL)) keyMods |= ModifierKeys::ctrlModifier;
  1730. if (isKeyDown (VK_MENU)) keyMods |= ModifierKeys::altModifier;
  1731. // workaround: Windows maps AltGr to left-Ctrl + right-Alt.
  1732. if (isKeyDown (VK_RMENU) && !isKeyDown (VK_RCONTROL))
  1733. {
  1734. keyMods = (keyMods & ~ModifierKeys::ctrlModifier) | ModifierKeys::altModifier;
  1735. }
  1736. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  1737. }
  1738. static void updateModifiersFromWParam (const WPARAM wParam)
  1739. {
  1740. int mouseMods = 0;
  1741. if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
  1742. if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
  1743. if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
  1744. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  1745. updateKeyModifiers();
  1746. }
  1747. //==============================================================================
  1748. bool dontRepaint;
  1749. static ModifierKeys modifiersAtLastCallback;
  1750. //==============================================================================
  1751. struct FileDropTarget : public ComBaseClassHelper<IDropTarget>
  1752. {
  1753. FileDropTarget (HWNDComponentPeer& p) : peer (p) {}
  1754. JUCE_COMRESULT DragEnter (IDataObject* pDataObject, DWORD grfKeyState, POINTL mousePos, DWORD* pdwEffect) override
  1755. {
  1756. auto hr = updateFileList (pDataObject);
  1757. if (FAILED (hr))
  1758. return hr;
  1759. return DragOver (grfKeyState, mousePos, pdwEffect);
  1760. }
  1761. JUCE_COMRESULT DragLeave() override
  1762. {
  1763. if (peerIsDeleted)
  1764. return S_FALSE;
  1765. peer.handleDragExit (dragInfo);
  1766. return S_OK;
  1767. }
  1768. JUCE_COMRESULT DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect) override
  1769. {
  1770. if (peerIsDeleted)
  1771. return S_FALSE;
  1772. dragInfo.position = getMousePos (mousePos).roundToInt();
  1773. *pdwEffect = peer.handleDragMove (dragInfo) ? (DWORD) DROPEFFECT_COPY
  1774. : (DWORD) DROPEFFECT_NONE;
  1775. return S_OK;
  1776. }
  1777. JUCE_COMRESULT Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect) override
  1778. {
  1779. auto hr = updateFileList (pDataObject);
  1780. if (FAILED (hr))
  1781. return hr;
  1782. dragInfo.position = getMousePos (mousePos).roundToInt();
  1783. *pdwEffect = peer.handleDragDrop (dragInfo) ? (DWORD) DROPEFFECT_COPY
  1784. : (DWORD) DROPEFFECT_NONE;
  1785. return S_OK;
  1786. }
  1787. HWNDComponentPeer& peer;
  1788. ComponentPeer::DragInfo dragInfo;
  1789. bool peerIsDeleted = false;
  1790. private:
  1791. Point<float> getMousePos (POINTL mousePos) const
  1792. {
  1793. const auto originalPos = pointFromPOINT ({ mousePos.x, mousePos.y });
  1794. const auto logicalPos = convertPhysicalScreenPointToLogical (originalPos, peer.hwnd);
  1795. return ScalingHelpers::screenPosToLocalPos (peer.component, logicalPos.toFloat());
  1796. }
  1797. struct DroppedData
  1798. {
  1799. DroppedData (IDataObject* dataObject, CLIPFORMAT type)
  1800. {
  1801. FORMATETC format = { type, nullptr, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  1802. if (SUCCEEDED (error = dataObject->GetData (&format, &medium)) && medium.hGlobal != nullptr)
  1803. {
  1804. dataSize = GlobalSize (medium.hGlobal);
  1805. data = GlobalLock (medium.hGlobal);
  1806. }
  1807. }
  1808. ~DroppedData()
  1809. {
  1810. if (data != nullptr && medium.hGlobal != nullptr)
  1811. GlobalUnlock (medium.hGlobal);
  1812. }
  1813. HRESULT error;
  1814. STGMEDIUM medium { TYMED_HGLOBAL, { nullptr }, nullptr };
  1815. void* data = {};
  1816. SIZE_T dataSize;
  1817. };
  1818. void parseFileList (HDROP dropFiles)
  1819. {
  1820. dragInfo.files.clearQuick();
  1821. std::vector<TCHAR> nameBuffer;
  1822. const auto numFiles = DragQueryFile (dropFiles, ~(UINT) 0, nullptr, 0);
  1823. for (UINT i = 0; i < numFiles; ++i)
  1824. {
  1825. const auto bufferSize = DragQueryFile (dropFiles, i, nullptr, 0);
  1826. nameBuffer.clear();
  1827. nameBuffer.resize (bufferSize + 1, 0); // + 1 for the null terminator
  1828. [[maybe_unused]] const auto readCharacters = DragQueryFile (dropFiles, i, nameBuffer.data(), (UINT) nameBuffer.size());
  1829. jassert (readCharacters == bufferSize);
  1830. dragInfo.files.add (String (nameBuffer.data()));
  1831. }
  1832. }
  1833. HRESULT updateFileList (IDataObject* const dataObject)
  1834. {
  1835. if (peerIsDeleted)
  1836. return S_FALSE;
  1837. dragInfo.clear();
  1838. {
  1839. DroppedData fileData (dataObject, CF_HDROP);
  1840. if (SUCCEEDED (fileData.error))
  1841. {
  1842. parseFileList (static_cast<HDROP> (fileData.data));
  1843. return S_OK;
  1844. }
  1845. }
  1846. DroppedData textData (dataObject, CF_UNICODETEXT);
  1847. if (SUCCEEDED (textData.error))
  1848. {
  1849. dragInfo.text = String (CharPointer_UTF16 ((const WCHAR*) textData.data),
  1850. CharPointer_UTF16 ((const WCHAR*) addBytesToPointer (textData.data, textData.dataSize)));
  1851. return S_OK;
  1852. }
  1853. return textData.error;
  1854. }
  1855. JUCE_DECLARE_NON_COPYABLE (FileDropTarget)
  1856. };
  1857. static bool offerKeyMessageToJUCEWindow (MSG& m)
  1858. {
  1859. if (m.message == WM_KEYDOWN || m.message == WM_KEYUP)
  1860. {
  1861. if (Component::getCurrentlyFocusedComponent() != nullptr)
  1862. {
  1863. if (auto* peer = getOwnerOfWindow (m.hwnd))
  1864. {
  1865. ScopedThreadDPIAwarenessSetter threadDpiAwarenessSetter { m.hwnd };
  1866. return m.message == WM_KEYDOWN ? peer->doKeyDown (m.wParam)
  1867. : peer->doKeyUp (m.wParam);
  1868. }
  1869. }
  1870. }
  1871. return false;
  1872. }
  1873. double getPlatformScaleFactor() const noexcept override
  1874. {
  1875. #if ! JUCE_WIN_PER_MONITOR_DPI_AWARE
  1876. return 1.0;
  1877. #else
  1878. if (! isPerMonitorDPIAwareWindow (hwnd))
  1879. return 1.0;
  1880. if (auto* parentHWND = GetParent (hwnd))
  1881. {
  1882. if (auto* parentPeer = getOwnerOfWindow (parentHWND))
  1883. return parentPeer->getPlatformScaleFactor();
  1884. if (getDPIForWindow != nullptr)
  1885. return getScaleFactorForWindow (parentHWND);
  1886. }
  1887. return scaleFactor;
  1888. #endif
  1889. }
  1890. private:
  1891. HWND hwnd, parentToAddTo;
  1892. std::unique_ptr<DropShadower> shadower;
  1893. RenderingEngineType currentRenderingEngine;
  1894. #if JUCE_DIRECT2D
  1895. std::unique_ptr<Direct2DLowLevelGraphicsContext> direct2DContext;
  1896. #endif
  1897. uint32 lastPaintTime = 0;
  1898. ULONGLONG lastMagnifySize = 0;
  1899. bool fullScreen = false, isDragging = false, isMouseOver = false,
  1900. hasCreatedCaret = false, constrainerIsResizing = false;
  1901. BorderSize<int> windowBorder;
  1902. IconConverters::IconPtr currentWindowIcon;
  1903. FileDropTarget* dropTarget = nullptr;
  1904. uint8 updateLayeredWindowAlpha = 255;
  1905. UWPUIViewSettings uwpViewSettings;
  1906. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  1907. ModifierKeyProvider* modProvider = nullptr;
  1908. #endif
  1909. double scaleFactor = 1.0;
  1910. bool inDpiChange = 0, inHandlePositionChanged = 0;
  1911. HMONITOR currentMonitor = nullptr;
  1912. bool isAccessibilityActive = false;
  1913. //==============================================================================
  1914. static MultiTouchMapper<DWORD> currentTouches;
  1915. //==============================================================================
  1916. struct TemporaryImage : private Timer
  1917. {
  1918. TemporaryImage() {}
  1919. Image& getImage (bool transparent, int w, int h)
  1920. {
  1921. auto format = transparent ? Image::ARGB : Image::RGB;
  1922. if ((! image.isValid()) || image.getWidth() < w || image.getHeight() < h || image.getFormat() != format)
  1923. image = Image (new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false));
  1924. startTimer (3000);
  1925. return image;
  1926. }
  1927. void timerCallback() override
  1928. {
  1929. stopTimer();
  1930. image = {};
  1931. }
  1932. private:
  1933. Image image;
  1934. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TemporaryImage)
  1935. };
  1936. TemporaryImage offscreenImageGenerator;
  1937. //==============================================================================
  1938. class WindowClassHolder : private DeletedAtShutdown
  1939. {
  1940. public:
  1941. WindowClassHolder()
  1942. {
  1943. // this name has to be different for each app/dll instance because otherwise poor old Windows can
  1944. // get a bit confused (even despite it not being a process-global window class).
  1945. String windowClassName ("JUCE_");
  1946. windowClassName << String::toHexString (Time::currentTimeMillis());
  1947. auto moduleHandle = (HINSTANCE) Process::getCurrentModuleInstanceHandle();
  1948. TCHAR moduleFile[1024] = {};
  1949. GetModuleFileName (moduleHandle, moduleFile, 1024);
  1950. WNDCLASSEX wcex = {};
  1951. wcex.cbSize = sizeof (wcex);
  1952. wcex.style = CS_OWNDC;
  1953. wcex.lpfnWndProc = (WNDPROC) windowProc;
  1954. wcex.lpszClassName = windowClassName.toWideCharPointer();
  1955. wcex.cbWndExtra = 32;
  1956. wcex.hInstance = moduleHandle;
  1957. for (const auto& [index, field, ptr] : { std::tuple { 0, &wcex.hIcon, &iconBig },
  1958. std::tuple { 1, &wcex.hIconSm, &iconSmall } })
  1959. {
  1960. auto iconNum = static_cast<WORD> (index);
  1961. ptr->reset (*field = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum));
  1962. }
  1963. atom = RegisterClassEx (&wcex);
  1964. jassert (atom != 0);
  1965. isEventBlockedByModalComps = checkEventBlockedByModalComps;
  1966. }
  1967. ~WindowClassHolder()
  1968. {
  1969. if (ComponentPeer::getNumPeers() == 0)
  1970. UnregisterClass (getWindowClassName(), (HINSTANCE) Process::getCurrentModuleInstanceHandle());
  1971. clearSingletonInstance();
  1972. }
  1973. LPCTSTR getWindowClassName() const noexcept { return (LPCTSTR) (pointer_sized_uint) atom; }
  1974. JUCE_DECLARE_SINGLETON_SINGLETHREADED_MINIMAL (WindowClassHolder)
  1975. private:
  1976. ATOM atom;
  1977. static bool isHWNDBlockedByModalComponents (HWND h)
  1978. {
  1979. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  1980. if (auto* c = Desktop::getInstance().getComponent (i))
  1981. if ((! c->isCurrentlyBlockedByAnotherModalComponent())
  1982. && IsChild ((HWND) c->getWindowHandle(), h))
  1983. return false;
  1984. return true;
  1985. }
  1986. static bool checkEventBlockedByModalComps (const MSG& m)
  1987. {
  1988. if (Component::getNumCurrentlyModalComponents() == 0 || JuceWindowIdentifier::isJUCEWindow (m.hwnd))
  1989. return false;
  1990. switch (m.message)
  1991. {
  1992. case WM_MOUSEMOVE:
  1993. case WM_NCMOUSEMOVE:
  1994. case 0x020A: /* WM_MOUSEWHEEL */
  1995. case 0x020E: /* WM_MOUSEHWHEEL */
  1996. case WM_KEYUP:
  1997. case WM_SYSKEYUP:
  1998. case WM_CHAR:
  1999. case WM_APPCOMMAND:
  2000. case WM_LBUTTONUP:
  2001. case WM_MBUTTONUP:
  2002. case WM_RBUTTONUP:
  2003. case WM_MOUSEACTIVATE:
  2004. case WM_NCMOUSEHOVER:
  2005. case WM_MOUSEHOVER:
  2006. case WM_TOUCH:
  2007. case WM_POINTERUPDATE:
  2008. case WM_NCPOINTERUPDATE:
  2009. case WM_POINTERWHEEL:
  2010. case WM_POINTERHWHEEL:
  2011. case WM_POINTERUP:
  2012. case WM_POINTERACTIVATE:
  2013. return isHWNDBlockedByModalComponents(m.hwnd);
  2014. case WM_NCLBUTTONDOWN:
  2015. case WM_NCLBUTTONDBLCLK:
  2016. case WM_NCRBUTTONDOWN:
  2017. case WM_NCRBUTTONDBLCLK:
  2018. case WM_NCMBUTTONDOWN:
  2019. case WM_NCMBUTTONDBLCLK:
  2020. case WM_LBUTTONDOWN:
  2021. case WM_LBUTTONDBLCLK:
  2022. case WM_MBUTTONDOWN:
  2023. case WM_MBUTTONDBLCLK:
  2024. case WM_RBUTTONDOWN:
  2025. case WM_RBUTTONDBLCLK:
  2026. case WM_KEYDOWN:
  2027. case WM_SYSKEYDOWN:
  2028. case WM_NCPOINTERDOWN:
  2029. case WM_POINTERDOWN:
  2030. if (isHWNDBlockedByModalComponents (m.hwnd))
  2031. {
  2032. if (auto* modal = Component::getCurrentlyModalComponent (0))
  2033. modal->inputAttemptWhenModal();
  2034. return true;
  2035. }
  2036. break;
  2037. default:
  2038. break;
  2039. }
  2040. return false;
  2041. }
  2042. IconConverters::IconPtr iconBig, iconSmall;
  2043. JUCE_DECLARE_NON_COPYABLE (WindowClassHolder)
  2044. };
  2045. //==============================================================================
  2046. static void* createWindowCallback (void* userData)
  2047. {
  2048. static_cast<HWNDComponentPeer*> (userData)->createWindow();
  2049. return nullptr;
  2050. }
  2051. void createWindow()
  2052. {
  2053. DWORD exstyle = 0;
  2054. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  2055. if (hasTitleBar())
  2056. {
  2057. type |= WS_OVERLAPPED;
  2058. if ((styleFlags & windowHasCloseButton) != 0)
  2059. {
  2060. type |= WS_SYSMENU;
  2061. }
  2062. else
  2063. {
  2064. // annoyingly, windows won't let you have a min/max button without a close button
  2065. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  2066. }
  2067. if ((styleFlags & windowIsResizable) != 0)
  2068. type |= WS_THICKFRAME;
  2069. }
  2070. else if (parentToAddTo != nullptr)
  2071. {
  2072. type |= WS_CHILD;
  2073. }
  2074. else
  2075. {
  2076. type |= WS_POPUP | WS_SYSMENU;
  2077. }
  2078. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  2079. exstyle |= WS_EX_TOOLWINDOW;
  2080. else
  2081. exstyle |= WS_EX_APPWINDOW;
  2082. if ((styleFlags & windowHasMinimiseButton) != 0) type |= WS_MINIMIZEBOX;
  2083. if ((styleFlags & windowHasMaximiseButton) != 0) type |= WS_MAXIMIZEBOX;
  2084. if ((styleFlags & windowIgnoresMouseClicks) != 0) exstyle |= WS_EX_TRANSPARENT;
  2085. if ((styleFlags & windowIsSemiTransparent) != 0) exstyle |= WS_EX_LAYERED;
  2086. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->getWindowClassName(),
  2087. L"", type, 0, 0, 0, 0, parentToAddTo, nullptr,
  2088. (HINSTANCE) Process::getCurrentModuleInstanceHandle(), nullptr);
  2089. #if JUCE_DEBUG
  2090. // The DPI-awareness context of this window and JUCE's hidden message window are different.
  2091. // You normally want these to match otherwise timer events and async messages will happen
  2092. // in a different context to normal HWND messages which can cause issues with UI scaling.
  2093. jassert (isPerMonitorDPIAwareWindow (hwnd) == isPerMonitorDPIAwareWindow (juce_messageWindowHandle)
  2094. || isInScopedDPIAwarenessDisabler());
  2095. #endif
  2096. if (hwnd != nullptr)
  2097. {
  2098. SetWindowLongPtr (hwnd, 0, 0);
  2099. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  2100. JuceWindowIdentifier::setAsJUCEWindow (hwnd, true);
  2101. if (dropTarget == nullptr)
  2102. {
  2103. HWNDComponentPeer* peer = nullptr;
  2104. if (dontRepaint)
  2105. peer = getOwnerOfWindow (parentToAddTo);
  2106. if (peer == nullptr)
  2107. peer = this;
  2108. dropTarget = new FileDropTarget (*peer);
  2109. }
  2110. RegisterDragDrop (hwnd, dropTarget);
  2111. if (canUseMultiTouch())
  2112. registerTouchWindow (hwnd, 0);
  2113. setDPIAwareness();
  2114. if (isPerMonitorDPIAwareThread())
  2115. scaleFactor = getScaleFactorForWindow (hwnd);
  2116. setMessageFilter();
  2117. updateBorderSize();
  2118. checkForPointerAPI();
  2119. // This is needed so that our plugin window gets notified of WM_SETTINGCHANGE messages
  2120. // and can respond to display scale changes
  2121. if (! JUCEApplication::isStandaloneApp())
  2122. settingChangeCallback = ComponentPeer::forceDisplayUpdate;
  2123. // Calling this function here is (for some reason) necessary to make Windows
  2124. // correctly enable the menu items that we specify in the wm_initmenu message.
  2125. GetSystemMenu (hwnd, false);
  2126. auto alpha = component.getAlpha();
  2127. if (alpha < 1.0f)
  2128. setAlpha (alpha);
  2129. }
  2130. else
  2131. {
  2132. TCHAR messageBuffer[256] = {};
  2133. FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  2134. nullptr, GetLastError(), MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
  2135. messageBuffer, (DWORD) numElementsInArray (messageBuffer) - 1, nullptr);
  2136. DBG (messageBuffer);
  2137. jassertfalse;
  2138. }
  2139. }
  2140. static BOOL CALLBACK revokeChildDragDropCallback (HWND hwnd, LPARAM) { RevokeDragDrop (hwnd); return TRUE; }
  2141. static void* destroyWindowCallback (void* handle)
  2142. {
  2143. auto hwnd = reinterpret_cast<HWND> (handle);
  2144. if (IsWindow (hwnd))
  2145. {
  2146. RevokeDragDrop (hwnd);
  2147. // NB: we need to do this before DestroyWindow() as child HWNDs will be invalid after
  2148. EnumChildWindows (hwnd, revokeChildDragDropCallback, 0);
  2149. DestroyWindow (hwnd);
  2150. }
  2151. return nullptr;
  2152. }
  2153. static void* toFrontCallback1 (void* h)
  2154. {
  2155. BringWindowToTop ((HWND) h);
  2156. return nullptr;
  2157. }
  2158. static void* toFrontCallback2 (void* h)
  2159. {
  2160. setWindowZOrder ((HWND) h, HWND_TOP);
  2161. return nullptr;
  2162. }
  2163. static void* setFocusCallback (void* h)
  2164. {
  2165. SetFocus ((HWND) h);
  2166. return nullptr;
  2167. }
  2168. static void* getFocusCallback (void*)
  2169. {
  2170. return GetFocus();
  2171. }
  2172. bool isUsingUpdateLayeredWindow() const
  2173. {
  2174. return ! component.isOpaque();
  2175. }
  2176. bool hasTitleBar() const noexcept { return (styleFlags & windowHasTitleBar) != 0; }
  2177. void updateShadower()
  2178. {
  2179. if (! component.isCurrentlyModal() && (styleFlags & windowHasDropShadow) != 0
  2180. && ((! hasTitleBar()) || SystemStats::getOperatingSystemType() < SystemStats::WinVista))
  2181. {
  2182. shadower = component.getLookAndFeel().createDropShadowerForComponent (component);
  2183. if (shadower != nullptr)
  2184. shadower->setOwner (&component);
  2185. }
  2186. }
  2187. void setIcon (const Image& newIcon) override
  2188. {
  2189. if (IconConverters::IconPtr hicon { IconConverters::createHICONFromImage (newIcon, TRUE, 0, 0) })
  2190. {
  2191. SendMessage (hwnd, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM> (hicon.get()));
  2192. SendMessage (hwnd, WM_SETICON, ICON_SMALL, reinterpret_cast<LPARAM> (hicon.get()));
  2193. currentWindowIcon = std::move (hicon);
  2194. }
  2195. }
  2196. void setMessageFilter()
  2197. {
  2198. using ChangeWindowMessageFilterExFunc = BOOL (WINAPI*) (HWND, UINT, DWORD, PVOID);
  2199. if (auto changeMessageFilter = (ChangeWindowMessageFilterExFunc) getUser32Function ("ChangeWindowMessageFilterEx"))
  2200. {
  2201. changeMessageFilter (hwnd, WM_DROPFILES, 1 /*MSGFLT_ALLOW*/, nullptr);
  2202. changeMessageFilter (hwnd, WM_COPYDATA, 1 /*MSGFLT_ALLOW*/, nullptr);
  2203. changeMessageFilter (hwnd, 0x49, 1 /*MSGFLT_ALLOW*/, nullptr);
  2204. }
  2205. }
  2206. struct ChildWindowClippingInfo
  2207. {
  2208. HDC dc;
  2209. HWNDComponentPeer* peer;
  2210. RectangleList<int>* clip;
  2211. Point<int> origin;
  2212. int savedDC;
  2213. };
  2214. static BOOL CALLBACK clipChildWindowCallback (HWND hwnd, LPARAM context)
  2215. {
  2216. if (IsWindowVisible (hwnd))
  2217. {
  2218. auto& info = *(ChildWindowClippingInfo*) context;
  2219. if (GetParent (hwnd) == info.peer->hwnd)
  2220. {
  2221. auto clip = rectangleFromRECT (getWindowClientRect (hwnd));
  2222. info.clip->subtract (clip - info.origin);
  2223. if (info.savedDC == 0)
  2224. info.savedDC = SaveDC (info.dc);
  2225. ExcludeClipRect (info.dc, clip.getX(), clip.getY(), clip.getRight(), clip.getBottom());
  2226. }
  2227. }
  2228. return TRUE;
  2229. }
  2230. //==============================================================================
  2231. void handlePaintMessage()
  2232. {
  2233. #if JUCE_DIRECT2D
  2234. if (direct2DContext != nullptr)
  2235. {
  2236. RECT r;
  2237. if (GetUpdateRect (hwnd, &r, false))
  2238. {
  2239. direct2DContext->start();
  2240. direct2DContext->clipToRectangle (convertPhysicalScreenRectangleToLogical (rectangleFromRECT (r), hwnd));
  2241. handlePaint (*direct2DContext);
  2242. direct2DContext->end();
  2243. ValidateRect (hwnd, &r);
  2244. }
  2245. }
  2246. else
  2247. #endif
  2248. {
  2249. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  2250. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  2251. PAINTSTRUCT paintStruct;
  2252. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  2253. // message and become re-entrant, but that's OK
  2254. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  2255. // corrupt the image it's using to paint into, so do a check here.
  2256. static bool reentrant = false;
  2257. if (! reentrant)
  2258. {
  2259. const ScopedValueSetter<bool> setter (reentrant, true, false);
  2260. if (dontRepaint)
  2261. component.handleCommandMessage (0); // (this triggers a repaint in the openGL context)
  2262. else
  2263. performPaint (dc, rgn, regionType, paintStruct);
  2264. }
  2265. DeleteObject (rgn);
  2266. EndPaint (hwnd, &paintStruct);
  2267. #if JUCE_MSVC
  2268. _fpreset(); // because some graphics cards can unmask FP exceptions
  2269. #endif
  2270. }
  2271. lastPaintTime = Time::getMillisecondCounter();
  2272. }
  2273. void performPaint (HDC dc, HRGN rgn, int regionType, PAINTSTRUCT& paintStruct)
  2274. {
  2275. int x = paintStruct.rcPaint.left;
  2276. int y = paintStruct.rcPaint.top;
  2277. int w = paintStruct.rcPaint.right - x;
  2278. int h = paintStruct.rcPaint.bottom - y;
  2279. const bool transparent = isUsingUpdateLayeredWindow();
  2280. if (transparent)
  2281. {
  2282. // it's not possible to have a transparent window with a title bar at the moment!
  2283. jassert (! hasTitleBar());
  2284. auto r = getWindowScreenRect (hwnd);
  2285. x = y = 0;
  2286. w = r.right - r.left;
  2287. h = r.bottom - r.top;
  2288. }
  2289. if (w > 0 && h > 0)
  2290. {
  2291. Image& offscreenImage = offscreenImageGenerator.getImage (transparent, w, h);
  2292. RectangleList<int> contextClip;
  2293. const Rectangle<int> clipBounds (w, h);
  2294. bool needToPaintAll = true;
  2295. if (regionType == COMPLEXREGION && ! transparent)
  2296. {
  2297. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  2298. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  2299. DeleteObject (clipRgn);
  2300. std::aligned_storage_t<8192, alignof (RGNDATA)> rgnData;
  2301. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) &rgnData);
  2302. if (res > 0 && res <= sizeof (rgnData))
  2303. {
  2304. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) &rgnData)->rdh);
  2305. if (hdr->iType == RDH_RECTANGLES
  2306. && hdr->rcBound.right - hdr->rcBound.left >= w
  2307. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  2308. {
  2309. needToPaintAll = false;
  2310. auto rects = unalignedPointerCast<const RECT*> ((char*) &rgnData + sizeof (RGNDATAHEADER));
  2311. for (int i = (int) ((RGNDATA*) &rgnData)->rdh.nCount; --i >= 0;)
  2312. {
  2313. if (rects->right <= x + w && rects->bottom <= y + h)
  2314. {
  2315. const int cx = jmax (x, (int) rects->left);
  2316. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y,
  2317. rects->right - cx, rects->bottom - rects->top)
  2318. .getIntersection (clipBounds));
  2319. }
  2320. else
  2321. {
  2322. needToPaintAll = true;
  2323. break;
  2324. }
  2325. ++rects;
  2326. }
  2327. }
  2328. }
  2329. }
  2330. if (needToPaintAll)
  2331. {
  2332. contextClip.clear();
  2333. contextClip.addWithoutMerging (Rectangle<int> (w, h));
  2334. }
  2335. ChildWindowClippingInfo childClipInfo = { dc, this, &contextClip, Point<int> (x, y), 0 };
  2336. EnumChildWindows (hwnd, clipChildWindowCallback, (LPARAM) &childClipInfo);
  2337. if (! contextClip.isEmpty())
  2338. {
  2339. if (transparent)
  2340. for (auto& i : contextClip)
  2341. offscreenImage.clear (i);
  2342. {
  2343. auto context = component.getLookAndFeel()
  2344. .createGraphicsContext (offscreenImage, { -x, -y }, contextClip);
  2345. context->addTransform (AffineTransform::scale ((float) getPlatformScaleFactor()));
  2346. handlePaint (*context);
  2347. }
  2348. static_cast<WindowsBitmapImage*> (offscreenImage.getPixelData())
  2349. ->blitToWindow (hwnd, dc, transparent, x, y, updateLayeredWindowAlpha);
  2350. }
  2351. if (childClipInfo.savedDC != 0)
  2352. RestoreDC (dc, childClipInfo.savedDC);
  2353. }
  2354. }
  2355. //==============================================================================
  2356. void doMouseEvent (Point<float> position, float pressure, float orientation = 0.0f, ModifierKeys mods = ModifierKeys::currentModifiers)
  2357. {
  2358. handleMouseEvent (MouseInputSource::InputSourceType::mouse, position, mods, pressure, orientation, getMouseEventTime());
  2359. }
  2360. StringArray getAvailableRenderingEngines() override
  2361. {
  2362. StringArray s ("Software Renderer");
  2363. #if JUCE_DIRECT2D
  2364. if (SystemStats::getOperatingSystemType() >= SystemStats::Windows7)
  2365. s.add ("Direct2D");
  2366. #endif
  2367. return s;
  2368. }
  2369. int getCurrentRenderingEngine() const override { return currentRenderingEngine; }
  2370. #if JUCE_DIRECT2D
  2371. void updateDirect2DContext()
  2372. {
  2373. if (currentRenderingEngine != direct2DRenderingEngine)
  2374. direct2DContext = nullptr;
  2375. else if (direct2DContext == nullptr)
  2376. direct2DContext.reset (new Direct2DLowLevelGraphicsContext (hwnd));
  2377. }
  2378. #endif
  2379. void setCurrentRenderingEngine ([[maybe_unused]] int index) override
  2380. {
  2381. #if JUCE_DIRECT2D
  2382. if (getAvailableRenderingEngines().size() > 1)
  2383. {
  2384. currentRenderingEngine = index == 1 ? direct2DRenderingEngine : softwareRenderingEngine;
  2385. updateDirect2DContext();
  2386. repaint (component.getLocalBounds());
  2387. }
  2388. #endif
  2389. }
  2390. static uint32 getMinTimeBetweenMouseMoves()
  2391. {
  2392. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  2393. return 0;
  2394. return 1000 / 60; // Throttling the incoming mouse-events seems to still be needed in XP..
  2395. }
  2396. bool isTouchEvent() noexcept
  2397. {
  2398. if (registerTouchWindow == nullptr)
  2399. return false;
  2400. // Relevant info about touch/pen detection flags:
  2401. // https://msdn.microsoft.com/en-us/library/windows/desktop/ms703320(v=vs.85).aspx
  2402. // http://www.petertissen.de/?p=4
  2403. return ((uint32_t) GetMessageExtraInfo() & 0xFFFFFF80 /*SIGNATURE_MASK*/) == 0xFF515780 /*MI_WP_SIGNATURE*/;
  2404. }
  2405. static bool areOtherTouchSourcesActive()
  2406. {
  2407. for (auto& ms : Desktop::getInstance().getMouseSources())
  2408. if (ms.isDragging() && (ms.getType() == MouseInputSource::InputSourceType::touch
  2409. || ms.getType() == MouseInputSource::InputSourceType::pen))
  2410. return true;
  2411. return false;
  2412. }
  2413. void doMouseMove (Point<float> position, bool isMouseDownEvent)
  2414. {
  2415. ModifierKeys modsToSend (ModifierKeys::currentModifiers);
  2416. // this will be handled by WM_TOUCH
  2417. if (isTouchEvent() || areOtherTouchSourcesActive())
  2418. return;
  2419. if (! isMouseOver)
  2420. {
  2421. isMouseOver = true;
  2422. // This avoids a rare stuck-button problem when focus is lost unexpectedly, but must
  2423. // not be called as part of a move, in case it's actually a mouse-drag from another
  2424. // app which ends up here when we get focus before the mouse is released..
  2425. if (isMouseDownEvent && getNativeRealtimeModifiers != nullptr)
  2426. getNativeRealtimeModifiers();
  2427. updateKeyModifiers();
  2428. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  2429. if (modProvider != nullptr)
  2430. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withFlags (modProvider->getWin32Modifiers());
  2431. #endif
  2432. TRACKMOUSEEVENT tme;
  2433. tme.cbSize = sizeof (tme);
  2434. tme.dwFlags = TME_LEAVE;
  2435. tme.hwndTrack = hwnd;
  2436. tme.dwHoverTime = 0;
  2437. if (! TrackMouseEvent (&tme))
  2438. jassertfalse;
  2439. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  2440. }
  2441. else if (! isDragging)
  2442. {
  2443. if (! contains (position.roundToInt(), false))
  2444. return;
  2445. }
  2446. static uint32 lastMouseTime = 0;
  2447. static auto minTimeBetweenMouses = getMinTimeBetweenMouseMoves();
  2448. auto now = Time::getMillisecondCounter();
  2449. if (! Desktop::getInstance().getMainMouseSource().isDragging())
  2450. modsToSend = modsToSend.withoutMouseButtons();
  2451. if (now >= lastMouseTime + minTimeBetweenMouses)
  2452. {
  2453. lastMouseTime = now;
  2454. doMouseEvent (position, MouseInputSource::defaultPressure,
  2455. MouseInputSource::defaultOrientation, modsToSend);
  2456. }
  2457. }
  2458. void doMouseDown (Point<float> position, const WPARAM wParam)
  2459. {
  2460. // this will be handled by WM_TOUCH
  2461. if (isTouchEvent() || areOtherTouchSourcesActive())
  2462. return;
  2463. if (GetCapture() != hwnd)
  2464. SetCapture (hwnd);
  2465. doMouseMove (position, true);
  2466. if (isValidPeer (this))
  2467. {
  2468. updateModifiersFromWParam (wParam);
  2469. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  2470. if (modProvider != nullptr)
  2471. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withFlags (modProvider->getWin32Modifiers());
  2472. #endif
  2473. isDragging = true;
  2474. doMouseEvent (position, MouseInputSource::defaultPressure);
  2475. }
  2476. }
  2477. void doMouseUp (Point<float> position, const WPARAM wParam)
  2478. {
  2479. // this will be handled by WM_TOUCH
  2480. if (isTouchEvent() || areOtherTouchSourcesActive())
  2481. return;
  2482. updateModifiersFromWParam (wParam);
  2483. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  2484. if (modProvider != nullptr)
  2485. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withFlags (modProvider->getWin32Modifiers());
  2486. #endif
  2487. const bool wasDragging = isDragging;
  2488. isDragging = false;
  2489. // release the mouse capture if the user has released all buttons
  2490. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  2491. ReleaseCapture();
  2492. // NB: under some circumstances (e.g. double-clicking a native title bar), a mouse-up can
  2493. // arrive without a mouse-down, so in that case we need to avoid sending a message.
  2494. if (wasDragging)
  2495. doMouseEvent (position, MouseInputSource::defaultPressure);
  2496. }
  2497. void doCaptureChanged()
  2498. {
  2499. if (constrainerIsResizing)
  2500. {
  2501. if (constrainer != nullptr)
  2502. constrainer->resizeEnd();
  2503. constrainerIsResizing = false;
  2504. }
  2505. if (isDragging)
  2506. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  2507. }
  2508. void doMouseExit()
  2509. {
  2510. isMouseOver = false;
  2511. if (! areOtherTouchSourcesActive())
  2512. doMouseEvent (getCurrentMousePos(), MouseInputSource::defaultPressure);
  2513. }
  2514. ComponentPeer* findPeerUnderMouse (Point<float>& localPos)
  2515. {
  2516. auto currentMousePos = getPOINTFromLParam ((LPARAM) GetMessagePos());
  2517. // Because Windows stupidly sends all wheel events to the window with the keyboard
  2518. // focus, we have to redirect them here according to the mouse pos..
  2519. auto* peer = getOwnerOfWindow (WindowFromPoint (currentMousePos));
  2520. if (peer == nullptr)
  2521. peer = this;
  2522. localPos = peer->globalToLocal (convertPhysicalScreenPointToLogical (pointFromPOINT (currentMousePos), hwnd).toFloat());
  2523. return peer;
  2524. }
  2525. static MouseInputSource::InputSourceType getPointerType (WPARAM wParam)
  2526. {
  2527. if (getPointerTypeFunction != nullptr)
  2528. {
  2529. POINTER_INPUT_TYPE pointerType;
  2530. if (getPointerTypeFunction (GET_POINTERID_WPARAM (wParam), &pointerType))
  2531. {
  2532. if (pointerType == 2)
  2533. return MouseInputSource::InputSourceType::touch;
  2534. if (pointerType == 3)
  2535. return MouseInputSource::InputSourceType::pen;
  2536. }
  2537. }
  2538. return MouseInputSource::InputSourceType::mouse;
  2539. }
  2540. void doMouseWheel (const WPARAM wParam, const bool isVertical)
  2541. {
  2542. updateKeyModifiers();
  2543. const float amount = jlimit (-1000.0f, 1000.0f, 0.5f * (short) HIWORD (wParam));
  2544. MouseWheelDetails wheel;
  2545. wheel.deltaX = isVertical ? 0.0f : amount / -256.0f;
  2546. wheel.deltaY = isVertical ? amount / 256.0f : 0.0f;
  2547. wheel.isReversed = false;
  2548. wheel.isSmooth = false;
  2549. wheel.isInertial = false;
  2550. Point<float> localPos;
  2551. if (auto* peer = findPeerUnderMouse (localPos))
  2552. peer->handleMouseWheel (getPointerType (wParam), localPos, getMouseEventTime(), wheel);
  2553. }
  2554. bool doGestureEvent (LPARAM lParam)
  2555. {
  2556. GESTUREINFO gi;
  2557. zerostruct (gi);
  2558. gi.cbSize = sizeof (gi);
  2559. if (getGestureInfo != nullptr && getGestureInfo ((HGESTUREINFO) lParam, &gi))
  2560. {
  2561. updateKeyModifiers();
  2562. Point<float> localPos;
  2563. if (auto* peer = findPeerUnderMouse (localPos))
  2564. {
  2565. switch (gi.dwID)
  2566. {
  2567. case 3: /*GID_ZOOM*/
  2568. if (gi.dwFlags != 1 /*GF_BEGIN*/ && lastMagnifySize > 0)
  2569. peer->handleMagnifyGesture (MouseInputSource::InputSourceType::touch, localPos, getMouseEventTime(),
  2570. (float) ((double) gi.ullArguments / (double) lastMagnifySize));
  2571. lastMagnifySize = gi.ullArguments;
  2572. return true;
  2573. case 4: /*GID_PAN*/
  2574. case 5: /*GID_ROTATE*/
  2575. case 6: /*GID_TWOFINGERTAP*/
  2576. case 7: /*GID_PRESSANDTAP*/
  2577. default:
  2578. break;
  2579. }
  2580. }
  2581. }
  2582. return false;
  2583. }
  2584. LRESULT doTouchEvent (const int numInputs, HTOUCHINPUT eventHandle)
  2585. {
  2586. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  2587. if (auto* parent = getOwnerOfWindow (GetParent (hwnd)))
  2588. if (parent != this)
  2589. return parent->doTouchEvent (numInputs, eventHandle);
  2590. HeapBlock<TOUCHINPUT> inputInfo (numInputs);
  2591. if (getTouchInputInfo (eventHandle, (UINT) numInputs, inputInfo, sizeof (TOUCHINPUT)))
  2592. {
  2593. for (int i = 0; i < numInputs; ++i)
  2594. {
  2595. auto flags = inputInfo[i].dwFlags;
  2596. if ((flags & (TOUCHEVENTF_DOWN | TOUCHEVENTF_MOVE | TOUCHEVENTF_UP)) != 0)
  2597. if (! handleTouchInput (inputInfo[i], (flags & TOUCHEVENTF_DOWN) != 0, (flags & TOUCHEVENTF_UP) != 0))
  2598. return 0; // abandon method if this window was deleted by the callback
  2599. }
  2600. }
  2601. closeTouchInputHandle (eventHandle);
  2602. return 0;
  2603. }
  2604. bool handleTouchInput (const TOUCHINPUT& touch, const bool isDown, const bool isUp,
  2605. const float touchPressure = MouseInputSource::defaultPressure,
  2606. const float orientation = 0.0f)
  2607. {
  2608. auto isCancel = false;
  2609. const auto touchIndex = currentTouches.getIndexOfTouch (this, touch.dwID);
  2610. const auto time = getMouseEventTime();
  2611. const auto pos = globalToLocal (convertPhysicalScreenPointToLogical (pointFromPOINT ({ roundToInt (touch.x / 100.0f),
  2612. roundToInt (touch.y / 100.0f) }), hwnd).toFloat());
  2613. const auto pressure = touchPressure;
  2614. auto modsToSend = ModifierKeys::currentModifiers;
  2615. if (isDown)
  2616. {
  2617. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  2618. modsToSend = ModifierKeys::currentModifiers;
  2619. // this forces a mouse-enter/up event, in case for some reason we didn't get a mouse-up before.
  2620. handleMouseEvent (MouseInputSource::InputSourceType::touch, pos, modsToSend.withoutMouseButtons(),
  2621. pressure, orientation, time, {}, touchIndex);
  2622. if (! isValidPeer (this)) // (in case this component was deleted by the event)
  2623. return false;
  2624. }
  2625. else if (isUp)
  2626. {
  2627. modsToSend = modsToSend.withoutMouseButtons();
  2628. ModifierKeys::currentModifiers = modsToSend;
  2629. currentTouches.clearTouch (touchIndex);
  2630. if (! currentTouches.areAnyTouchesActive())
  2631. isCancel = true;
  2632. }
  2633. else
  2634. {
  2635. modsToSend = ModifierKeys::currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  2636. }
  2637. handleMouseEvent (MouseInputSource::InputSourceType::touch, pos, modsToSend,
  2638. pressure, orientation, time, {}, touchIndex);
  2639. if (! isValidPeer (this))
  2640. return false;
  2641. if (isUp)
  2642. {
  2643. handleMouseEvent (MouseInputSource::InputSourceType::touch, MouseInputSource::offscreenMousePos, ModifierKeys::currentModifiers.withoutMouseButtons(),
  2644. pressure, orientation, time, {}, touchIndex);
  2645. if (! isValidPeer (this))
  2646. return false;
  2647. if (isCancel)
  2648. {
  2649. currentTouches.clear();
  2650. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons();
  2651. }
  2652. }
  2653. return true;
  2654. }
  2655. bool handlePointerInput (WPARAM wParam, LPARAM lParam, const bool isDown, const bool isUp)
  2656. {
  2657. if (! canUsePointerAPI)
  2658. return false;
  2659. auto pointerType = getPointerType (wParam);
  2660. if (pointerType == MouseInputSource::InputSourceType::touch)
  2661. {
  2662. POINTER_TOUCH_INFO touchInfo;
  2663. if (! getPointerTouchInfo (GET_POINTERID_WPARAM (wParam), &touchInfo))
  2664. return false;
  2665. const auto pressure = touchInfo.touchMask & TOUCH_MASK_PRESSURE ? static_cast<float> (touchInfo.pressure)
  2666. : MouseInputSource::defaultPressure;
  2667. const auto orientation = touchInfo.touchMask & TOUCH_MASK_ORIENTATION ? degreesToRadians (static_cast<float> (touchInfo.orientation))
  2668. : MouseInputSource::defaultOrientation;
  2669. if (! handleTouchInput (emulateTouchEventFromPointer (touchInfo.pointerInfo.ptPixelLocationRaw, wParam),
  2670. isDown, isUp, pressure, orientation))
  2671. return false;
  2672. }
  2673. else if (pointerType == MouseInputSource::InputSourceType::pen)
  2674. {
  2675. POINTER_PEN_INFO penInfo;
  2676. if (! getPointerPenInfo (GET_POINTERID_WPARAM (wParam), &penInfo))
  2677. return false;
  2678. const auto pressure = (penInfo.penMask & PEN_MASK_PRESSURE) ? (float) penInfo.pressure / 1024.0f : MouseInputSource::defaultPressure;
  2679. if (! handlePenInput (penInfo, globalToLocal (convertPhysicalScreenPointToLogical (pointFromPOINT (getPOINTFromLParam (lParam)), hwnd).toFloat()),
  2680. pressure, isDown, isUp))
  2681. return false;
  2682. }
  2683. else
  2684. {
  2685. return false;
  2686. }
  2687. return true;
  2688. }
  2689. TOUCHINPUT emulateTouchEventFromPointer (POINT p, WPARAM wParam)
  2690. {
  2691. TOUCHINPUT touchInput;
  2692. touchInput.dwID = GET_POINTERID_WPARAM (wParam);
  2693. touchInput.x = p.x * 100;
  2694. touchInput.y = p.y * 100;
  2695. return touchInput;
  2696. }
  2697. bool handlePenInput (POINTER_PEN_INFO penInfo, Point<float> pos, const float pressure, bool isDown, bool isUp)
  2698. {
  2699. const auto time = getMouseEventTime();
  2700. ModifierKeys modsToSend (ModifierKeys::currentModifiers);
  2701. PenDetails penDetails;
  2702. penDetails.rotation = (penInfo.penMask & PEN_MASK_ROTATION) ? degreesToRadians (static_cast<float> (penInfo.rotation)) : MouseInputSource::defaultRotation;
  2703. penDetails.tiltX = (penInfo.penMask & PEN_MASK_TILT_X) ? (float) penInfo.tiltX / 90.0f : MouseInputSource::defaultTiltX;
  2704. penDetails.tiltY = (penInfo.penMask & PEN_MASK_TILT_Y) ? (float) penInfo.tiltY / 90.0f : MouseInputSource::defaultTiltY;
  2705. auto pInfoFlags = penInfo.pointerInfo.pointerFlags;
  2706. if ((pInfoFlags & POINTER_FLAG_FIRSTBUTTON) != 0)
  2707. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  2708. else if ((pInfoFlags & POINTER_FLAG_SECONDBUTTON) != 0)
  2709. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::rightButtonModifier);
  2710. if (isDown)
  2711. {
  2712. modsToSend = ModifierKeys::currentModifiers;
  2713. // this forces a mouse-enter/up event, in case for some reason we didn't get a mouse-up before.
  2714. handleMouseEvent (MouseInputSource::InputSourceType::pen, pos, modsToSend.withoutMouseButtons(),
  2715. pressure, MouseInputSource::defaultOrientation, time, penDetails);
  2716. if (! isValidPeer (this)) // (in case this component was deleted by the event)
  2717. return false;
  2718. }
  2719. else if (isUp || ! (pInfoFlags & POINTER_FLAG_INCONTACT))
  2720. {
  2721. modsToSend = modsToSend.withoutMouseButtons();
  2722. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons();
  2723. }
  2724. handleMouseEvent (MouseInputSource::InputSourceType::pen, pos, modsToSend, pressure,
  2725. MouseInputSource::defaultOrientation, time, penDetails);
  2726. if (! isValidPeer (this)) // (in case this component was deleted by the event)
  2727. return false;
  2728. if (isUp)
  2729. {
  2730. handleMouseEvent (MouseInputSource::InputSourceType::pen, MouseInputSource::offscreenMousePos, ModifierKeys::currentModifiers,
  2731. pressure, MouseInputSource::defaultOrientation, time, penDetails);
  2732. if (! isValidPeer (this))
  2733. return false;
  2734. }
  2735. return true;
  2736. }
  2737. //==============================================================================
  2738. void sendModifierKeyChangeIfNeeded()
  2739. {
  2740. if (modifiersAtLastCallback != ModifierKeys::currentModifiers)
  2741. {
  2742. modifiersAtLastCallback = ModifierKeys::currentModifiers;
  2743. handleModifierKeysChange();
  2744. }
  2745. }
  2746. bool doKeyUp (const WPARAM key)
  2747. {
  2748. updateKeyModifiers();
  2749. switch (key)
  2750. {
  2751. case VK_SHIFT:
  2752. case VK_CONTROL:
  2753. case VK_MENU:
  2754. case VK_CAPITAL:
  2755. case VK_LWIN:
  2756. case VK_RWIN:
  2757. case VK_APPS:
  2758. case VK_NUMLOCK:
  2759. case VK_SCROLL:
  2760. case VK_LSHIFT:
  2761. case VK_RSHIFT:
  2762. case VK_LCONTROL:
  2763. case VK_LMENU:
  2764. case VK_RCONTROL:
  2765. case VK_RMENU:
  2766. sendModifierKeyChangeIfNeeded();
  2767. }
  2768. return handleKeyUpOrDown (false)
  2769. || Component::getCurrentlyModalComponent() != nullptr;
  2770. }
  2771. bool doKeyDown (const WPARAM key)
  2772. {
  2773. updateKeyModifiers();
  2774. bool used = false;
  2775. switch (key)
  2776. {
  2777. case VK_SHIFT:
  2778. case VK_LSHIFT:
  2779. case VK_RSHIFT:
  2780. case VK_CONTROL:
  2781. case VK_LCONTROL:
  2782. case VK_RCONTROL:
  2783. case VK_MENU:
  2784. case VK_LMENU:
  2785. case VK_RMENU:
  2786. case VK_LWIN:
  2787. case VK_RWIN:
  2788. case VK_CAPITAL:
  2789. case VK_NUMLOCK:
  2790. case VK_SCROLL:
  2791. case VK_APPS:
  2792. used = handleKeyUpOrDown (true);
  2793. sendModifierKeyChangeIfNeeded();
  2794. break;
  2795. case VK_LEFT:
  2796. case VK_RIGHT:
  2797. case VK_UP:
  2798. case VK_DOWN:
  2799. case VK_PRIOR:
  2800. case VK_NEXT:
  2801. case VK_HOME:
  2802. case VK_END:
  2803. case VK_DELETE:
  2804. case VK_INSERT:
  2805. case VK_F1:
  2806. case VK_F2:
  2807. case VK_F3:
  2808. case VK_F4:
  2809. case VK_F5:
  2810. case VK_F6:
  2811. case VK_F7:
  2812. case VK_F8:
  2813. case VK_F9:
  2814. case VK_F10:
  2815. case VK_F11:
  2816. case VK_F12:
  2817. case VK_F13:
  2818. case VK_F14:
  2819. case VK_F15:
  2820. case VK_F16:
  2821. case VK_F17:
  2822. case VK_F18:
  2823. case VK_F19:
  2824. case VK_F20:
  2825. case VK_F21:
  2826. case VK_F22:
  2827. case VK_F23:
  2828. case VK_F24:
  2829. used = handleKeyUpOrDown (true);
  2830. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  2831. break;
  2832. default:
  2833. used = handleKeyUpOrDown (true);
  2834. {
  2835. MSG msg;
  2836. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  2837. {
  2838. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  2839. // manually generate the key-press event that matches this key-down.
  2840. const UINT keyChar = MapVirtualKey ((UINT) key, 2);
  2841. const UINT scanCode = MapVirtualKey ((UINT) key, 0);
  2842. BYTE keyState[256];
  2843. [[maybe_unused]] const auto state = GetKeyboardState (keyState);
  2844. WCHAR text[16] = { 0 };
  2845. if (ToUnicode ((UINT) key, scanCode, keyState, text, 8, 0) != 1)
  2846. text[0] = 0;
  2847. used = handleKeyPress ((int) LOWORD (keyChar), (juce_wchar) text[0]) || used;
  2848. }
  2849. }
  2850. break;
  2851. }
  2852. return used || (Component::getCurrentlyModalComponent() != nullptr);
  2853. }
  2854. bool doKeyChar (int key, const LPARAM flags)
  2855. {
  2856. updateKeyModifiers();
  2857. auto textChar = (juce_wchar) key;
  2858. const int virtualScanCode = (flags >> 16) & 0xff;
  2859. if (key >= '0' && key <= '9')
  2860. {
  2861. switch (virtualScanCode) // check for a numeric keypad scan-code
  2862. {
  2863. case 0x52:
  2864. case 0x4f:
  2865. case 0x50:
  2866. case 0x51:
  2867. case 0x4b:
  2868. case 0x4c:
  2869. case 0x4d:
  2870. case 0x47:
  2871. case 0x48:
  2872. case 0x49:
  2873. key = (key - '0') + KeyPress::numberPad0;
  2874. break;
  2875. default:
  2876. break;
  2877. }
  2878. }
  2879. else
  2880. {
  2881. // convert the scan code to an unmodified character code..
  2882. const UINT virtualKey = MapVirtualKey ((UINT) virtualScanCode, 1);
  2883. UINT keyChar = MapVirtualKey (virtualKey, 2);
  2884. keyChar = LOWORD (keyChar);
  2885. if (keyChar != 0)
  2886. key = (int) keyChar;
  2887. // avoid sending junk text characters for some control-key combinations
  2888. if (textChar < ' ' && ModifierKeys::currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  2889. textChar = 0;
  2890. }
  2891. return handleKeyPress (key, textChar);
  2892. }
  2893. void forwardMessageToParent (UINT message, WPARAM wParam, LPARAM lParam) const
  2894. {
  2895. if (HWND parentH = GetParent (hwnd))
  2896. PostMessage (parentH, message, wParam, lParam);
  2897. }
  2898. bool doAppCommand (const LPARAM lParam)
  2899. {
  2900. int key = 0;
  2901. switch (GET_APPCOMMAND_LPARAM (lParam))
  2902. {
  2903. case APPCOMMAND_MEDIA_PLAY_PAUSE: key = KeyPress::playKey; break;
  2904. case APPCOMMAND_MEDIA_STOP: key = KeyPress::stopKey; break;
  2905. case APPCOMMAND_MEDIA_NEXTTRACK: key = KeyPress::fastForwardKey; break;
  2906. case APPCOMMAND_MEDIA_PREVIOUSTRACK: key = KeyPress::rewindKey; break;
  2907. default: break;
  2908. }
  2909. if (key != 0)
  2910. {
  2911. updateKeyModifiers();
  2912. if (hwnd == GetActiveWindow())
  2913. return handleKeyPress (key, 0);
  2914. }
  2915. return false;
  2916. }
  2917. bool isConstrainedNativeWindow() const
  2918. {
  2919. return constrainer != nullptr
  2920. && (styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable)
  2921. && ! isKioskMode();
  2922. }
  2923. Rectangle<int> getCurrentScaledBounds() const
  2924. {
  2925. return ScalingHelpers::unscaledScreenPosToScaled (component, windowBorder.addedTo (ScalingHelpers::scaledScreenPosToUnscaled (component, component.getBounds())));
  2926. }
  2927. LRESULT handleSizeConstraining (RECT& r, const WPARAM wParam)
  2928. {
  2929. if (isConstrainedNativeWindow())
  2930. {
  2931. const auto logicalBounds = convertPhysicalScreenRectangleToLogical (rectangleFromRECT (r).toFloat(), hwnd);
  2932. auto pos = ScalingHelpers::unscaledScreenPosToScaled (component, logicalBounds).toNearestInt();
  2933. const auto original = getCurrentScaledBounds();
  2934. constrainer->checkBounds (pos, original,
  2935. Desktop::getInstance().getDisplays().getTotalBounds (true),
  2936. wParam == WMSZ_TOP || wParam == WMSZ_TOPLEFT || wParam == WMSZ_TOPRIGHT,
  2937. wParam == WMSZ_LEFT || wParam == WMSZ_TOPLEFT || wParam == WMSZ_BOTTOMLEFT,
  2938. wParam == WMSZ_BOTTOM || wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_BOTTOMRIGHT,
  2939. wParam == WMSZ_RIGHT || wParam == WMSZ_TOPRIGHT || wParam == WMSZ_BOTTOMRIGHT);
  2940. r = RECTFromRectangle (convertLogicalScreenRectangleToPhysical (ScalingHelpers::scaledScreenPosToUnscaled (component, pos.toFloat()).toNearestInt(), hwnd));
  2941. }
  2942. return TRUE;
  2943. }
  2944. LRESULT handlePositionChanging (WINDOWPOS& wp)
  2945. {
  2946. if (isConstrainedNativeWindow() && ! isFullScreen())
  2947. {
  2948. if ((wp.flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE)
  2949. && (wp.x > -32000 && wp.y > -32000)
  2950. && ! Component::isMouseButtonDownAnywhere())
  2951. {
  2952. const auto logicalBounds = convertPhysicalScreenRectangleToLogical (rectangleFromRECT ({ wp.x, wp.y, wp.x + wp.cx, wp.y + wp.cy }).toFloat(), hwnd);
  2953. auto pos = ScalingHelpers::unscaledScreenPosToScaled (component, logicalBounds).toNearestInt();
  2954. const auto original = getCurrentScaledBounds();
  2955. constrainer->checkBounds (pos, original,
  2956. Desktop::getInstance().getDisplays().getTotalBounds (true),
  2957. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  2958. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  2959. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  2960. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  2961. auto physicalBounds = convertLogicalScreenRectangleToPhysical (ScalingHelpers::scaledScreenPosToUnscaled (component, pos.toFloat()), hwnd);
  2962. auto getNewPositionIfNotRoundingError = [] (int posIn, float newPos)
  2963. {
  2964. return (std::abs ((float) posIn - newPos) >= 1.0f) ? roundToInt (newPos) : posIn;
  2965. };
  2966. wp.x = getNewPositionIfNotRoundingError (wp.x, physicalBounds.getX());
  2967. wp.y = getNewPositionIfNotRoundingError (wp.y, physicalBounds.getY());
  2968. wp.cx = getNewPositionIfNotRoundingError (wp.cx, physicalBounds.getWidth());
  2969. wp.cy = getNewPositionIfNotRoundingError (wp.cy, physicalBounds.getHeight());
  2970. }
  2971. }
  2972. if (((wp.flags & SWP_SHOWWINDOW) != 0 && ! component.isVisible()))
  2973. component.setVisible (true);
  2974. else if (((wp.flags & SWP_HIDEWINDOW) != 0 && component.isVisible()))
  2975. component.setVisible (false);
  2976. return 0;
  2977. }
  2978. enum class ForceRefreshDispatcher
  2979. {
  2980. no,
  2981. yes
  2982. };
  2983. void updateCurrentMonitorAndRefreshVBlankDispatcher (ForceRefreshDispatcher force = ForceRefreshDispatcher::no)
  2984. {
  2985. auto monitor = MonitorFromWindow (hwnd, MONITOR_DEFAULTTONULL);
  2986. if (std::exchange (currentMonitor, monitor) != monitor || force == ForceRefreshDispatcher::yes)
  2987. VBlankDispatcher::getInstance()->updateDisplay (*this, currentMonitor);
  2988. }
  2989. bool handlePositionChanged()
  2990. {
  2991. auto pos = getCurrentMousePos();
  2992. if (contains (pos.roundToInt(), false))
  2993. {
  2994. const ScopedValueSetter<bool> scope (inHandlePositionChanged, true);
  2995. if (! areOtherTouchSourcesActive())
  2996. doMouseEvent (pos, MouseInputSource::defaultPressure);
  2997. if (! isValidPeer (this))
  2998. return true;
  2999. }
  3000. handleMovedOrResized();
  3001. updateCurrentMonitorAndRefreshVBlankDispatcher();
  3002. return ! dontRepaint; // to allow non-accelerated openGL windows to draw themselves correctly.
  3003. }
  3004. //==============================================================================
  3005. LRESULT handleDPIChanging (int newDPI, RECT newRect)
  3006. {
  3007. // Sometimes, windows that should not be automatically scaled (secondary windows in plugins)
  3008. // are sent WM_DPICHANGED. The size suggested by the OS is incorrect for our unscaled
  3009. // window, so we should ignore it.
  3010. if (! isPerMonitorDPIAwareWindow (hwnd))
  3011. return 0;
  3012. const auto newScale = (double) newDPI / USER_DEFAULT_SCREEN_DPI;
  3013. if (approximatelyEqual (scaleFactor, newScale))
  3014. return 0;
  3015. scaleFactor = newScale;
  3016. {
  3017. const ScopedValueSetter<bool> setter (inDpiChange, true);
  3018. SetWindowPos (hwnd,
  3019. nullptr,
  3020. newRect.left,
  3021. newRect.top,
  3022. newRect.right - newRect.left,
  3023. newRect.bottom - newRect.top,
  3024. SWP_NOZORDER | SWP_NOACTIVATE);
  3025. }
  3026. // This is to handle reentrancy. If responding to a DPI change triggers further DPI changes,
  3027. // we should only notify listeners and resize windows once all of the DPI changes have
  3028. // resolved.
  3029. if (inDpiChange)
  3030. {
  3031. // Danger! Re-entrant call to handleDPIChanging.
  3032. // Please report this issue on the JUCE forum, along with instructions
  3033. // so that a JUCE developer can reproduce the issue.
  3034. jassertfalse;
  3035. return 0;
  3036. }
  3037. updateShadower();
  3038. InvalidateRect (hwnd, nullptr, FALSE);
  3039. scaleFactorListeners.call ([this] (ScaleFactorListener& l) { l.nativeScaleFactorChanged (scaleFactor); });
  3040. return 0;
  3041. }
  3042. //==============================================================================
  3043. void handleAppActivation (const WPARAM wParam)
  3044. {
  3045. modifiersAtLastCallback = -1;
  3046. updateKeyModifiers();
  3047. if (isMinimised())
  3048. {
  3049. component.repaint();
  3050. handleMovedOrResized();
  3051. if (! isValidPeer (this))
  3052. return;
  3053. }
  3054. auto* underMouse = component.getComponentAt (component.getMouseXYRelative());
  3055. if (underMouse == nullptr)
  3056. underMouse = &component;
  3057. if (underMouse->isCurrentlyBlockedByAnotherModalComponent())
  3058. {
  3059. if (LOWORD (wParam) == WA_CLICKACTIVE)
  3060. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  3061. else
  3062. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  3063. }
  3064. else
  3065. {
  3066. handleBroughtToFront();
  3067. }
  3068. }
  3069. void handlePowerBroadcast (WPARAM wParam)
  3070. {
  3071. if (auto* app = JUCEApplicationBase::getInstance())
  3072. {
  3073. switch (wParam)
  3074. {
  3075. case PBT_APMSUSPEND: app->suspended(); break;
  3076. case PBT_APMQUERYSUSPENDFAILED:
  3077. case PBT_APMRESUMECRITICAL:
  3078. case PBT_APMRESUMESUSPEND:
  3079. case PBT_APMRESUMEAUTOMATIC: app->resumed(); break;
  3080. default: break;
  3081. }
  3082. }
  3083. }
  3084. void handleLeftClickInNCArea (WPARAM wParam)
  3085. {
  3086. if (! sendInputAttemptWhenModalMessage())
  3087. {
  3088. switch (wParam)
  3089. {
  3090. case HTBOTTOM:
  3091. case HTBOTTOMLEFT:
  3092. case HTBOTTOMRIGHT:
  3093. case HTGROWBOX:
  3094. case HTLEFT:
  3095. case HTRIGHT:
  3096. case HTTOP:
  3097. case HTTOPLEFT:
  3098. case HTTOPRIGHT:
  3099. if (isConstrainedNativeWindow())
  3100. {
  3101. constrainerIsResizing = true;
  3102. constrainer->resizeStart();
  3103. }
  3104. break;
  3105. default:
  3106. break;
  3107. }
  3108. }
  3109. }
  3110. void initialiseSysMenu (HMENU menu) const
  3111. {
  3112. if (! hasTitleBar())
  3113. {
  3114. if (isFullScreen())
  3115. {
  3116. EnableMenuItem (menu, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  3117. EnableMenuItem (menu, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  3118. }
  3119. else if (! isMinimised())
  3120. {
  3121. EnableMenuItem (menu, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  3122. }
  3123. }
  3124. }
  3125. void doSettingChange()
  3126. {
  3127. forceDisplayUpdate();
  3128. if (fullScreen && ! isMinimised())
  3129. setWindowPos (hwnd, ScalingHelpers::scaledScreenPosToUnscaled (component, Desktop::getInstance().getDisplays()
  3130. .getDisplayForRect (component.getScreenBounds())->userArea),
  3131. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  3132. auto* dispatcher = VBlankDispatcher::getInstance();
  3133. dispatcher->reconfigureDisplays();
  3134. updateCurrentMonitorAndRefreshVBlankDispatcher (ForceRefreshDispatcher::yes);
  3135. }
  3136. //==============================================================================
  3137. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  3138. void setModifierKeyProvider (ModifierKeyProvider* provider) override
  3139. {
  3140. modProvider = provider;
  3141. }
  3142. void removeModifierKeyProvider() override
  3143. {
  3144. modProvider = nullptr;
  3145. }
  3146. #endif
  3147. public:
  3148. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  3149. {
  3150. // Ensure that non-client areas are scaled for per-monitor DPI awareness v1 - can't
  3151. // do this in peerWindowProc as we have no window at this point
  3152. if (message == WM_NCCREATE && enableNonClientDPIScaling != nullptr)
  3153. enableNonClientDPIScaling (h);
  3154. if (auto* peer = getOwnerOfWindow (h))
  3155. {
  3156. jassert (isValidPeer (peer));
  3157. return peer->peerWindowProc (h, message, wParam, lParam);
  3158. }
  3159. return DefWindowProcW (h, message, wParam, lParam);
  3160. }
  3161. private:
  3162. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  3163. {
  3164. auto& mm = *MessageManager::getInstance();
  3165. if (mm.currentThreadHasLockedMessageManager())
  3166. return callback (userData);
  3167. return mm.callFunctionOnMessageThread (callback, userData);
  3168. }
  3169. static POINT getPOINTFromLParam (LPARAM lParam) noexcept
  3170. {
  3171. return { GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam) };
  3172. }
  3173. Point<float> getPointFromLocalLParam (LPARAM lParam) noexcept
  3174. {
  3175. auto p = pointFromPOINT (getPOINTFromLParam (lParam));
  3176. if (isPerMonitorDPIAwareWindow (hwnd))
  3177. {
  3178. // LPARAM is relative to this window's top-left but may be on a different monitor so we need to calculate the
  3179. // physical screen position and then convert this to local logical coordinates
  3180. auto r = getWindowScreenRect (hwnd);
  3181. return globalToLocal (Desktop::getInstance().getDisplays().physicalToLogical (pointFromPOINT ({ r.left + p.x + roundToInt (windowBorder.getLeft() * scaleFactor),
  3182. r.top + p.y + roundToInt (windowBorder.getTop() * scaleFactor) })).toFloat());
  3183. }
  3184. return p.toFloat();
  3185. }
  3186. Point<float> getCurrentMousePos() noexcept
  3187. {
  3188. return globalToLocal (convertPhysicalScreenPointToLogical (pointFromPOINT (getPOINTFromLParam ((LPARAM) GetMessagePos())), hwnd).toFloat());
  3189. }
  3190. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  3191. {
  3192. switch (message)
  3193. {
  3194. //==============================================================================
  3195. case WM_NCHITTEST:
  3196. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  3197. return HTTRANSPARENT;
  3198. if (! hasTitleBar())
  3199. return HTCLIENT;
  3200. break;
  3201. //==============================================================================
  3202. case WM_PAINT:
  3203. handlePaintMessage();
  3204. return 0;
  3205. case WM_NCPAINT:
  3206. handlePaintMessage(); // this must be done, even with native titlebars, or there are rendering artifacts.
  3207. if (hasTitleBar())
  3208. break; // let the DefWindowProc handle drawing the frame.
  3209. return 0;
  3210. case WM_ERASEBKGND:
  3211. case WM_NCCALCSIZE:
  3212. if (hasTitleBar())
  3213. break;
  3214. return 1;
  3215. //==============================================================================
  3216. case WM_POINTERUPDATE:
  3217. if (handlePointerInput (wParam, lParam, false, false))
  3218. return 0;
  3219. break;
  3220. case WM_POINTERDOWN:
  3221. if (handlePointerInput (wParam, lParam, true, false))
  3222. return 0;
  3223. break;
  3224. case WM_POINTERUP:
  3225. if (handlePointerInput (wParam, lParam, false, true))
  3226. return 0;
  3227. break;
  3228. //==============================================================================
  3229. case WM_MOUSEMOVE: doMouseMove (getPointFromLocalLParam (lParam), false); return 0;
  3230. case WM_POINTERLEAVE:
  3231. case WM_MOUSELEAVE: doMouseExit(); return 0;
  3232. case WM_LBUTTONDOWN:
  3233. case WM_MBUTTONDOWN:
  3234. case WM_RBUTTONDOWN: doMouseDown (getPointFromLocalLParam (lParam), wParam); return 0;
  3235. case WM_LBUTTONUP:
  3236. case WM_MBUTTONUP:
  3237. case WM_RBUTTONUP: doMouseUp (getPointFromLocalLParam (lParam), wParam); return 0;
  3238. case WM_POINTERWHEEL:
  3239. case 0x020A: /* WM_MOUSEWHEEL */ doMouseWheel (wParam, true); return 0;
  3240. case WM_POINTERHWHEEL:
  3241. case 0x020E: /* WM_MOUSEHWHEEL */ doMouseWheel (wParam, false); return 0;
  3242. case WM_CAPTURECHANGED: doCaptureChanged(); return 0;
  3243. case WM_NCPOINTERUPDATE:
  3244. case WM_NCMOUSEMOVE:
  3245. if (hasTitleBar())
  3246. break;
  3247. return 0;
  3248. case WM_TOUCH:
  3249. if (getTouchInputInfo != nullptr)
  3250. return doTouchEvent ((int) wParam, (HTOUCHINPUT) lParam);
  3251. break;
  3252. case 0x119: /* WM_GESTURE */
  3253. if (doGestureEvent (lParam))
  3254. return 0;
  3255. break;
  3256. //==============================================================================
  3257. case WM_SIZING: return handleSizeConstraining (*(RECT*) lParam, wParam);
  3258. case WM_WINDOWPOSCHANGING: return handlePositionChanging (*(WINDOWPOS*) lParam);
  3259. case 0x2e0: /* WM_DPICHANGED */ return handleDPIChanging ((int) HIWORD (wParam), *(RECT*) lParam);
  3260. case WM_WINDOWPOSCHANGED:
  3261. {
  3262. const WINDOWPOS& wPos = *reinterpret_cast<WINDOWPOS*> (lParam);
  3263. if ((wPos.flags & SWP_NOMOVE) != 0 && (wPos.flags & SWP_NOSIZE) != 0)
  3264. startTimer (100);
  3265. else
  3266. if (handlePositionChanged())
  3267. return 0;
  3268. }
  3269. break;
  3270. //==============================================================================
  3271. case WM_KEYDOWN:
  3272. case WM_SYSKEYDOWN:
  3273. if (doKeyDown (wParam))
  3274. return 0;
  3275. forwardMessageToParent (message, wParam, lParam);
  3276. break;
  3277. case WM_KEYUP:
  3278. case WM_SYSKEYUP:
  3279. if (doKeyUp (wParam))
  3280. return 0;
  3281. forwardMessageToParent (message, wParam, lParam);
  3282. break;
  3283. case WM_CHAR:
  3284. if (doKeyChar ((int) wParam, lParam))
  3285. return 0;
  3286. forwardMessageToParent (message, wParam, lParam);
  3287. break;
  3288. case WM_APPCOMMAND:
  3289. if (doAppCommand (lParam))
  3290. return TRUE;
  3291. break;
  3292. case WM_MENUCHAR: // triggered when alt+something is pressed
  3293. return MNC_CLOSE << 16; // (avoids making the default system beep)
  3294. //==============================================================================
  3295. case WM_SETFOCUS:
  3296. updateKeyModifiers();
  3297. handleFocusGain();
  3298. break;
  3299. case WM_KILLFOCUS:
  3300. if (hasCreatedCaret)
  3301. {
  3302. hasCreatedCaret = false;
  3303. DestroyCaret();
  3304. }
  3305. handleFocusLoss();
  3306. if (auto* modal = Component::getCurrentlyModalComponent())
  3307. if (auto* peer = modal->getPeer())
  3308. if ((peer->getStyleFlags() & ComponentPeer::windowIsTemporary) != 0)
  3309. sendInputAttemptWhenModalMessage();
  3310. break;
  3311. case WM_ACTIVATEAPP:
  3312. // Windows does weird things to process priority when you swap apps,
  3313. // so this forces an update when the app is brought to the front
  3314. if (wParam != FALSE)
  3315. juce_repeatLastProcessPriority();
  3316. else
  3317. Desktop::getInstance().setKioskModeComponent (nullptr); // turn kiosk mode off if we lose focus
  3318. juce_checkCurrentlyFocusedTopLevelWindow();
  3319. modifiersAtLastCallback = -1;
  3320. return 0;
  3321. case WM_ACTIVATE:
  3322. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  3323. {
  3324. handleAppActivation (wParam);
  3325. return 0;
  3326. }
  3327. break;
  3328. case WM_NCACTIVATE:
  3329. // while a temporary window is being shown, prevent Windows from deactivating the
  3330. // title bars of our main windows.
  3331. if (wParam == 0 && ! shouldDeactivateTitleBar)
  3332. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  3333. break;
  3334. case WM_POINTERACTIVATE:
  3335. case WM_MOUSEACTIVATE:
  3336. if (! component.getMouseClickGrabsKeyboardFocus())
  3337. return MA_NOACTIVATE;
  3338. break;
  3339. case WM_SHOWWINDOW:
  3340. if (wParam != 0)
  3341. {
  3342. component.setVisible (true);
  3343. handleBroughtToFront();
  3344. }
  3345. break;
  3346. case WM_CLOSE:
  3347. if (! component.isCurrentlyBlockedByAnotherModalComponent())
  3348. handleUserClosingWindow();
  3349. return 0;
  3350. #if JUCE_REMOVE_COMPONENT_FROM_DESKTOP_ON_WM_DESTROY
  3351. case WM_DESTROY:
  3352. getComponent().removeFromDesktop();
  3353. return 0;
  3354. #endif
  3355. case WM_QUERYENDSESSION:
  3356. if (auto* app = JUCEApplicationBase::getInstance())
  3357. {
  3358. app->systemRequestedQuit();
  3359. return MessageManager::getInstance()->hasStopMessageBeenSent();
  3360. }
  3361. return TRUE;
  3362. case WM_POWERBROADCAST:
  3363. handlePowerBroadcast (wParam);
  3364. break;
  3365. case WM_SYNCPAINT:
  3366. return 0;
  3367. case WM_DISPLAYCHANGE:
  3368. InvalidateRect (h, nullptr, 0);
  3369. // intentional fall-through...
  3370. JUCE_FALLTHROUGH
  3371. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  3372. doSettingChange();
  3373. break;
  3374. case WM_INITMENU:
  3375. initialiseSysMenu ((HMENU) wParam);
  3376. break;
  3377. case WM_SYSCOMMAND:
  3378. switch (wParam & 0xfff0)
  3379. {
  3380. case SC_CLOSE:
  3381. if (sendInputAttemptWhenModalMessage())
  3382. return 0;
  3383. if (hasTitleBar())
  3384. {
  3385. PostMessage (h, WM_CLOSE, 0, 0);
  3386. return 0;
  3387. }
  3388. break;
  3389. case SC_KEYMENU:
  3390. #if ! JUCE_WINDOWS_ALT_KEY_TRIGGERS_MENU
  3391. // This test prevents a press of the ALT key from triggering the ancient top-left window menu.
  3392. // By default we suppress this behaviour because it's unlikely that more than a tiny subset of
  3393. // our users will actually want it, and it causes problems if you're trying to use the ALT key
  3394. // as a modifier for mouse actions. If you really need the old behaviour, then just define
  3395. // JUCE_WINDOWS_ALT_KEY_TRIGGERS_MENU=1 in your app.
  3396. if ((lParam >> 16) <= 0) // Values above zero indicate that a mouse-click triggered the menu
  3397. return 0;
  3398. #endif
  3399. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very obscure
  3400. // situations that can arise if a modal loop is started from an alt-key keypress).
  3401. if (hasTitleBar() && h == GetCapture())
  3402. ReleaseCapture();
  3403. break;
  3404. case SC_MAXIMIZE:
  3405. if (! sendInputAttemptWhenModalMessage())
  3406. setFullScreen (true);
  3407. return 0;
  3408. case SC_MINIMIZE:
  3409. if (sendInputAttemptWhenModalMessage())
  3410. return 0;
  3411. if (! hasTitleBar())
  3412. {
  3413. setMinimised (true);
  3414. return 0;
  3415. }
  3416. break;
  3417. case SC_RESTORE:
  3418. if (sendInputAttemptWhenModalMessage())
  3419. return 0;
  3420. if (hasTitleBar())
  3421. {
  3422. if (isFullScreen())
  3423. {
  3424. setFullScreen (false);
  3425. return 0;
  3426. }
  3427. }
  3428. else
  3429. {
  3430. if (isMinimised())
  3431. setMinimised (false);
  3432. else if (isFullScreen())
  3433. setFullScreen (false);
  3434. return 0;
  3435. }
  3436. break;
  3437. }
  3438. break;
  3439. case WM_NCPOINTERDOWN:
  3440. case WM_NCLBUTTONDOWN:
  3441. handleLeftClickInNCArea (wParam);
  3442. break;
  3443. case WM_NCRBUTTONDOWN:
  3444. case WM_NCMBUTTONDOWN:
  3445. sendInputAttemptWhenModalMessage();
  3446. break;
  3447. case WM_IME_SETCONTEXT:
  3448. imeHandler.handleSetContext (h, wParam == TRUE);
  3449. lParam &= ~(LPARAM) ISC_SHOWUICOMPOSITIONWINDOW;
  3450. break;
  3451. case WM_IME_STARTCOMPOSITION: imeHandler.handleStartComposition (*this); return 0;
  3452. case WM_IME_ENDCOMPOSITION: imeHandler.handleEndComposition (*this, h); break;
  3453. case WM_IME_COMPOSITION: imeHandler.handleComposition (*this, h, lParam); return 0;
  3454. case WM_GETDLGCODE:
  3455. return DLGC_WANTALLKEYS;
  3456. case WM_GETOBJECT:
  3457. {
  3458. if (static_cast<long> (lParam) == WindowsAccessibility::getUiaRootObjectId())
  3459. {
  3460. if (auto* handler = component.getAccessibilityHandler())
  3461. {
  3462. LRESULT res = 0;
  3463. if (WindowsAccessibility::handleWmGetObject (handler, wParam, lParam, &res))
  3464. {
  3465. isAccessibilityActive = true;
  3466. return res;
  3467. }
  3468. }
  3469. }
  3470. break;
  3471. }
  3472. default:
  3473. break;
  3474. }
  3475. return DefWindowProcW (h, message, wParam, lParam);
  3476. }
  3477. bool sendInputAttemptWhenModalMessage()
  3478. {
  3479. if (! component.isCurrentlyBlockedByAnotherModalComponent())
  3480. return false;
  3481. if (auto* current = Component::getCurrentlyModalComponent())
  3482. if (auto* owner = getOwnerOfWindow ((HWND) current->getWindowHandle()))
  3483. if (! owner->shouldIgnoreModalDismiss)
  3484. current->inputAttemptWhenModal();
  3485. return true;
  3486. }
  3487. //==============================================================================
  3488. struct IMEHandler
  3489. {
  3490. IMEHandler()
  3491. {
  3492. reset();
  3493. }
  3494. void handleSetContext (HWND hWnd, const bool windowIsActive)
  3495. {
  3496. if (compositionInProgress && ! windowIsActive)
  3497. {
  3498. if (HIMC hImc = ImmGetContext (hWnd))
  3499. {
  3500. ImmNotifyIME (hImc, NI_COMPOSITIONSTR, CPS_COMPLETE, 0);
  3501. ImmReleaseContext (hWnd, hImc);
  3502. }
  3503. // If the composition is still in progress, calling ImmNotifyIME may call back
  3504. // into handleComposition to let us know that the composition has finished.
  3505. // We need to set compositionInProgress *after* calling handleComposition, so that
  3506. // the text replaces the current selection, rather than being inserted after the
  3507. // caret.
  3508. compositionInProgress = false;
  3509. }
  3510. }
  3511. void handleStartComposition (ComponentPeer& owner)
  3512. {
  3513. reset();
  3514. if (auto* target = owner.findCurrentTextInputTarget())
  3515. target->insertTextAtCaret (String());
  3516. }
  3517. void handleEndComposition (ComponentPeer& owner, HWND hWnd)
  3518. {
  3519. if (compositionInProgress)
  3520. {
  3521. // If this occurs, the user has cancelled the composition, so clear their changes..
  3522. if (auto* target = owner.findCurrentTextInputTarget())
  3523. {
  3524. target->setHighlightedRegion (compositionRange);
  3525. target->insertTextAtCaret (String());
  3526. compositionRange.setLength (0);
  3527. target->setHighlightedRegion (Range<int>::emptyRange (compositionRange.getEnd()));
  3528. target->setTemporaryUnderlining ({});
  3529. }
  3530. if (auto hImc = ImmGetContext (hWnd))
  3531. {
  3532. ImmNotifyIME (hImc, NI_CLOSECANDIDATE, 0, 0);
  3533. ImmReleaseContext (hWnd, hImc);
  3534. }
  3535. }
  3536. reset();
  3537. }
  3538. void handleComposition (ComponentPeer& owner, HWND hWnd, const LPARAM lParam)
  3539. {
  3540. if (auto* target = owner.findCurrentTextInputTarget())
  3541. {
  3542. if (auto hImc = ImmGetContext (hWnd))
  3543. {
  3544. if (compositionRange.getStart() < 0)
  3545. compositionRange = Range<int>::emptyRange (target->getHighlightedRegion().getStart());
  3546. if ((lParam & GCS_RESULTSTR) != 0) // (composition has finished)
  3547. {
  3548. replaceCurrentSelection (target, getCompositionString (hImc, GCS_RESULTSTR),
  3549. Range<int>::emptyRange (-1));
  3550. reset();
  3551. target->setTemporaryUnderlining ({});
  3552. }
  3553. else if ((lParam & GCS_COMPSTR) != 0) // (composition is still in-progress)
  3554. {
  3555. replaceCurrentSelection (target, getCompositionString (hImc, GCS_COMPSTR),
  3556. getCompositionSelection (hImc, lParam));
  3557. target->setTemporaryUnderlining (getCompositionUnderlines (hImc, lParam));
  3558. compositionInProgress = true;
  3559. }
  3560. moveCandidateWindowToLeftAlignWithSelection (hImc, owner, target);
  3561. ImmReleaseContext (hWnd, hImc);
  3562. }
  3563. }
  3564. }
  3565. private:
  3566. //==============================================================================
  3567. Range<int> compositionRange; // The range being modified in the TextInputTarget
  3568. bool compositionInProgress;
  3569. //==============================================================================
  3570. void reset()
  3571. {
  3572. compositionRange = Range<int>::emptyRange (-1);
  3573. compositionInProgress = false;
  3574. }
  3575. String getCompositionString (HIMC hImc, const DWORD type) const
  3576. {
  3577. jassert (hImc != HIMC{});
  3578. const auto stringSizeBytes = ImmGetCompositionString (hImc, type, nullptr, 0);
  3579. if (stringSizeBytes > 0)
  3580. {
  3581. HeapBlock<TCHAR> buffer;
  3582. buffer.calloc ((size_t) stringSizeBytes / sizeof (TCHAR) + 1);
  3583. ImmGetCompositionString (hImc, type, buffer, (DWORD) stringSizeBytes);
  3584. return String (buffer.get());
  3585. }
  3586. return {};
  3587. }
  3588. int getCompositionCaretPos (HIMC hImc, LPARAM lParam, const String& currentIMEString) const
  3589. {
  3590. jassert (hImc != HIMC{});
  3591. if ((lParam & CS_NOMOVECARET) != 0)
  3592. return compositionRange.getStart();
  3593. if ((lParam & GCS_CURSORPOS) != 0)
  3594. {
  3595. const int localCaretPos = ImmGetCompositionString (hImc, GCS_CURSORPOS, nullptr, 0);
  3596. return compositionRange.getStart() + jmax (0, localCaretPos);
  3597. }
  3598. return compositionRange.getStart() + currentIMEString.length();
  3599. }
  3600. // Get selected/highlighted range while doing composition:
  3601. // returned range is relative to beginning of TextInputTarget, not composition string
  3602. Range<int> getCompositionSelection (HIMC hImc, LPARAM lParam) const
  3603. {
  3604. jassert (hImc != HIMC{});
  3605. int selectionStart = 0;
  3606. int selectionEnd = 0;
  3607. if ((lParam & GCS_COMPATTR) != 0)
  3608. {
  3609. // Get size of attributes array:
  3610. const int attributeSizeBytes = ImmGetCompositionString (hImc, GCS_COMPATTR, nullptr, 0);
  3611. if (attributeSizeBytes > 0)
  3612. {
  3613. // Get attributes (8 bit flag per character):
  3614. HeapBlock<char> attributes (attributeSizeBytes);
  3615. ImmGetCompositionString (hImc, GCS_COMPATTR, attributes, (DWORD) attributeSizeBytes);
  3616. selectionStart = 0;
  3617. for (selectionStart = 0; selectionStart < attributeSizeBytes; ++selectionStart)
  3618. if (attributes[selectionStart] == ATTR_TARGET_CONVERTED || attributes[selectionStart] == ATTR_TARGET_NOTCONVERTED)
  3619. break;
  3620. for (selectionEnd = selectionStart; selectionEnd < attributeSizeBytes; ++selectionEnd)
  3621. if (attributes[selectionEnd] != ATTR_TARGET_CONVERTED && attributes[selectionEnd] != ATTR_TARGET_NOTCONVERTED)
  3622. break;
  3623. }
  3624. }
  3625. return Range<int> (selectionStart, selectionEnd) + compositionRange.getStart();
  3626. }
  3627. void replaceCurrentSelection (TextInputTarget* const target, const String& newContent, Range<int> newSelection)
  3628. {
  3629. if (compositionInProgress)
  3630. target->setHighlightedRegion (compositionRange);
  3631. target->insertTextAtCaret (newContent);
  3632. compositionRange.setLength (newContent.length());
  3633. if (newSelection.getStart() < 0)
  3634. newSelection = Range<int>::emptyRange (compositionRange.getEnd());
  3635. target->setHighlightedRegion (newSelection);
  3636. }
  3637. Array<Range<int>> getCompositionUnderlines (HIMC hImc, LPARAM lParam) const
  3638. {
  3639. Array<Range<int>> result;
  3640. if (hImc != HIMC{} && (lParam & GCS_COMPCLAUSE) != 0)
  3641. {
  3642. auto clauseDataSizeBytes = ImmGetCompositionString (hImc, GCS_COMPCLAUSE, nullptr, 0);
  3643. if (clauseDataSizeBytes > 0)
  3644. {
  3645. const auto numItems = (size_t) clauseDataSizeBytes / sizeof (uint32);
  3646. HeapBlock<uint32> clauseData (numItems);
  3647. if (ImmGetCompositionString (hImc, GCS_COMPCLAUSE, clauseData, (DWORD) clauseDataSizeBytes) > 0)
  3648. for (size_t i = 0; i + 1 < numItems; ++i)
  3649. result.add (Range<int> ((int) clauseData[i], (int) clauseData[i + 1]) + compositionRange.getStart());
  3650. }
  3651. }
  3652. return result;
  3653. }
  3654. void moveCandidateWindowToLeftAlignWithSelection (HIMC hImc, ComponentPeer& peer, TextInputTarget* target) const
  3655. {
  3656. if (auto* targetComp = dynamic_cast<Component*> (target))
  3657. {
  3658. auto area = peer.getComponent().getLocalArea (targetComp, target->getCaretRectangle());
  3659. CANDIDATEFORM pos = { 0, CFS_CANDIDATEPOS, { area.getX(), area.getBottom() }, { 0, 0, 0, 0 } };
  3660. ImmSetCandidateWindow (hImc, &pos);
  3661. }
  3662. }
  3663. JUCE_DECLARE_NON_COPYABLE (IMEHandler)
  3664. };
  3665. void timerCallback() override
  3666. {
  3667. handlePositionChanged();
  3668. stopTimer();
  3669. }
  3670. static bool isAncestor (HWND outer, HWND inner)
  3671. {
  3672. if (outer == nullptr || inner == nullptr)
  3673. return false;
  3674. if (outer == inner)
  3675. return true;
  3676. return isAncestor (outer, GetAncestor (inner, GA_PARENT));
  3677. }
  3678. void windowShouldDismissModals (HWND originator)
  3679. {
  3680. if (shouldIgnoreModalDismiss)
  3681. return;
  3682. if (isAncestor (originator, hwnd))
  3683. sendInputAttemptWhenModalMessage();
  3684. }
  3685. // Unfortunately SetWindowsHookEx only allows us to register a static function as a hook.
  3686. // To get around this, we keep a static list of listeners which are interested in
  3687. // top-level window events, and notify all of these listeners from the callback.
  3688. class TopLevelModalDismissBroadcaster
  3689. {
  3690. public:
  3691. TopLevelModalDismissBroadcaster()
  3692. : hook (SetWindowsHookEx (WH_CALLWNDPROC,
  3693. callWndProc,
  3694. (HINSTANCE) juce::Process::getCurrentModuleInstanceHandle(),
  3695. GetCurrentThreadId()))
  3696. {}
  3697. ~TopLevelModalDismissBroadcaster() noexcept
  3698. {
  3699. UnhookWindowsHookEx (hook);
  3700. }
  3701. private:
  3702. static void processMessage (int nCode, const CWPSTRUCT* info)
  3703. {
  3704. if (nCode < 0 || info == nullptr)
  3705. return;
  3706. constexpr UINT events[] { WM_MOVE,
  3707. WM_SIZE,
  3708. WM_WINDOWPOSCHANGING,
  3709. WM_NCPOINTERDOWN,
  3710. WM_NCLBUTTONDOWN,
  3711. WM_NCRBUTTONDOWN,
  3712. WM_NCMBUTTONDOWN };
  3713. if (std::find (std::begin (events), std::end (events), info->message) == std::end (events))
  3714. return;
  3715. if (info->message == WM_WINDOWPOSCHANGING)
  3716. {
  3717. const auto* windowPos = reinterpret_cast<const WINDOWPOS*> (info->lParam);
  3718. const auto windowPosFlags = windowPos->flags;
  3719. constexpr auto maskToCheck = SWP_NOMOVE | SWP_NOSIZE;
  3720. if ((windowPosFlags & maskToCheck) == maskToCheck)
  3721. return;
  3722. }
  3723. // windowMayDismissModals could affect the number of active ComponentPeer instances
  3724. for (auto i = ComponentPeer::getNumPeers(); --i >= 0;)
  3725. if (i < ComponentPeer::getNumPeers())
  3726. if (auto* hwndPeer = dynamic_cast<HWNDComponentPeer*> (ComponentPeer::getPeer (i)))
  3727. hwndPeer->windowShouldDismissModals (info->hwnd);
  3728. }
  3729. static LRESULT CALLBACK callWndProc (int nCode, WPARAM wParam, LPARAM lParam)
  3730. {
  3731. processMessage (nCode, reinterpret_cast<CWPSTRUCT*> (lParam));
  3732. return CallNextHookEx ({}, nCode, wParam, lParam);
  3733. }
  3734. HHOOK hook;
  3735. };
  3736. SharedResourcePointer<TopLevelModalDismissBroadcaster> modalDismissBroadcaster;
  3737. IMEHandler imeHandler;
  3738. bool shouldIgnoreModalDismiss = false;
  3739. RectangleList<int> deferredRepaints;
  3740. ScopedSuspendResumeNotificationRegistration suspendResumeRegistration;
  3741. std::optional<SimpleTimer> monitorUpdateTimer;
  3742. //==============================================================================
  3743. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HWNDComponentPeer)
  3744. };
  3745. MultiTouchMapper<DWORD> HWNDComponentPeer::currentTouches;
  3746. ModifierKeys HWNDComponentPeer::modifiersAtLastCallback;
  3747. ComponentPeer* Component::createNewPeer (int styleFlags, void* parentHWND)
  3748. {
  3749. return new HWNDComponentPeer (*this, styleFlags, (HWND) parentHWND, false);
  3750. }
  3751. JUCE_API ComponentPeer* createNonRepaintingEmbeddedWindowsPeer (Component& component, void* parentHWND);
  3752. JUCE_API ComponentPeer* createNonRepaintingEmbeddedWindowsPeer (Component& component, void* parentHWND)
  3753. {
  3754. return new HWNDComponentPeer (component, ComponentPeer::windowIgnoresMouseClicks,
  3755. (HWND) parentHWND, true);
  3756. }
  3757. JUCE_IMPLEMENT_SINGLETON (HWNDComponentPeer::WindowClassHolder)
  3758. //==============================================================================
  3759. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  3760. {
  3761. auto k = (SHORT) keyCode;
  3762. if ((keyCode & extendedKeyModifier) == 0)
  3763. {
  3764. if (k >= (SHORT) 'a' && k <= (SHORT) 'z')
  3765. k += (SHORT) 'A' - (SHORT) 'a';
  3766. // Only translate if extendedKeyModifier flag is not set
  3767. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  3768. (SHORT) '+', VK_OEM_PLUS,
  3769. (SHORT) '-', VK_OEM_MINUS,
  3770. (SHORT) '.', VK_OEM_PERIOD,
  3771. (SHORT) ';', VK_OEM_1,
  3772. (SHORT) ':', VK_OEM_1,
  3773. (SHORT) '/', VK_OEM_2,
  3774. (SHORT) '?', VK_OEM_2,
  3775. (SHORT) '[', VK_OEM_4,
  3776. (SHORT) ']', VK_OEM_6 };
  3777. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  3778. if (k == translatedValues[i])
  3779. k = translatedValues[i + 1];
  3780. }
  3781. return HWNDComponentPeer::isKeyDown (k);
  3782. }
  3783. // (This internal function is used by the plugin client module)
  3784. bool offerKeyMessageToJUCEWindow (MSG& m);
  3785. bool offerKeyMessageToJUCEWindow (MSG& m) { return HWNDComponentPeer::offerKeyMessageToJUCEWindow (m); }
  3786. //==============================================================================
  3787. static DWORD getProcess (HWND hwnd)
  3788. {
  3789. DWORD result = 0;
  3790. GetWindowThreadProcessId (hwnd, &result);
  3791. return result;
  3792. }
  3793. /* Returns true if the viewComponent is embedded into a window
  3794. owned by the foreground process.
  3795. */
  3796. bool isEmbeddedInForegroundProcess (Component* c)
  3797. {
  3798. if (c == nullptr)
  3799. return false;
  3800. auto* peer = c->getPeer();
  3801. auto* hwnd = peer != nullptr ? static_cast<HWND> (peer->getNativeHandle()) : nullptr;
  3802. if (hwnd == nullptr)
  3803. return true;
  3804. const auto fgProcess = getProcess (GetForegroundWindow());
  3805. const auto ownerProcess = getProcess (GetAncestor (hwnd, GA_ROOTOWNER));
  3806. return fgProcess == ownerProcess;
  3807. }
  3808. bool JUCE_CALLTYPE Process::isForegroundProcess()
  3809. {
  3810. if (auto fg = GetForegroundWindow())
  3811. return getProcess (fg) == GetCurrentProcessId();
  3812. return true;
  3813. }
  3814. // N/A on Windows as far as I know.
  3815. void JUCE_CALLTYPE Process::makeForegroundProcess() {}
  3816. void JUCE_CALLTYPE Process::hide() {}
  3817. //==============================================================================
  3818. static BOOL CALLBACK enumAlwaysOnTopWindows (HWND hwnd, LPARAM lParam)
  3819. {
  3820. if (IsWindowVisible (hwnd))
  3821. {
  3822. DWORD processID = 0;
  3823. GetWindowThreadProcessId (hwnd, &processID);
  3824. if (processID == GetCurrentProcessId())
  3825. {
  3826. WINDOWINFO info{};
  3827. if (GetWindowInfo (hwnd, &info)
  3828. && (info.dwExStyle & WS_EX_TOPMOST) != 0)
  3829. {
  3830. *reinterpret_cast<bool*> (lParam) = true;
  3831. return FALSE;
  3832. }
  3833. }
  3834. }
  3835. return TRUE;
  3836. }
  3837. bool juce_areThereAnyAlwaysOnTopWindows()
  3838. {
  3839. bool anyAlwaysOnTopFound = false;
  3840. EnumWindows (&enumAlwaysOnTopWindows, (LPARAM) &anyAlwaysOnTopFound);
  3841. return anyAlwaysOnTopFound;
  3842. }
  3843. //==============================================================================
  3844. #if JUCE_MSVC
  3845. // required to enable the newer dialog box on vista and above
  3846. #pragma comment(linker, \
  3847. "\"/MANIFESTDEPENDENCY:type='Win32' " \
  3848. "name='Microsoft.Windows.Common-Controls' " \
  3849. "version='6.0.0.0' " \
  3850. "processorArchitecture='*' " \
  3851. "publicKeyToken='6595b64144ccf1df' " \
  3852. "language='*'\"" \
  3853. )
  3854. #endif
  3855. class WindowsMessageBoxBase : private AsyncUpdater
  3856. {
  3857. public:
  3858. WindowsMessageBoxBase (Component* comp,
  3859. std::unique_ptr<ModalComponentManager::Callback>&& cb)
  3860. : associatedComponent (comp),
  3861. callback (std::move (cb))
  3862. {
  3863. }
  3864. virtual int getResult() = 0;
  3865. HWND getParentHWND() const
  3866. {
  3867. if (associatedComponent != nullptr)
  3868. return (HWND) associatedComponent->getWindowHandle();
  3869. return nullptr;
  3870. }
  3871. using AsyncUpdater::triggerAsyncUpdate;
  3872. private:
  3873. void handleAsyncUpdate() override
  3874. {
  3875. const auto result = getResult();
  3876. if (callback != nullptr)
  3877. callback->modalStateFinished (result);
  3878. delete this;
  3879. }
  3880. Component::SafePointer<Component> associatedComponent;
  3881. std::unique_ptr<ModalComponentManager::Callback> callback;
  3882. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowsMessageBoxBase)
  3883. };
  3884. class PreVistaMessageBox : public WindowsMessageBoxBase
  3885. {
  3886. public:
  3887. PreVistaMessageBox (const MessageBoxOptions& opts,
  3888. UINT extraFlags,
  3889. std::unique_ptr<ModalComponentManager::Callback>&& cb)
  3890. : WindowsMessageBoxBase (opts.getAssociatedComponent(), std::move (cb)),
  3891. flags (extraFlags | getMessageBoxFlags (opts.getIconType())),
  3892. title (opts.getTitle()), message (opts.getMessage())
  3893. {
  3894. }
  3895. int getResult() override
  3896. {
  3897. const auto result = MessageBox (getParentHWND(), message.toWideCharPointer(), title.toWideCharPointer(), flags);
  3898. if (result == IDYES || result == IDOK) return 0;
  3899. if (result == IDNO && ((flags & 1) != 0)) return 1;
  3900. return 2;
  3901. }
  3902. private:
  3903. static UINT getMessageBoxFlags (MessageBoxIconType iconType) noexcept
  3904. {
  3905. // this window can get lost behind JUCE windows which are set to be alwaysOnTop
  3906. // so if there are any set it to be topmost
  3907. const auto topmostFlag = juce_areThereAnyAlwaysOnTopWindows() ? MB_TOPMOST : 0;
  3908. const auto iconFlags = [&]() -> decltype (topmostFlag)
  3909. {
  3910. switch (iconType)
  3911. {
  3912. case MessageBoxIconType::QuestionIcon: return MB_ICONQUESTION;
  3913. case MessageBoxIconType::WarningIcon: return MB_ICONWARNING;
  3914. case MessageBoxIconType::InfoIcon: return MB_ICONINFORMATION;
  3915. case MessageBoxIconType::NoIcon: break;
  3916. }
  3917. return 0;
  3918. }();
  3919. return static_cast<UINT> (MB_TASKMODAL | MB_SETFOREGROUND | topmostFlag | iconFlags);
  3920. }
  3921. const UINT flags;
  3922. const String title, message;
  3923. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PreVistaMessageBox)
  3924. };
  3925. using TaskDialogIndirectFunc = HRESULT (WINAPI*) (const TASKDIALOGCONFIG*, INT*, INT*, BOOL*);
  3926. static TaskDialogIndirectFunc taskDialogIndirect = nullptr;
  3927. class WindowsTaskDialog : public WindowsMessageBoxBase
  3928. {
  3929. public:
  3930. WindowsTaskDialog (const MessageBoxOptions& opts,
  3931. std::unique_ptr<ModalComponentManager::Callback>&& cb)
  3932. : WindowsMessageBoxBase (opts.getAssociatedComponent(), std::move (cb)),
  3933. iconType (opts.getIconType()),
  3934. title (opts.getTitle()), message (opts.getMessage()),
  3935. button1 (opts.getButtonText (0)), button2 (opts.getButtonText (1)), button3 (opts.getButtonText (2))
  3936. {
  3937. }
  3938. int getResult() override
  3939. {
  3940. TASKDIALOGCONFIG config{};
  3941. config.cbSize = sizeof (config);
  3942. config.hwndParent = getParentHWND();
  3943. config.pszWindowTitle = title.toWideCharPointer();
  3944. config.pszContent = message.toWideCharPointer();
  3945. config.hInstance = (HINSTANCE) Process::getCurrentModuleInstanceHandle();
  3946. if (iconType == MessageBoxIconType::QuestionIcon)
  3947. {
  3948. if (auto* questionIcon = LoadIcon (nullptr, IDI_QUESTION))
  3949. {
  3950. config.hMainIcon = questionIcon;
  3951. config.dwFlags |= TDF_USE_HICON_MAIN;
  3952. }
  3953. }
  3954. else
  3955. {
  3956. auto icon = [this]() -> LPWSTR
  3957. {
  3958. switch (iconType)
  3959. {
  3960. case MessageBoxIconType::WarningIcon: return TD_WARNING_ICON;
  3961. case MessageBoxIconType::InfoIcon: return TD_INFORMATION_ICON;
  3962. case MessageBoxIconType::QuestionIcon: JUCE_FALLTHROUGH
  3963. case MessageBoxIconType::NoIcon:
  3964. break;
  3965. }
  3966. return nullptr;
  3967. }();
  3968. if (icon != nullptr)
  3969. config.pszMainIcon = icon;
  3970. }
  3971. std::vector<TASKDIALOG_BUTTON> buttons;
  3972. for (const auto* buttonText : { &button1, &button2, &button3 })
  3973. if (buttonText->isNotEmpty())
  3974. buttons.push_back ({ (int) buttons.size(), buttonText->toWideCharPointer() });
  3975. config.pButtons = buttons.data();
  3976. config.cButtons = (UINT) buttons.size();
  3977. int buttonIndex = 0;
  3978. taskDialogIndirect (&config, &buttonIndex, nullptr, nullptr);
  3979. return buttonIndex;
  3980. }
  3981. static bool loadTaskDialog()
  3982. {
  3983. static bool hasChecked = false;
  3984. if (! hasChecked)
  3985. {
  3986. hasChecked = true;
  3987. const auto comctl = "Comctl32.dll";
  3988. LoadLibraryA (comctl);
  3989. const auto comctlModule = GetModuleHandleA (comctl);
  3990. if (comctlModule != nullptr)
  3991. taskDialogIndirect = (TaskDialogIndirectFunc) GetProcAddress (comctlModule, "TaskDialogIndirect");
  3992. }
  3993. return taskDialogIndirect != nullptr;
  3994. }
  3995. private:
  3996. MessageBoxIconType iconType;
  3997. String title, message, button1, button2, button3;
  3998. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowsTaskDialog)
  3999. };
  4000. static std::unique_ptr<WindowsMessageBoxBase> createMessageBox (const MessageBoxOptions& options,
  4001. std::unique_ptr<ModalComponentManager::Callback> callback)
  4002. {
  4003. const auto useTaskDialog =
  4004. #if JUCE_MODAL_LOOPS_PERMITTED
  4005. callback != nullptr &&
  4006. #endif
  4007. SystemStats::getOperatingSystemType() >= SystemStats::WinVista
  4008. && WindowsTaskDialog::loadTaskDialog();
  4009. if (useTaskDialog)
  4010. return std::make_unique<WindowsTaskDialog> (options, std::move (callback));
  4011. const auto extraFlags = [&options]
  4012. {
  4013. const auto numButtons = options.getNumButtons();
  4014. if (numButtons == 3)
  4015. return MB_YESNOCANCEL;
  4016. if (numButtons == 2)
  4017. return options.getButtonText (0) == "OK" ? MB_OKCANCEL
  4018. : MB_YESNO;
  4019. return MB_OK;
  4020. }();
  4021. return std::make_unique<PreVistaMessageBox> (options, (UINT) extraFlags, std::move (callback));
  4022. }
  4023. static int showDialog (const MessageBoxOptions& options,
  4024. ModalComponentManager::Callback* callbackIn,
  4025. AlertWindowMappings::MapFn mapFn)
  4026. {
  4027. #if JUCE_MODAL_LOOPS_PERMITTED
  4028. if (callbackIn == nullptr)
  4029. {
  4030. jassert (mapFn != nullptr);
  4031. auto messageBox = createMessageBox (options, nullptr);
  4032. return mapFn (messageBox->getResult());
  4033. }
  4034. #endif
  4035. auto messageBox = createMessageBox (options,
  4036. AlertWindowMappings::getWrappedCallback (callbackIn, mapFn));
  4037. messageBox->triggerAsyncUpdate();
  4038. messageBox.release();
  4039. return 0;
  4040. }
  4041. #if JUCE_MODAL_LOOPS_PERMITTED
  4042. void JUCE_CALLTYPE NativeMessageBox::showMessageBox (MessageBoxIconType iconType,
  4043. const String& title, const String& message,
  4044. Component* associatedComponent)
  4045. {
  4046. showDialog (MessageBoxOptions()
  4047. .withIconType (iconType)
  4048. .withTitle (title)
  4049. .withMessage (message)
  4050. .withButton (TRANS("OK"))
  4051. .withAssociatedComponent (associatedComponent),
  4052. nullptr, AlertWindowMappings::messageBox);
  4053. }
  4054. int JUCE_CALLTYPE NativeMessageBox::show (const MessageBoxOptions& options)
  4055. {
  4056. return showDialog (options, nullptr, AlertWindowMappings::noMapping);
  4057. }
  4058. #endif
  4059. void JUCE_CALLTYPE NativeMessageBox::showMessageBoxAsync (MessageBoxIconType iconType,
  4060. const String& title, const String& message,
  4061. Component* associatedComponent,
  4062. ModalComponentManager::Callback* callback)
  4063. {
  4064. showDialog (MessageBoxOptions()
  4065. .withIconType (iconType)
  4066. .withTitle (title)
  4067. .withMessage (message)
  4068. .withButton (TRANS("OK"))
  4069. .withAssociatedComponent (associatedComponent),
  4070. callback, AlertWindowMappings::messageBox);
  4071. }
  4072. bool JUCE_CALLTYPE NativeMessageBox::showOkCancelBox (MessageBoxIconType iconType,
  4073. const String& title, const String& message,
  4074. Component* associatedComponent,
  4075. ModalComponentManager::Callback* callback)
  4076. {
  4077. return showDialog (MessageBoxOptions()
  4078. .withIconType (iconType)
  4079. .withTitle (title)
  4080. .withMessage (message)
  4081. .withButton (TRANS("OK"))
  4082. .withButton (TRANS("Cancel"))
  4083. .withAssociatedComponent (associatedComponent),
  4084. callback, AlertWindowMappings::okCancel) != 0;
  4085. }
  4086. int JUCE_CALLTYPE NativeMessageBox::showYesNoCancelBox (MessageBoxIconType iconType,
  4087. const String& title, const String& message,
  4088. Component* associatedComponent,
  4089. ModalComponentManager::Callback* callback)
  4090. {
  4091. return showDialog (MessageBoxOptions()
  4092. .withIconType (iconType)
  4093. .withTitle (title)
  4094. .withMessage (message)
  4095. .withButton (TRANS("Yes"))
  4096. .withButton (TRANS("No"))
  4097. .withButton (TRANS("Cancel"))
  4098. .withAssociatedComponent (associatedComponent),
  4099. callback, AlertWindowMappings::yesNoCancel);
  4100. }
  4101. int JUCE_CALLTYPE NativeMessageBox::showYesNoBox (MessageBoxIconType iconType,
  4102. const String& title, const String& message,
  4103. Component* associatedComponent,
  4104. ModalComponentManager::Callback* callback)
  4105. {
  4106. return showDialog (MessageBoxOptions()
  4107. .withIconType (iconType)
  4108. .withTitle (title)
  4109. .withMessage (message)
  4110. .withButton (TRANS("Yes"))
  4111. .withButton (TRANS("No"))
  4112. .withAssociatedComponent (associatedComponent),
  4113. callback, AlertWindowMappings::okCancel);
  4114. }
  4115. void JUCE_CALLTYPE NativeMessageBox::showAsync (const MessageBoxOptions& options,
  4116. ModalComponentManager::Callback* callback)
  4117. {
  4118. showDialog (options, callback, AlertWindowMappings::noMapping);
  4119. }
  4120. void JUCE_CALLTYPE NativeMessageBox::showAsync (const MessageBoxOptions& options,
  4121. std::function<void (int)> callback)
  4122. {
  4123. showAsync (options, ModalCallbackFunction::create (callback));
  4124. }
  4125. //==============================================================================
  4126. bool MouseInputSource::SourceList::addSource()
  4127. {
  4128. auto numSources = sources.size();
  4129. if (numSources == 0 || canUseMultiTouch())
  4130. {
  4131. addSource (numSources, numSources == 0 ? MouseInputSource::InputSourceType::mouse
  4132. : MouseInputSource::InputSourceType::touch);
  4133. return true;
  4134. }
  4135. return false;
  4136. }
  4137. bool MouseInputSource::SourceList::canUseTouch()
  4138. {
  4139. return canUseMultiTouch();
  4140. }
  4141. Point<float> MouseInputSource::getCurrentRawMousePosition()
  4142. {
  4143. POINT mousePos;
  4144. GetCursorPos (&mousePos);
  4145. auto p = pointFromPOINT (mousePos);
  4146. if (isPerMonitorDPIAwareThread())
  4147. p = Desktop::getInstance().getDisplays().physicalToLogical (p);
  4148. return p.toFloat();
  4149. }
  4150. void MouseInputSource::setRawMousePosition (Point<float> newPosition)
  4151. {
  4152. auto newPositionInt = newPosition.roundToInt();
  4153. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  4154. if (isPerMonitorDPIAwareThread())
  4155. newPositionInt = Desktop::getInstance().getDisplays().logicalToPhysical (newPositionInt);
  4156. #endif
  4157. auto point = POINTFromPoint (newPositionInt);
  4158. SetCursorPos (point.x, point.y);
  4159. }
  4160. //==============================================================================
  4161. class ScreenSaverDefeater : public Timer
  4162. {
  4163. public:
  4164. ScreenSaverDefeater()
  4165. {
  4166. startTimer (10000);
  4167. timerCallback();
  4168. }
  4169. void timerCallback() override
  4170. {
  4171. if (Process::isForegroundProcess())
  4172. {
  4173. INPUT input = {};
  4174. input.type = INPUT_MOUSE;
  4175. input.mi.mouseData = MOUSEEVENTF_MOVE;
  4176. SendInput (1, &input, sizeof (INPUT));
  4177. }
  4178. }
  4179. };
  4180. static std::unique_ptr<ScreenSaverDefeater> screenSaverDefeater;
  4181. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  4182. {
  4183. if (isEnabled)
  4184. screenSaverDefeater = nullptr;
  4185. else if (screenSaverDefeater == nullptr)
  4186. screenSaverDefeater.reset (new ScreenSaverDefeater());
  4187. }
  4188. bool Desktop::isScreenSaverEnabled()
  4189. {
  4190. return screenSaverDefeater == nullptr;
  4191. }
  4192. //==============================================================================
  4193. void LookAndFeel::playAlertSound()
  4194. {
  4195. MessageBeep (MB_OK);
  4196. }
  4197. //==============================================================================
  4198. void SystemClipboard::copyTextToClipboard (const String& text)
  4199. {
  4200. if (OpenClipboard (nullptr) != 0)
  4201. {
  4202. if (EmptyClipboard() != 0)
  4203. {
  4204. auto bytesNeeded = CharPointer_UTF16::getBytesRequiredFor (text.getCharPointer()) + 4;
  4205. if (bytesNeeded > 0)
  4206. {
  4207. if (auto bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE | GMEM_ZEROINIT, bytesNeeded + sizeof (WCHAR)))
  4208. {
  4209. if (auto* data = static_cast<WCHAR*> (GlobalLock (bufH)))
  4210. {
  4211. text.copyToUTF16 (data, bytesNeeded);
  4212. GlobalUnlock (bufH);
  4213. SetClipboardData (CF_UNICODETEXT, bufH);
  4214. }
  4215. }
  4216. }
  4217. }
  4218. CloseClipboard();
  4219. }
  4220. }
  4221. String SystemClipboard::getTextFromClipboard()
  4222. {
  4223. String result;
  4224. if (OpenClipboard (nullptr) != 0)
  4225. {
  4226. if (auto bufH = GetClipboardData (CF_UNICODETEXT))
  4227. {
  4228. if (auto* data = (const WCHAR*) GlobalLock (bufH))
  4229. {
  4230. result = String (data, (size_t) (GlobalSize (bufH) / sizeof (WCHAR)));
  4231. GlobalUnlock (bufH);
  4232. }
  4233. }
  4234. CloseClipboard();
  4235. }
  4236. return result;
  4237. }
  4238. //==============================================================================
  4239. void Desktop::setKioskComponent (Component* kioskModeComp, bool enableOrDisable, bool /*allowMenusAndBars*/)
  4240. {
  4241. if (auto* tlw = dynamic_cast<TopLevelWindow*> (kioskModeComp))
  4242. tlw->setUsingNativeTitleBar (! enableOrDisable);
  4243. if (kioskModeComp != nullptr && enableOrDisable)
  4244. kioskModeComp->setBounds (getDisplays().getDisplayForRect (kioskModeComp->getScreenBounds())->totalArea);
  4245. }
  4246. void Desktop::allowedOrientationsChanged() {}
  4247. //==============================================================================
  4248. static const Displays::Display* getCurrentDisplayFromScaleFactor (HWND hwnd)
  4249. {
  4250. Array<const Displays::Display*> candidateDisplays;
  4251. const auto scaleToLookFor = [&]
  4252. {
  4253. if (auto* peer = HWNDComponentPeer::getOwnerOfWindow (hwnd))
  4254. return peer->getPlatformScaleFactor();
  4255. return getScaleFactorForWindow (hwnd);
  4256. }();
  4257. auto globalScale = Desktop::getInstance().getGlobalScaleFactor();
  4258. for (auto& d : Desktop::getInstance().getDisplays().displays)
  4259. if (approximatelyEqual (d.scale / globalScale, scaleToLookFor))
  4260. candidateDisplays.add (&d);
  4261. if (candidateDisplays.size() > 0)
  4262. {
  4263. if (candidateDisplays.size() == 1)
  4264. return candidateDisplays[0];
  4265. const auto bounds = [&]
  4266. {
  4267. if (auto* peer = HWNDComponentPeer::getOwnerOfWindow (hwnd))
  4268. return peer->getComponent().getTopLevelComponent()->getBounds();
  4269. return Desktop::getInstance().getDisplays().physicalToLogical (rectangleFromRECT (getWindowScreenRect (hwnd)));
  4270. }();
  4271. const Displays::Display* retVal = nullptr;
  4272. int maxArea = -1;
  4273. for (auto* d : candidateDisplays)
  4274. {
  4275. auto intersection = d->totalArea.getIntersection (bounds);
  4276. auto area = intersection.getWidth() * intersection.getHeight();
  4277. if (area > maxArea)
  4278. {
  4279. maxArea = area;
  4280. retVal = d;
  4281. }
  4282. }
  4283. if (retVal != nullptr)
  4284. return retVal;
  4285. }
  4286. return Desktop::getInstance().getDisplays().getPrimaryDisplay();
  4287. }
  4288. //==============================================================================
  4289. struct MonitorInfo
  4290. {
  4291. MonitorInfo (bool main, RECT totalArea, RECT workArea, double d) noexcept
  4292. : isMain (main),
  4293. totalAreaRect (totalArea),
  4294. workAreaRect (workArea),
  4295. dpi (d)
  4296. {
  4297. }
  4298. bool isMain;
  4299. RECT totalAreaRect, workAreaRect;
  4300. double dpi;
  4301. };
  4302. static BOOL CALLBACK enumMonitorsProc (HMONITOR hm, HDC, LPRECT, LPARAM userInfo)
  4303. {
  4304. MONITORINFO info = {};
  4305. info.cbSize = sizeof (info);
  4306. GetMonitorInfo (hm, &info);
  4307. auto isMain = (info.dwFlags & 1 /* MONITORINFOF_PRIMARY */) != 0;
  4308. auto dpi = 0.0;
  4309. if (getDPIForMonitor != nullptr)
  4310. {
  4311. UINT dpiX = 0, dpiY = 0;
  4312. if (SUCCEEDED (getDPIForMonitor (hm, MDT_Default, &dpiX, &dpiY)))
  4313. dpi = (dpiX + dpiY) / 2.0;
  4314. }
  4315. ((Array<MonitorInfo>*) userInfo)->add ({ isMain, info.rcMonitor, info.rcWork, dpi });
  4316. return TRUE;
  4317. }
  4318. void Displays::findDisplays (float masterScale)
  4319. {
  4320. setDPIAwareness();
  4321. Array<MonitorInfo> monitors;
  4322. EnumDisplayMonitors (nullptr, nullptr, &enumMonitorsProc, (LPARAM) &monitors);
  4323. auto globalDPI = getGlobalDPI();
  4324. if (monitors.size() == 0)
  4325. {
  4326. auto windowRect = getWindowScreenRect (GetDesktopWindow());
  4327. monitors.add ({ true, windowRect, windowRect, globalDPI });
  4328. }
  4329. // make sure the first in the list is the main monitor
  4330. for (int i = 1; i < monitors.size(); ++i)
  4331. if (monitors.getReference (i).isMain)
  4332. monitors.swap (i, 0);
  4333. for (auto& monitor : monitors)
  4334. {
  4335. Display d;
  4336. d.isMain = monitor.isMain;
  4337. d.dpi = monitor.dpi;
  4338. if (d.dpi == 0)
  4339. {
  4340. d.dpi = globalDPI;
  4341. d.scale = masterScale;
  4342. }
  4343. else
  4344. {
  4345. d.scale = (d.dpi / USER_DEFAULT_SCREEN_DPI) * (masterScale / Desktop::getDefaultMasterScale());
  4346. }
  4347. d.totalArea = rectangleFromRECT (monitor.totalAreaRect);
  4348. d.userArea = rectangleFromRECT (monitor.workAreaRect);
  4349. displays.add (d);
  4350. }
  4351. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  4352. if (isPerMonitorDPIAwareThread())
  4353. updateToLogical();
  4354. else
  4355. #endif
  4356. {
  4357. for (auto& d : displays)
  4358. {
  4359. d.totalArea /= masterScale;
  4360. d.userArea /= masterScale;
  4361. }
  4362. }
  4363. }
  4364. //==============================================================================
  4365. static auto extractFileHICON (const File& file)
  4366. {
  4367. WORD iconNum = 0;
  4368. WCHAR name[MAX_PATH * 2];
  4369. file.getFullPathName().copyToUTF16 (name, sizeof (name));
  4370. return IconConverters::IconPtr { ExtractAssociatedIcon ((HINSTANCE) Process::getCurrentModuleInstanceHandle(),
  4371. name,
  4372. &iconNum) };
  4373. }
  4374. Image juce_createIconForFile (const File& file)
  4375. {
  4376. if (const auto icon = extractFileHICON (file))
  4377. return IconConverters::createImageFromHICON (icon.get());
  4378. return {};
  4379. }
  4380. //==============================================================================
  4381. class MouseCursor::PlatformSpecificHandle
  4382. {
  4383. public:
  4384. explicit PlatformSpecificHandle (const MouseCursor::StandardCursorType type)
  4385. : impl (makeHandle (type)) {}
  4386. explicit PlatformSpecificHandle (const CustomMouseCursorInfo& info)
  4387. : impl (makeHandle (info)) {}
  4388. static void showInWindow (PlatformSpecificHandle* handle, ComponentPeer* peer)
  4389. {
  4390. SetCursor ([&]
  4391. {
  4392. if (handle != nullptr && handle->impl != nullptr && peer != nullptr)
  4393. return handle->impl->getCursor (*peer);
  4394. return LoadCursor (nullptr, IDC_ARROW);
  4395. }());
  4396. }
  4397. private:
  4398. struct Impl
  4399. {
  4400. virtual ~Impl() = default;
  4401. virtual HCURSOR getCursor (ComponentPeer&) = 0;
  4402. };
  4403. class BuiltinImpl : public Impl
  4404. {
  4405. public:
  4406. explicit BuiltinImpl (HCURSOR cursorIn)
  4407. : cursor (cursorIn) {}
  4408. HCURSOR getCursor (ComponentPeer&) override { return cursor; }
  4409. private:
  4410. HCURSOR cursor;
  4411. };
  4412. class ImageImpl : public Impl
  4413. {
  4414. public:
  4415. explicit ImageImpl (const CustomMouseCursorInfo& infoIn) : info (infoIn) {}
  4416. HCURSOR getCursor (ComponentPeer& peer) override
  4417. {
  4418. JUCE_ASSERT_MESSAGE_THREAD;
  4419. static auto getCursorSize = getCursorSizeForPeerFunction();
  4420. const auto size = getCursorSize (peer);
  4421. const auto iter = cursorsBySize.find (size);
  4422. if (iter != cursorsBySize.end())
  4423. return iter->second.get();
  4424. const auto logicalSize = info.image.getScaledBounds();
  4425. const auto scale = (float) size / (float) unityCursorSize;
  4426. const auto physicalSize = logicalSize * scale;
  4427. const auto& image = info.image.getImage();
  4428. const auto rescaled = image.rescaled (roundToInt ((float) physicalSize.getWidth()),
  4429. roundToInt ((float) physicalSize.getHeight()));
  4430. const auto effectiveScale = rescaled.getWidth() / logicalSize.getWidth();
  4431. const auto hx = jlimit (0, rescaled.getWidth(), roundToInt ((float) info.hotspot.x * effectiveScale));
  4432. const auto hy = jlimit (0, rescaled.getHeight(), roundToInt ((float) info.hotspot.y * effectiveScale));
  4433. return cursorsBySize.emplace (size, CursorPtr { IconConverters::createHICONFromImage (rescaled, false, hx, hy) }).first->second.get();
  4434. }
  4435. private:
  4436. struct CursorDestructor
  4437. {
  4438. void operator() (HCURSOR ptr) const { if (ptr != nullptr) DestroyCursor (ptr); }
  4439. };
  4440. using CursorPtr = std::unique_ptr<std::remove_pointer_t<HCURSOR>, CursorDestructor>;
  4441. const CustomMouseCursorInfo info;
  4442. std::map<int, CursorPtr> cursorsBySize;
  4443. };
  4444. static auto getCursorSizeForPeerFunction() -> int (*) (ComponentPeer&)
  4445. {
  4446. static const auto getDpiForMonitor = []() -> GetDPIForMonitorFunc
  4447. {
  4448. constexpr auto library = "SHCore.dll";
  4449. LoadLibraryA (library);
  4450. if (auto* handle = GetModuleHandleA (library))
  4451. return (GetDPIForMonitorFunc) GetProcAddress (handle, "GetDpiForMonitor");
  4452. return nullptr;
  4453. }();
  4454. static const auto getSystemMetricsForDpi = []() -> GetSystemMetricsForDpiFunc
  4455. {
  4456. constexpr auto library = "User32.dll";
  4457. LoadLibraryA (library);
  4458. if (auto* handle = GetModuleHandleA (library))
  4459. return (GetSystemMetricsForDpiFunc) GetProcAddress (handle, "GetSystemMetricsForDpi");
  4460. return nullptr;
  4461. }();
  4462. if (getDpiForMonitor == nullptr || getSystemMetricsForDpi == nullptr)
  4463. return [] (ComponentPeer&) { return unityCursorSize; };
  4464. return [] (ComponentPeer& p)
  4465. {
  4466. const ScopedThreadDPIAwarenessSetter threadDpiAwarenessSetter { p.getNativeHandle() };
  4467. UINT dpiX = 0, dpiY = 0;
  4468. if (auto* monitor = MonitorFromWindow ((HWND) p.getNativeHandle(), MONITOR_DEFAULTTONULL))
  4469. if (SUCCEEDED (getDpiForMonitor (monitor, MDT_Default, &dpiX, &dpiY)))
  4470. return getSystemMetricsForDpi (SM_CXCURSOR, dpiX);
  4471. return unityCursorSize;
  4472. };
  4473. }
  4474. static constexpr auto unityCursorSize = 32;
  4475. static std::unique_ptr<Impl> makeHandle (const CustomMouseCursorInfo& info)
  4476. {
  4477. return std::make_unique<ImageImpl> (info);
  4478. }
  4479. static std::unique_ptr<Impl> makeHandle (const MouseCursor::StandardCursorType type)
  4480. {
  4481. LPCTSTR cursorName = IDC_ARROW;
  4482. switch (type)
  4483. {
  4484. case NormalCursor:
  4485. case ParentCursor: break;
  4486. case NoCursor: return std::make_unique<BuiltinImpl> (nullptr);
  4487. case WaitCursor: cursorName = IDC_WAIT; break;
  4488. case IBeamCursor: cursorName = IDC_IBEAM; break;
  4489. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  4490. case CrosshairCursor: cursorName = IDC_CROSS; break;
  4491. case LeftRightResizeCursor:
  4492. case LeftEdgeResizeCursor:
  4493. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  4494. case UpDownResizeCursor:
  4495. case TopEdgeResizeCursor:
  4496. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  4497. case TopLeftCornerResizeCursor:
  4498. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  4499. case TopRightCornerResizeCursor:
  4500. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  4501. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  4502. case DraggingHandCursor:
  4503. {
  4504. static const unsigned char dragHandData[]
  4505. { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,0,0,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  4506. 16,0,0,2,52,148,47,0,200,185,16,130,90,12,74,139,107,84,123,39,132,117,151,116,132,146,248,60,209,138,
  4507. 98,22,203,114,34,236,37,52,77,217,247,154,191,119,110,240,193,128,193,95,163,56,60,234,98,135,2,0,59 };
  4508. return makeHandle ({ ScaledImage (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData))), { 8, 7 } });
  4509. }
  4510. case CopyingCursor:
  4511. {
  4512. static const unsigned char copyCursorData[]
  4513. { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,128,128,255,255,255,33,249,4,1,0,0,3,0,44,0,0,0,0,21,0,
  4514. 21,0,0,2,72,4,134,169,171,16,199,98,11,79,90,71,161,93,56,111,78,133,218,215,137,31,82,154,100,200,86,91,202,142,
  4515. 12,108,212,87,235,174, 15,54,214,126,237,226,37,96,59,141,16,37,18,201,142,157,230,204,51,112,252,114,147,74,83,
  4516. 5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  4517. return makeHandle ({ ScaledImage (ImageFileFormat::loadFrom (copyCursorData, sizeof (copyCursorData))), { 1, 3 } });
  4518. }
  4519. case NumStandardCursorTypes: JUCE_FALLTHROUGH
  4520. default:
  4521. jassertfalse; break;
  4522. }
  4523. return std::make_unique<BuiltinImpl> ([&]
  4524. {
  4525. if (auto* c = LoadCursor (nullptr, cursorName))
  4526. return c;
  4527. return LoadCursor (nullptr, IDC_ARROW);
  4528. }());
  4529. }
  4530. std::unique_ptr<Impl> impl;
  4531. };
  4532. //==============================================================================
  4533. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  4534. } // namespace juce