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.

5591 lines
199KB

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