Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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