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

5333 lines
189KB

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