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.

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