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.

5621 lines
200KB

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