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.

5597 lines
199KB

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