Audio plugin host https://kx.studio/carla
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.

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