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

4926 lines
175KB

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