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.

5387 lines
191KB

  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 (detail::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 detail::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. auto* peer = getOwnerOfWindow (m.hwnd);
  1878. if (peer == nullptr)
  1879. return false;
  1880. auto* focused = Component::getCurrentlyFocusedComponent();
  1881. if (focused == nullptr || focused->getPeer() != peer)
  1882. return false;
  1883. constexpr UINT keyMessages[] { WM_KEYDOWN,
  1884. WM_KEYUP,
  1885. WM_SYSKEYDOWN,
  1886. WM_SYSKEYUP,
  1887. WM_CHAR };
  1888. const auto messageTypeMatches = [&] (UINT msg) { return m.message == msg; };
  1889. if (std::none_of (std::begin (keyMessages), std::end (keyMessages), messageTypeMatches))
  1890. return false;
  1891. ScopedThreadDPIAwarenessSetter threadDpiAwarenessSetter { m.hwnd };
  1892. if (m.message == WM_CHAR)
  1893. return peer->doKeyChar ((int) m.wParam, m.lParam);
  1894. TranslateMessage (&m);
  1895. switch (m.message)
  1896. {
  1897. case WM_KEYDOWN:
  1898. case WM_SYSKEYDOWN:
  1899. return peer->doKeyDown (m.wParam);
  1900. case WM_KEYUP:
  1901. case WM_SYSKEYUP:
  1902. return peer->doKeyUp (m.wParam);
  1903. }
  1904. return false;
  1905. }
  1906. double getPlatformScaleFactor() const noexcept override
  1907. {
  1908. #if ! JUCE_WIN_PER_MONITOR_DPI_AWARE
  1909. return 1.0;
  1910. #else
  1911. if (! isPerMonitorDPIAwareWindow (hwnd))
  1912. return 1.0;
  1913. if (auto* parentHWND = GetParent (hwnd))
  1914. {
  1915. if (auto* parentPeer = getOwnerOfWindow (parentHWND))
  1916. return parentPeer->getPlatformScaleFactor();
  1917. if (getDPIForWindow != nullptr)
  1918. return getScaleFactorForWindow (parentHWND);
  1919. }
  1920. return scaleFactor;
  1921. #endif
  1922. }
  1923. private:
  1924. HWND hwnd, parentToAddTo;
  1925. std::unique_ptr<DropShadower> shadower;
  1926. RenderingEngineType currentRenderingEngine;
  1927. #if JUCE_DIRECT2D
  1928. std::unique_ptr<Direct2DLowLevelGraphicsContext> direct2DContext;
  1929. #endif
  1930. uint32 lastPaintTime = 0;
  1931. ULONGLONG lastMagnifySize = 0;
  1932. bool fullScreen = false, isDragging = false, isMouseOver = false,
  1933. hasCreatedCaret = false, constrainerIsResizing = false;
  1934. BorderSize<int> windowBorder;
  1935. IconConverters::IconPtr currentWindowIcon;
  1936. FileDropTarget* dropTarget = nullptr;
  1937. uint8 updateLayeredWindowAlpha = 255;
  1938. UWPUIViewSettings uwpViewSettings;
  1939. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  1940. ModifierKeyProvider* modProvider = nullptr;
  1941. #endif
  1942. double scaleFactor = 1.0;
  1943. bool inDpiChange = 0, inHandlePositionChanged = 0;
  1944. HMONITOR currentMonitor = nullptr;
  1945. bool isAccessibilityActive = false;
  1946. //==============================================================================
  1947. static MultiTouchMapper<DWORD> currentTouches;
  1948. //==============================================================================
  1949. struct TemporaryImage : private Timer
  1950. {
  1951. TemporaryImage() {}
  1952. Image& getImage (bool transparent, int w, int h)
  1953. {
  1954. auto format = transparent ? Image::ARGB : Image::RGB;
  1955. if ((! image.isValid()) || image.getWidth() < w || image.getHeight() < h || image.getFormat() != format)
  1956. image = Image (new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false));
  1957. startTimer (3000);
  1958. return image;
  1959. }
  1960. void timerCallback() override
  1961. {
  1962. stopTimer();
  1963. image = {};
  1964. }
  1965. private:
  1966. Image image;
  1967. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TemporaryImage)
  1968. };
  1969. TemporaryImage offscreenImageGenerator;
  1970. //==============================================================================
  1971. class WindowClassHolder : private DeletedAtShutdown
  1972. {
  1973. public:
  1974. WindowClassHolder()
  1975. {
  1976. // this name has to be different for each app/dll instance because otherwise poor old Windows can
  1977. // get a bit confused (even despite it not being a process-global window class).
  1978. String windowClassName ("JUCE_");
  1979. windowClassName << String::toHexString (Time::currentTimeMillis());
  1980. auto moduleHandle = (HINSTANCE) Process::getCurrentModuleInstanceHandle();
  1981. TCHAR moduleFile[1024] = {};
  1982. GetModuleFileName (moduleHandle, moduleFile, 1024);
  1983. WNDCLASSEX wcex = {};
  1984. wcex.cbSize = sizeof (wcex);
  1985. wcex.style = CS_OWNDC;
  1986. wcex.lpfnWndProc = (WNDPROC) windowProc;
  1987. wcex.lpszClassName = windowClassName.toWideCharPointer();
  1988. wcex.cbWndExtra = 32;
  1989. wcex.hInstance = moduleHandle;
  1990. for (const auto& [index, field, ptr] : { std::tuple { 0, &wcex.hIcon, &iconBig },
  1991. std::tuple { 1, &wcex.hIconSm, &iconSmall } })
  1992. {
  1993. auto iconNum = static_cast<WORD> (index);
  1994. ptr->reset (*field = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum));
  1995. }
  1996. atom = RegisterClassEx (&wcex);
  1997. jassert (atom != 0);
  1998. isEventBlockedByModalComps = checkEventBlockedByModalComps;
  1999. }
  2000. ~WindowClassHolder()
  2001. {
  2002. if (ComponentPeer::getNumPeers() == 0)
  2003. UnregisterClass (getWindowClassName(), (HINSTANCE) Process::getCurrentModuleInstanceHandle());
  2004. clearSingletonInstance();
  2005. }
  2006. LPCTSTR getWindowClassName() const noexcept { return (LPCTSTR) (pointer_sized_uint) atom; }
  2007. JUCE_DECLARE_SINGLETON_SINGLETHREADED_MINIMAL (WindowClassHolder)
  2008. private:
  2009. ATOM atom;
  2010. static bool isHWNDBlockedByModalComponents (HWND h)
  2011. {
  2012. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  2013. if (auto* c = Desktop::getInstance().getComponent (i))
  2014. if ((! c->isCurrentlyBlockedByAnotherModalComponent())
  2015. && IsChild ((HWND) c->getWindowHandle(), h))
  2016. return false;
  2017. return true;
  2018. }
  2019. static bool checkEventBlockedByModalComps (const MSG& m)
  2020. {
  2021. if (Component::getNumCurrentlyModalComponents() == 0 || JuceWindowIdentifier::isJUCEWindow (m.hwnd))
  2022. return false;
  2023. switch (m.message)
  2024. {
  2025. case WM_MOUSEMOVE:
  2026. case WM_NCMOUSEMOVE:
  2027. case 0x020A: /* WM_MOUSEWHEEL */
  2028. case 0x020E: /* WM_MOUSEHWHEEL */
  2029. case WM_KEYUP:
  2030. case WM_SYSKEYUP:
  2031. case WM_CHAR:
  2032. case WM_APPCOMMAND:
  2033. case WM_LBUTTONUP:
  2034. case WM_MBUTTONUP:
  2035. case WM_RBUTTONUP:
  2036. case WM_MOUSEACTIVATE:
  2037. case WM_NCMOUSEHOVER:
  2038. case WM_MOUSEHOVER:
  2039. case WM_TOUCH:
  2040. case WM_POINTERUPDATE:
  2041. case WM_NCPOINTERUPDATE:
  2042. case WM_POINTERWHEEL:
  2043. case WM_POINTERHWHEEL:
  2044. case WM_POINTERUP:
  2045. case WM_POINTERACTIVATE:
  2046. return isHWNDBlockedByModalComponents(m.hwnd);
  2047. case WM_NCLBUTTONDOWN:
  2048. case WM_NCLBUTTONDBLCLK:
  2049. case WM_NCRBUTTONDOWN:
  2050. case WM_NCRBUTTONDBLCLK:
  2051. case WM_NCMBUTTONDOWN:
  2052. case WM_NCMBUTTONDBLCLK:
  2053. case WM_LBUTTONDOWN:
  2054. case WM_LBUTTONDBLCLK:
  2055. case WM_MBUTTONDOWN:
  2056. case WM_MBUTTONDBLCLK:
  2057. case WM_RBUTTONDOWN:
  2058. case WM_RBUTTONDBLCLK:
  2059. case WM_KEYDOWN:
  2060. case WM_SYSKEYDOWN:
  2061. case WM_NCPOINTERDOWN:
  2062. case WM_POINTERDOWN:
  2063. if (isHWNDBlockedByModalComponents (m.hwnd))
  2064. {
  2065. if (auto* modal = Component::getCurrentlyModalComponent (0))
  2066. modal->inputAttemptWhenModal();
  2067. return true;
  2068. }
  2069. break;
  2070. default:
  2071. break;
  2072. }
  2073. return false;
  2074. }
  2075. IconConverters::IconPtr iconBig, iconSmall;
  2076. JUCE_DECLARE_NON_COPYABLE (WindowClassHolder)
  2077. };
  2078. //==============================================================================
  2079. static void* createWindowCallback (void* userData)
  2080. {
  2081. static_cast<HWNDComponentPeer*> (userData)->createWindow();
  2082. return nullptr;
  2083. }
  2084. void createWindow()
  2085. {
  2086. DWORD exstyle = 0;
  2087. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  2088. if (hasTitleBar())
  2089. {
  2090. type |= WS_OVERLAPPED;
  2091. if ((styleFlags & windowHasCloseButton) != 0)
  2092. {
  2093. type |= WS_SYSMENU;
  2094. }
  2095. else
  2096. {
  2097. // annoyingly, windows won't let you have a min/max button without a close button
  2098. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  2099. }
  2100. if ((styleFlags & windowIsResizable) != 0)
  2101. type |= WS_THICKFRAME;
  2102. }
  2103. else if (parentToAddTo != nullptr)
  2104. {
  2105. type |= WS_CHILD;
  2106. }
  2107. else
  2108. {
  2109. type |= WS_POPUP | WS_SYSMENU;
  2110. }
  2111. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  2112. exstyle |= WS_EX_TOOLWINDOW;
  2113. else
  2114. exstyle |= WS_EX_APPWINDOW;
  2115. if ((styleFlags & windowHasMinimiseButton) != 0) type |= WS_MINIMIZEBOX;
  2116. if ((styleFlags & windowHasMaximiseButton) != 0) type |= WS_MAXIMIZEBOX;
  2117. if ((styleFlags & windowIgnoresMouseClicks) != 0) exstyle |= WS_EX_TRANSPARENT;
  2118. if ((styleFlags & windowIsSemiTransparent) != 0) exstyle |= WS_EX_LAYERED;
  2119. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->getWindowClassName(),
  2120. L"", type, 0, 0, 0, 0, parentToAddTo, nullptr,
  2121. (HINSTANCE) Process::getCurrentModuleInstanceHandle(), nullptr);
  2122. #if JUCE_DEBUG
  2123. // The DPI-awareness context of this window and JUCE's hidden message window are different.
  2124. // You normally want these to match otherwise timer events and async messages will happen
  2125. // in a different context to normal HWND messages which can cause issues with UI scaling.
  2126. jassert (isPerMonitorDPIAwareWindow (hwnd) == isPerMonitorDPIAwareWindow (juce_messageWindowHandle)
  2127. || isInScopedDPIAwarenessDisabler());
  2128. #endif
  2129. if (hwnd != nullptr)
  2130. {
  2131. SetWindowLongPtr (hwnd, 0, 0);
  2132. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  2133. JuceWindowIdentifier::setAsJUCEWindow (hwnd, true);
  2134. if (dropTarget == nullptr)
  2135. {
  2136. HWNDComponentPeer* peer = nullptr;
  2137. if (dontRepaint)
  2138. peer = getOwnerOfWindow (parentToAddTo);
  2139. if (peer == nullptr)
  2140. peer = this;
  2141. dropTarget = new FileDropTarget (*peer);
  2142. }
  2143. RegisterDragDrop (hwnd, dropTarget);
  2144. if (canUseMultiTouch())
  2145. registerTouchWindow (hwnd, 0);
  2146. setDPIAwareness();
  2147. if (isPerMonitorDPIAwareThread())
  2148. scaleFactor = getScaleFactorForWindow (hwnd);
  2149. setMessageFilter();
  2150. updateBorderSize();
  2151. checkForPointerAPI();
  2152. // This is needed so that our plugin window gets notified of WM_SETTINGCHANGE messages
  2153. // and can respond to display scale changes
  2154. if (! JUCEApplication::isStandaloneApp())
  2155. settingChangeCallback = ComponentPeer::forceDisplayUpdate;
  2156. // Calling this function here is (for some reason) necessary to make Windows
  2157. // correctly enable the menu items that we specify in the wm_initmenu message.
  2158. GetSystemMenu (hwnd, false);
  2159. auto alpha = component.getAlpha();
  2160. if (alpha < 1.0f)
  2161. setAlpha (alpha);
  2162. }
  2163. else
  2164. {
  2165. TCHAR messageBuffer[256] = {};
  2166. FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  2167. nullptr, GetLastError(), MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
  2168. messageBuffer, (DWORD) numElementsInArray (messageBuffer) - 1, nullptr);
  2169. DBG (messageBuffer);
  2170. jassertfalse;
  2171. }
  2172. }
  2173. static BOOL CALLBACK revokeChildDragDropCallback (HWND hwnd, LPARAM) { RevokeDragDrop (hwnd); return TRUE; }
  2174. static void* destroyWindowCallback (void* handle)
  2175. {
  2176. auto hwnd = reinterpret_cast<HWND> (handle);
  2177. if (IsWindow (hwnd))
  2178. {
  2179. RevokeDragDrop (hwnd);
  2180. // NB: we need to do this before DestroyWindow() as child HWNDs will be invalid after
  2181. EnumChildWindows (hwnd, revokeChildDragDropCallback, 0);
  2182. DestroyWindow (hwnd);
  2183. }
  2184. return nullptr;
  2185. }
  2186. static void* toFrontCallback1 (void* h)
  2187. {
  2188. BringWindowToTop ((HWND) h);
  2189. return nullptr;
  2190. }
  2191. static void* toFrontCallback2 (void* h)
  2192. {
  2193. setWindowZOrder ((HWND) h, HWND_TOP);
  2194. return nullptr;
  2195. }
  2196. static void* setFocusCallback (void* h)
  2197. {
  2198. SetFocus ((HWND) h);
  2199. return nullptr;
  2200. }
  2201. static void* getFocusCallback (void*)
  2202. {
  2203. return GetFocus();
  2204. }
  2205. bool isUsingUpdateLayeredWindow() const
  2206. {
  2207. return ! component.isOpaque();
  2208. }
  2209. bool hasTitleBar() const noexcept { return (styleFlags & windowHasTitleBar) != 0; }
  2210. void updateShadower()
  2211. {
  2212. if (! component.isCurrentlyModal() && (styleFlags & windowHasDropShadow) != 0
  2213. && ((! hasTitleBar()) || SystemStats::getOperatingSystemType() < SystemStats::WinVista))
  2214. {
  2215. shadower = component.getLookAndFeel().createDropShadowerForComponent (component);
  2216. if (shadower != nullptr)
  2217. shadower->setOwner (&component);
  2218. }
  2219. }
  2220. void setIcon (const Image& newIcon) override
  2221. {
  2222. if (IconConverters::IconPtr hicon { IconConverters::createHICONFromImage (newIcon, TRUE, 0, 0) })
  2223. {
  2224. SendMessage (hwnd, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM> (hicon.get()));
  2225. SendMessage (hwnd, WM_SETICON, ICON_SMALL, reinterpret_cast<LPARAM> (hicon.get()));
  2226. currentWindowIcon = std::move (hicon);
  2227. }
  2228. }
  2229. void setMessageFilter()
  2230. {
  2231. using ChangeWindowMessageFilterExFunc = BOOL (WINAPI*) (HWND, UINT, DWORD, PVOID);
  2232. static auto changeMessageFilter = (ChangeWindowMessageFilterExFunc) getUser32Function ("ChangeWindowMessageFilterEx");
  2233. if (changeMessageFilter != nullptr)
  2234. {
  2235. changeMessageFilter (hwnd, WM_DROPFILES, 1 /*MSGFLT_ALLOW*/, nullptr);
  2236. changeMessageFilter (hwnd, WM_COPYDATA, 1 /*MSGFLT_ALLOW*/, nullptr);
  2237. changeMessageFilter (hwnd, 0x49, 1 /*MSGFLT_ALLOW*/, nullptr);
  2238. }
  2239. }
  2240. struct ChildWindowClippingInfo
  2241. {
  2242. HDC dc;
  2243. HWNDComponentPeer* peer;
  2244. RectangleList<int>* clip;
  2245. Point<int> origin;
  2246. int savedDC;
  2247. };
  2248. static BOOL CALLBACK clipChildWindowCallback (HWND hwnd, LPARAM context)
  2249. {
  2250. if (IsWindowVisible (hwnd))
  2251. {
  2252. auto& info = *(ChildWindowClippingInfo*) context;
  2253. if (GetParent (hwnd) == info.peer->hwnd)
  2254. {
  2255. auto clip = rectangleFromRECT (getWindowClientRect (hwnd));
  2256. info.clip->subtract (clip - info.origin);
  2257. if (info.savedDC == 0)
  2258. info.savedDC = SaveDC (info.dc);
  2259. ExcludeClipRect (info.dc, clip.getX(), clip.getY(), clip.getRight(), clip.getBottom());
  2260. }
  2261. }
  2262. return TRUE;
  2263. }
  2264. //==============================================================================
  2265. void handlePaintMessage()
  2266. {
  2267. #if JUCE_DIRECT2D
  2268. if (direct2DContext != nullptr)
  2269. {
  2270. RECT r;
  2271. if (GetUpdateRect (hwnd, &r, false))
  2272. {
  2273. direct2DContext->start();
  2274. direct2DContext->clipToRectangle (convertPhysicalScreenRectangleToLogical (rectangleFromRECT (r), hwnd));
  2275. handlePaint (*direct2DContext);
  2276. direct2DContext->end();
  2277. ValidateRect (hwnd, &r);
  2278. }
  2279. }
  2280. else
  2281. #endif
  2282. {
  2283. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  2284. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  2285. PAINTSTRUCT paintStruct;
  2286. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  2287. // message and become re-entrant, but that's OK
  2288. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  2289. // corrupt the image it's using to paint into, so do a check here.
  2290. static bool reentrant = false;
  2291. if (! reentrant)
  2292. {
  2293. const ScopedValueSetter<bool> setter (reentrant, true, false);
  2294. if (dontRepaint)
  2295. component.handleCommandMessage (0); // (this triggers a repaint in the openGL context)
  2296. else
  2297. performPaint (dc, rgn, regionType, paintStruct);
  2298. }
  2299. DeleteObject (rgn);
  2300. EndPaint (hwnd, &paintStruct);
  2301. #if JUCE_MSVC
  2302. _fpreset(); // because some graphics cards can unmask FP exceptions
  2303. #endif
  2304. }
  2305. lastPaintTime = Time::getMillisecondCounter();
  2306. }
  2307. void performPaint (HDC dc, HRGN rgn, int regionType, PAINTSTRUCT& paintStruct)
  2308. {
  2309. int x = paintStruct.rcPaint.left;
  2310. int y = paintStruct.rcPaint.top;
  2311. int w = paintStruct.rcPaint.right - x;
  2312. int h = paintStruct.rcPaint.bottom - y;
  2313. const bool transparent = isUsingUpdateLayeredWindow();
  2314. if (transparent)
  2315. {
  2316. // it's not possible to have a transparent window with a title bar at the moment!
  2317. jassert (! hasTitleBar());
  2318. auto r = getWindowScreenRect (hwnd);
  2319. x = y = 0;
  2320. w = r.right - r.left;
  2321. h = r.bottom - r.top;
  2322. }
  2323. if (w > 0 && h > 0)
  2324. {
  2325. Image& offscreenImage = offscreenImageGenerator.getImage (transparent, w, h);
  2326. RectangleList<int> contextClip;
  2327. const Rectangle<int> clipBounds (w, h);
  2328. bool needToPaintAll = true;
  2329. if (regionType == COMPLEXREGION && ! transparent)
  2330. {
  2331. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  2332. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  2333. DeleteObject (clipRgn);
  2334. std::aligned_storage_t<8192, alignof (RGNDATA)> rgnData;
  2335. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) &rgnData);
  2336. if (res > 0 && res <= sizeof (rgnData))
  2337. {
  2338. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) &rgnData)->rdh);
  2339. if (hdr->iType == RDH_RECTANGLES
  2340. && hdr->rcBound.right - hdr->rcBound.left >= w
  2341. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  2342. {
  2343. needToPaintAll = false;
  2344. auto rects = unalignedPointerCast<const RECT*> ((char*) &rgnData + sizeof (RGNDATAHEADER));
  2345. for (int i = (int) ((RGNDATA*) &rgnData)->rdh.nCount; --i >= 0;)
  2346. {
  2347. if (rects->right <= x + w && rects->bottom <= y + h)
  2348. {
  2349. const int cx = jmax (x, (int) rects->left);
  2350. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y,
  2351. rects->right - cx, rects->bottom - rects->top)
  2352. .getIntersection (clipBounds));
  2353. }
  2354. else
  2355. {
  2356. needToPaintAll = true;
  2357. break;
  2358. }
  2359. ++rects;
  2360. }
  2361. }
  2362. }
  2363. }
  2364. if (needToPaintAll)
  2365. {
  2366. contextClip.clear();
  2367. contextClip.addWithoutMerging (Rectangle<int> (w, h));
  2368. }
  2369. ChildWindowClippingInfo childClipInfo = { dc, this, &contextClip, Point<int> (x, y), 0 };
  2370. EnumChildWindows (hwnd, clipChildWindowCallback, (LPARAM) &childClipInfo);
  2371. if (! contextClip.isEmpty())
  2372. {
  2373. if (transparent)
  2374. for (auto& i : contextClip)
  2375. offscreenImage.clear (i);
  2376. {
  2377. auto context = component.getLookAndFeel()
  2378. .createGraphicsContext (offscreenImage, { -x, -y }, contextClip);
  2379. context->addTransform (AffineTransform::scale ((float) getPlatformScaleFactor()));
  2380. handlePaint (*context);
  2381. }
  2382. static_cast<WindowsBitmapImage*> (offscreenImage.getPixelData())
  2383. ->blitToWindow (hwnd, dc, transparent, x, y, updateLayeredWindowAlpha);
  2384. }
  2385. if (childClipInfo.savedDC != 0)
  2386. RestoreDC (dc, childClipInfo.savedDC);
  2387. }
  2388. }
  2389. //==============================================================================
  2390. void doMouseEvent (Point<float> position, float pressure, float orientation = 0.0f, ModifierKeys mods = ModifierKeys::currentModifiers)
  2391. {
  2392. handleMouseEvent (MouseInputSource::InputSourceType::mouse, position, mods, pressure, orientation, getMouseEventTime());
  2393. }
  2394. StringArray getAvailableRenderingEngines() override
  2395. {
  2396. StringArray s ("Software Renderer");
  2397. #if JUCE_DIRECT2D
  2398. if (SystemStats::getOperatingSystemType() >= SystemStats::Windows7)
  2399. s.add ("Direct2D");
  2400. #endif
  2401. return s;
  2402. }
  2403. int getCurrentRenderingEngine() const override { return currentRenderingEngine; }
  2404. #if JUCE_DIRECT2D
  2405. void updateDirect2DContext()
  2406. {
  2407. if (currentRenderingEngine != direct2DRenderingEngine)
  2408. direct2DContext = nullptr;
  2409. else if (direct2DContext == nullptr)
  2410. direct2DContext.reset (new Direct2DLowLevelGraphicsContext (hwnd));
  2411. }
  2412. #endif
  2413. void setCurrentRenderingEngine ([[maybe_unused]] int index) override
  2414. {
  2415. #if JUCE_DIRECT2D
  2416. if (getAvailableRenderingEngines().size() > 1)
  2417. {
  2418. currentRenderingEngine = index == 1 ? direct2DRenderingEngine : softwareRenderingEngine;
  2419. updateDirect2DContext();
  2420. repaint (component.getLocalBounds());
  2421. }
  2422. #endif
  2423. }
  2424. static uint32 getMinTimeBetweenMouseMoves()
  2425. {
  2426. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  2427. return 0;
  2428. return 1000 / 60; // Throttling the incoming mouse-events seems to still be needed in XP..
  2429. }
  2430. bool isTouchEvent() noexcept
  2431. {
  2432. if (registerTouchWindow == nullptr)
  2433. return false;
  2434. // Relevant info about touch/pen detection flags:
  2435. // https://msdn.microsoft.com/en-us/library/windows/desktop/ms703320(v=vs.85).aspx
  2436. // http://www.petertissen.de/?p=4
  2437. return ((uint32_t) GetMessageExtraInfo() & 0xFFFFFF80 /*SIGNATURE_MASK*/) == 0xFF515780 /*MI_WP_SIGNATURE*/;
  2438. }
  2439. static bool areOtherTouchSourcesActive()
  2440. {
  2441. for (auto& ms : Desktop::getInstance().getMouseSources())
  2442. if (ms.isDragging() && (ms.getType() == MouseInputSource::InputSourceType::touch
  2443. || ms.getType() == MouseInputSource::InputSourceType::pen))
  2444. return true;
  2445. return false;
  2446. }
  2447. void doMouseMove (Point<float> position, bool isMouseDownEvent)
  2448. {
  2449. ModifierKeys modsToSend (ModifierKeys::currentModifiers);
  2450. // this will be handled by WM_TOUCH
  2451. if (isTouchEvent() || areOtherTouchSourcesActive())
  2452. return;
  2453. if (! isMouseOver)
  2454. {
  2455. isMouseOver = true;
  2456. // This avoids a rare stuck-button problem when focus is lost unexpectedly, but must
  2457. // not be called as part of a move, in case it's actually a mouse-drag from another
  2458. // app which ends up here when we get focus before the mouse is released..
  2459. if (isMouseDownEvent && getNativeRealtimeModifiers != nullptr)
  2460. getNativeRealtimeModifiers();
  2461. updateKeyModifiers();
  2462. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  2463. if (modProvider != nullptr)
  2464. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withFlags (modProvider->getWin32Modifiers());
  2465. #endif
  2466. TRACKMOUSEEVENT tme;
  2467. tme.cbSize = sizeof (tme);
  2468. tme.dwFlags = TME_LEAVE;
  2469. tme.hwndTrack = hwnd;
  2470. tme.dwHoverTime = 0;
  2471. if (! TrackMouseEvent (&tme))
  2472. jassertfalse;
  2473. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  2474. }
  2475. else if (! isDragging)
  2476. {
  2477. if (! contains (position.roundToInt(), false))
  2478. return;
  2479. }
  2480. static uint32 lastMouseTime = 0;
  2481. static auto minTimeBetweenMouses = getMinTimeBetweenMouseMoves();
  2482. auto now = Time::getMillisecondCounter();
  2483. if (! Desktop::getInstance().getMainMouseSource().isDragging())
  2484. modsToSend = modsToSend.withoutMouseButtons();
  2485. if (now >= lastMouseTime + minTimeBetweenMouses)
  2486. {
  2487. lastMouseTime = now;
  2488. doMouseEvent (position, MouseInputSource::defaultPressure,
  2489. MouseInputSource::defaultOrientation, modsToSend);
  2490. }
  2491. }
  2492. void doMouseDown (Point<float> position, const WPARAM wParam)
  2493. {
  2494. // this will be handled by WM_TOUCH
  2495. if (isTouchEvent() || areOtherTouchSourcesActive())
  2496. return;
  2497. if (GetCapture() != hwnd)
  2498. SetCapture (hwnd);
  2499. doMouseMove (position, true);
  2500. if (isValidPeer (this))
  2501. {
  2502. updateModifiersFromWParam (wParam);
  2503. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  2504. if (modProvider != nullptr)
  2505. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withFlags (modProvider->getWin32Modifiers());
  2506. #endif
  2507. isDragging = true;
  2508. doMouseEvent (position, MouseInputSource::defaultPressure);
  2509. }
  2510. }
  2511. void doMouseUp (Point<float> position, const WPARAM wParam)
  2512. {
  2513. // this will be handled by WM_TOUCH
  2514. if (isTouchEvent() || areOtherTouchSourcesActive())
  2515. return;
  2516. updateModifiersFromWParam (wParam);
  2517. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  2518. if (modProvider != nullptr)
  2519. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withFlags (modProvider->getWin32Modifiers());
  2520. #endif
  2521. const bool wasDragging = isDragging;
  2522. isDragging = false;
  2523. // release the mouse capture if the user has released all buttons
  2524. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  2525. ReleaseCapture();
  2526. // NB: under some circumstances (e.g. double-clicking a native title bar), a mouse-up can
  2527. // arrive without a mouse-down, so in that case we need to avoid sending a message.
  2528. if (wasDragging)
  2529. doMouseEvent (position, MouseInputSource::defaultPressure);
  2530. }
  2531. void doCaptureChanged()
  2532. {
  2533. if (constrainerIsResizing)
  2534. {
  2535. if (constrainer != nullptr)
  2536. constrainer->resizeEnd();
  2537. constrainerIsResizing = false;
  2538. }
  2539. if (isDragging)
  2540. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  2541. }
  2542. void doMouseExit()
  2543. {
  2544. isMouseOver = false;
  2545. if (! areOtherTouchSourcesActive())
  2546. doMouseEvent (getCurrentMousePos(), MouseInputSource::defaultPressure);
  2547. }
  2548. ComponentPeer* findPeerUnderMouse (Point<float>& localPos)
  2549. {
  2550. auto currentMousePos = getPOINTFromLParam ((LPARAM) GetMessagePos());
  2551. // Because Windows stupidly sends all wheel events to the window with the keyboard
  2552. // focus, we have to redirect them here according to the mouse pos..
  2553. auto* peer = getOwnerOfWindow (WindowFromPoint (currentMousePos));
  2554. if (peer == nullptr)
  2555. peer = this;
  2556. localPos = peer->globalToLocal (convertPhysicalScreenPointToLogical (pointFromPOINT (currentMousePos), hwnd).toFloat());
  2557. return peer;
  2558. }
  2559. static MouseInputSource::InputSourceType getPointerType (WPARAM wParam)
  2560. {
  2561. if (getPointerTypeFunction != nullptr)
  2562. {
  2563. POINTER_INPUT_TYPE pointerType;
  2564. if (getPointerTypeFunction (GET_POINTERID_WPARAM (wParam), &pointerType))
  2565. {
  2566. if (pointerType == 2)
  2567. return MouseInputSource::InputSourceType::touch;
  2568. if (pointerType == 3)
  2569. return MouseInputSource::InputSourceType::pen;
  2570. }
  2571. }
  2572. return MouseInputSource::InputSourceType::mouse;
  2573. }
  2574. void doMouseWheel (const WPARAM wParam, const bool isVertical)
  2575. {
  2576. updateKeyModifiers();
  2577. const float amount = jlimit (-1000.0f, 1000.0f, 0.5f * (short) HIWORD (wParam));
  2578. MouseWheelDetails wheel;
  2579. wheel.deltaX = isVertical ? 0.0f : amount / -256.0f;
  2580. wheel.deltaY = isVertical ? amount / 256.0f : 0.0f;
  2581. wheel.isReversed = false;
  2582. wheel.isSmooth = false;
  2583. wheel.isInertial = false;
  2584. Point<float> localPos;
  2585. if (auto* peer = findPeerUnderMouse (localPos))
  2586. peer->handleMouseWheel (getPointerType (wParam), localPos, getMouseEventTime(), wheel);
  2587. }
  2588. bool doGestureEvent (LPARAM lParam)
  2589. {
  2590. GESTUREINFO gi;
  2591. zerostruct (gi);
  2592. gi.cbSize = sizeof (gi);
  2593. if (getGestureInfo != nullptr && getGestureInfo ((HGESTUREINFO) lParam, &gi))
  2594. {
  2595. updateKeyModifiers();
  2596. Point<float> localPos;
  2597. if (auto* peer = findPeerUnderMouse (localPos))
  2598. {
  2599. switch (gi.dwID)
  2600. {
  2601. case 3: /*GID_ZOOM*/
  2602. if (gi.dwFlags != 1 /*GF_BEGIN*/ && lastMagnifySize > 0)
  2603. peer->handleMagnifyGesture (MouseInputSource::InputSourceType::touch, localPos, getMouseEventTime(),
  2604. (float) ((double) gi.ullArguments / (double) lastMagnifySize));
  2605. lastMagnifySize = gi.ullArguments;
  2606. return true;
  2607. case 4: /*GID_PAN*/
  2608. case 5: /*GID_ROTATE*/
  2609. case 6: /*GID_TWOFINGERTAP*/
  2610. case 7: /*GID_PRESSANDTAP*/
  2611. default:
  2612. break;
  2613. }
  2614. }
  2615. }
  2616. return false;
  2617. }
  2618. LRESULT doTouchEvent (const int numInputs, HTOUCHINPUT eventHandle)
  2619. {
  2620. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  2621. if (auto* parent = getOwnerOfWindow (GetParent (hwnd)))
  2622. if (parent != this)
  2623. return parent->doTouchEvent (numInputs, eventHandle);
  2624. HeapBlock<TOUCHINPUT> inputInfo (numInputs);
  2625. if (getTouchInputInfo (eventHandle, (UINT) numInputs, inputInfo, sizeof (TOUCHINPUT)))
  2626. {
  2627. for (int i = 0; i < numInputs; ++i)
  2628. {
  2629. auto flags = inputInfo[i].dwFlags;
  2630. if ((flags & (TOUCHEVENTF_DOWN | TOUCHEVENTF_MOVE | TOUCHEVENTF_UP)) != 0)
  2631. if (! handleTouchInput (inputInfo[i], (flags & TOUCHEVENTF_DOWN) != 0, (flags & TOUCHEVENTF_UP) != 0))
  2632. return 0; // abandon method if this window was deleted by the callback
  2633. }
  2634. }
  2635. closeTouchInputHandle (eventHandle);
  2636. return 0;
  2637. }
  2638. bool handleTouchInput (const TOUCHINPUT& touch, const bool isDown, const bool isUp,
  2639. const float touchPressure = MouseInputSource::defaultPressure,
  2640. const float orientation = 0.0f)
  2641. {
  2642. auto isCancel = false;
  2643. const auto touchIndex = currentTouches.getIndexOfTouch (this, touch.dwID);
  2644. const auto time = getMouseEventTime();
  2645. const auto pos = globalToLocal (convertPhysicalScreenPointToLogical (pointFromPOINT ({ roundToInt (touch.x / 100.0f),
  2646. roundToInt (touch.y / 100.0f) }), hwnd).toFloat());
  2647. const auto pressure = touchPressure;
  2648. auto modsToSend = ModifierKeys::currentModifiers;
  2649. if (isDown)
  2650. {
  2651. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  2652. modsToSend = ModifierKeys::currentModifiers;
  2653. // this forces a mouse-enter/up event, in case for some reason we didn't get a mouse-up before.
  2654. handleMouseEvent (MouseInputSource::InputSourceType::touch, pos, modsToSend.withoutMouseButtons(),
  2655. pressure, orientation, time, {}, touchIndex);
  2656. if (! isValidPeer (this)) // (in case this component was deleted by the event)
  2657. return false;
  2658. }
  2659. else if (isUp)
  2660. {
  2661. modsToSend = modsToSend.withoutMouseButtons();
  2662. ModifierKeys::currentModifiers = modsToSend;
  2663. currentTouches.clearTouch (touchIndex);
  2664. if (! currentTouches.areAnyTouchesActive())
  2665. isCancel = true;
  2666. }
  2667. else
  2668. {
  2669. modsToSend = ModifierKeys::currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  2670. }
  2671. handleMouseEvent (MouseInputSource::InputSourceType::touch, pos, modsToSend,
  2672. pressure, orientation, time, {}, touchIndex);
  2673. if (! isValidPeer (this))
  2674. return false;
  2675. if (isUp)
  2676. {
  2677. handleMouseEvent (MouseInputSource::InputSourceType::touch, MouseInputSource::offscreenMousePos, ModifierKeys::currentModifiers.withoutMouseButtons(),
  2678. pressure, orientation, time, {}, touchIndex);
  2679. if (! isValidPeer (this))
  2680. return false;
  2681. if (isCancel)
  2682. {
  2683. currentTouches.clear();
  2684. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons();
  2685. }
  2686. }
  2687. return true;
  2688. }
  2689. bool handlePointerInput (WPARAM wParam, LPARAM lParam, const bool isDown, const bool isUp)
  2690. {
  2691. if (! canUsePointerAPI)
  2692. return false;
  2693. auto pointerType = getPointerType (wParam);
  2694. if (pointerType == MouseInputSource::InputSourceType::touch)
  2695. {
  2696. POINTER_TOUCH_INFO touchInfo;
  2697. if (! getPointerTouchInfo (GET_POINTERID_WPARAM (wParam), &touchInfo))
  2698. return false;
  2699. const auto pressure = touchInfo.touchMask & TOUCH_MASK_PRESSURE ? static_cast<float> (touchInfo.pressure)
  2700. : MouseInputSource::defaultPressure;
  2701. const auto orientation = touchInfo.touchMask & TOUCH_MASK_ORIENTATION ? degreesToRadians (static_cast<float> (touchInfo.orientation))
  2702. : MouseInputSource::defaultOrientation;
  2703. if (! handleTouchInput (emulateTouchEventFromPointer (touchInfo.pointerInfo.ptPixelLocationRaw, wParam),
  2704. isDown, isUp, pressure, orientation))
  2705. return false;
  2706. }
  2707. else if (pointerType == MouseInputSource::InputSourceType::pen)
  2708. {
  2709. POINTER_PEN_INFO penInfo;
  2710. if (! getPointerPenInfo (GET_POINTERID_WPARAM (wParam), &penInfo))
  2711. return false;
  2712. const auto pressure = (penInfo.penMask & PEN_MASK_PRESSURE) ? (float) penInfo.pressure / 1024.0f : MouseInputSource::defaultPressure;
  2713. if (! handlePenInput (penInfo, globalToLocal (convertPhysicalScreenPointToLogical (pointFromPOINT (getPOINTFromLParam (lParam)), hwnd).toFloat()),
  2714. pressure, isDown, isUp))
  2715. return false;
  2716. }
  2717. else
  2718. {
  2719. return false;
  2720. }
  2721. return true;
  2722. }
  2723. TOUCHINPUT emulateTouchEventFromPointer (POINT p, WPARAM wParam)
  2724. {
  2725. TOUCHINPUT touchInput;
  2726. touchInput.dwID = GET_POINTERID_WPARAM (wParam);
  2727. touchInput.x = p.x * 100;
  2728. touchInput.y = p.y * 100;
  2729. return touchInput;
  2730. }
  2731. bool handlePenInput (POINTER_PEN_INFO penInfo, Point<float> pos, const float pressure, bool isDown, bool isUp)
  2732. {
  2733. const auto time = getMouseEventTime();
  2734. ModifierKeys modsToSend (ModifierKeys::currentModifiers);
  2735. PenDetails penDetails;
  2736. penDetails.rotation = (penInfo.penMask & PEN_MASK_ROTATION) ? degreesToRadians (static_cast<float> (penInfo.rotation)) : MouseInputSource::defaultRotation;
  2737. penDetails.tiltX = (penInfo.penMask & PEN_MASK_TILT_X) ? (float) penInfo.tiltX / 90.0f : MouseInputSource::defaultTiltX;
  2738. penDetails.tiltY = (penInfo.penMask & PEN_MASK_TILT_Y) ? (float) penInfo.tiltY / 90.0f : MouseInputSource::defaultTiltY;
  2739. auto pInfoFlags = penInfo.pointerInfo.pointerFlags;
  2740. if ((pInfoFlags & POINTER_FLAG_FIRSTBUTTON) != 0)
  2741. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  2742. else if ((pInfoFlags & POINTER_FLAG_SECONDBUTTON) != 0)
  2743. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::rightButtonModifier);
  2744. if (isDown)
  2745. {
  2746. modsToSend = ModifierKeys::currentModifiers;
  2747. // this forces a mouse-enter/up event, in case for some reason we didn't get a mouse-up before.
  2748. handleMouseEvent (MouseInputSource::InputSourceType::pen, pos, modsToSend.withoutMouseButtons(),
  2749. pressure, MouseInputSource::defaultOrientation, time, penDetails);
  2750. if (! isValidPeer (this)) // (in case this component was deleted by the event)
  2751. return false;
  2752. }
  2753. else if (isUp || ! (pInfoFlags & POINTER_FLAG_INCONTACT))
  2754. {
  2755. modsToSend = modsToSend.withoutMouseButtons();
  2756. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons();
  2757. }
  2758. handleMouseEvent (MouseInputSource::InputSourceType::pen, pos, modsToSend, pressure,
  2759. MouseInputSource::defaultOrientation, time, penDetails);
  2760. if (! isValidPeer (this)) // (in case this component was deleted by the event)
  2761. return false;
  2762. if (isUp)
  2763. {
  2764. handleMouseEvent (MouseInputSource::InputSourceType::pen, MouseInputSource::offscreenMousePos, ModifierKeys::currentModifiers,
  2765. pressure, MouseInputSource::defaultOrientation, time, penDetails);
  2766. if (! isValidPeer (this))
  2767. return false;
  2768. }
  2769. return true;
  2770. }
  2771. //==============================================================================
  2772. void sendModifierKeyChangeIfNeeded()
  2773. {
  2774. if (modifiersAtLastCallback != ModifierKeys::currentModifiers)
  2775. {
  2776. modifiersAtLastCallback = ModifierKeys::currentModifiers;
  2777. handleModifierKeysChange();
  2778. }
  2779. }
  2780. bool doKeyUp (const WPARAM key)
  2781. {
  2782. updateKeyModifiers();
  2783. switch (key)
  2784. {
  2785. case VK_SHIFT:
  2786. case VK_CONTROL:
  2787. case VK_MENU:
  2788. case VK_CAPITAL:
  2789. case VK_LWIN:
  2790. case VK_RWIN:
  2791. case VK_APPS:
  2792. case VK_NUMLOCK:
  2793. case VK_SCROLL:
  2794. case VK_LSHIFT:
  2795. case VK_RSHIFT:
  2796. case VK_LCONTROL:
  2797. case VK_LMENU:
  2798. case VK_RCONTROL:
  2799. case VK_RMENU:
  2800. sendModifierKeyChangeIfNeeded();
  2801. }
  2802. return handleKeyUpOrDown (false)
  2803. || Component::getCurrentlyModalComponent() != nullptr;
  2804. }
  2805. bool doKeyDown (const WPARAM key)
  2806. {
  2807. updateKeyModifiers();
  2808. bool used = false;
  2809. switch (key)
  2810. {
  2811. case VK_SHIFT:
  2812. case VK_LSHIFT:
  2813. case VK_RSHIFT:
  2814. case VK_CONTROL:
  2815. case VK_LCONTROL:
  2816. case VK_RCONTROL:
  2817. case VK_MENU:
  2818. case VK_LMENU:
  2819. case VK_RMENU:
  2820. case VK_LWIN:
  2821. case VK_RWIN:
  2822. case VK_CAPITAL:
  2823. case VK_NUMLOCK:
  2824. case VK_SCROLL:
  2825. case VK_APPS:
  2826. used = handleKeyUpOrDown (true);
  2827. sendModifierKeyChangeIfNeeded();
  2828. break;
  2829. case VK_LEFT:
  2830. case VK_RIGHT:
  2831. case VK_UP:
  2832. case VK_DOWN:
  2833. case VK_PRIOR:
  2834. case VK_NEXT:
  2835. case VK_HOME:
  2836. case VK_END:
  2837. case VK_DELETE:
  2838. case VK_INSERT:
  2839. case VK_F1:
  2840. case VK_F2:
  2841. case VK_F3:
  2842. case VK_F4:
  2843. case VK_F5:
  2844. case VK_F6:
  2845. case VK_F7:
  2846. case VK_F8:
  2847. case VK_F9:
  2848. case VK_F10:
  2849. case VK_F11:
  2850. case VK_F12:
  2851. case VK_F13:
  2852. case VK_F14:
  2853. case VK_F15:
  2854. case VK_F16:
  2855. case VK_F17:
  2856. case VK_F18:
  2857. case VK_F19:
  2858. case VK_F20:
  2859. case VK_F21:
  2860. case VK_F22:
  2861. case VK_F23:
  2862. case VK_F24:
  2863. used = handleKeyUpOrDown (true);
  2864. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  2865. break;
  2866. default:
  2867. used = handleKeyUpOrDown (true);
  2868. {
  2869. MSG msg;
  2870. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  2871. {
  2872. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  2873. // manually generate the key-press event that matches this key-down.
  2874. const UINT keyChar = MapVirtualKey ((UINT) key, 2);
  2875. const UINT scanCode = MapVirtualKey ((UINT) key, 0);
  2876. BYTE keyState[256];
  2877. [[maybe_unused]] const auto state = GetKeyboardState (keyState);
  2878. WCHAR text[16] = { 0 };
  2879. if (ToUnicode ((UINT) key, scanCode, keyState, text, 8, 0) != 1)
  2880. text[0] = 0;
  2881. used = handleKeyPress ((int) LOWORD (keyChar), (juce_wchar) text[0]) || used;
  2882. }
  2883. }
  2884. break;
  2885. }
  2886. return used || (Component::getCurrentlyModalComponent() != nullptr);
  2887. }
  2888. bool doKeyChar (int key, const LPARAM flags)
  2889. {
  2890. updateKeyModifiers();
  2891. auto textChar = (juce_wchar) key;
  2892. const int virtualScanCode = (flags >> 16) & 0xff;
  2893. if (key >= '0' && key <= '9')
  2894. {
  2895. switch (virtualScanCode) // check for a numeric keypad scan-code
  2896. {
  2897. case 0x52:
  2898. case 0x4f:
  2899. case 0x50:
  2900. case 0x51:
  2901. case 0x4b:
  2902. case 0x4c:
  2903. case 0x4d:
  2904. case 0x47:
  2905. case 0x48:
  2906. case 0x49:
  2907. key = (key - '0') + KeyPress::numberPad0;
  2908. break;
  2909. default:
  2910. break;
  2911. }
  2912. }
  2913. else
  2914. {
  2915. // convert the scan code to an unmodified character code..
  2916. const UINT virtualKey = MapVirtualKey ((UINT) virtualScanCode, 1);
  2917. UINT keyChar = MapVirtualKey (virtualKey, 2);
  2918. keyChar = LOWORD (keyChar);
  2919. if (keyChar != 0)
  2920. key = (int) keyChar;
  2921. // avoid sending junk text characters for some control-key combinations
  2922. if (textChar < ' ' && ModifierKeys::currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  2923. textChar = 0;
  2924. }
  2925. return handleKeyPress (key, textChar);
  2926. }
  2927. void forwardMessageToParent (UINT message, WPARAM wParam, LPARAM lParam) const
  2928. {
  2929. if (HWND parentH = GetParent (hwnd))
  2930. PostMessage (parentH, message, wParam, lParam);
  2931. }
  2932. bool doAppCommand (const LPARAM lParam)
  2933. {
  2934. int key = 0;
  2935. switch (GET_APPCOMMAND_LPARAM (lParam))
  2936. {
  2937. case APPCOMMAND_MEDIA_PLAY_PAUSE: key = KeyPress::playKey; break;
  2938. case APPCOMMAND_MEDIA_STOP: key = KeyPress::stopKey; break;
  2939. case APPCOMMAND_MEDIA_NEXTTRACK: key = KeyPress::fastForwardKey; break;
  2940. case APPCOMMAND_MEDIA_PREVIOUSTRACK: key = KeyPress::rewindKey; break;
  2941. default: break;
  2942. }
  2943. if (key != 0)
  2944. {
  2945. updateKeyModifiers();
  2946. if (hwnd == GetActiveWindow())
  2947. return handleKeyPress (key, 0);
  2948. }
  2949. return false;
  2950. }
  2951. bool isConstrainedNativeWindow() const
  2952. {
  2953. return constrainer != nullptr
  2954. && (styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable)
  2955. && ! isKioskMode();
  2956. }
  2957. Rectangle<int> getCurrentScaledBounds() const
  2958. {
  2959. return detail::ScalingHelpers::unscaledScreenPosToScaled (component, windowBorder.addedTo (detail::ScalingHelpers::scaledScreenPosToUnscaled (component, component.getBounds())));
  2960. }
  2961. LRESULT handleSizeConstraining (RECT& r, const WPARAM wParam)
  2962. {
  2963. if (isConstrainedNativeWindow())
  2964. {
  2965. const auto logicalBounds = convertPhysicalScreenRectangleToLogical (rectangleFromRECT (r).toFloat(), hwnd);
  2966. auto pos = detail::ScalingHelpers::unscaledScreenPosToScaled (component, logicalBounds).toNearestInt();
  2967. const auto original = getCurrentScaledBounds();
  2968. constrainer->checkBounds (pos, original,
  2969. Desktop::getInstance().getDisplays().getTotalBounds (true),
  2970. wParam == WMSZ_TOP || wParam == WMSZ_TOPLEFT || wParam == WMSZ_TOPRIGHT,
  2971. wParam == WMSZ_LEFT || wParam == WMSZ_TOPLEFT || wParam == WMSZ_BOTTOMLEFT,
  2972. wParam == WMSZ_BOTTOM || wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_BOTTOMRIGHT,
  2973. wParam == WMSZ_RIGHT || wParam == WMSZ_TOPRIGHT || wParam == WMSZ_BOTTOMRIGHT);
  2974. r = RECTFromRectangle (convertLogicalScreenRectangleToPhysical (detail::ScalingHelpers::scaledScreenPosToUnscaled (component, pos.toFloat()).toNearestInt(), hwnd));
  2975. }
  2976. return TRUE;
  2977. }
  2978. LRESULT handlePositionChanging (WINDOWPOS& wp)
  2979. {
  2980. if (isConstrainedNativeWindow() && ! isFullScreen())
  2981. {
  2982. if ((wp.flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE)
  2983. && (wp.x > -32000 && wp.y > -32000)
  2984. && ! Component::isMouseButtonDownAnywhere())
  2985. {
  2986. const auto logicalBounds = convertPhysicalScreenRectangleToLogical (rectangleFromRECT ({ wp.x, wp.y, wp.x + wp.cx, wp.y + wp.cy }).toFloat(), hwnd);
  2987. auto pos = detail::ScalingHelpers::unscaledScreenPosToScaled (component, logicalBounds).toNearestInt();
  2988. const auto original = getCurrentScaledBounds();
  2989. constrainer->checkBounds (pos, original,
  2990. Desktop::getInstance().getDisplays().getTotalBounds (true),
  2991. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  2992. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  2993. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  2994. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  2995. auto physicalBounds = convertLogicalScreenRectangleToPhysical (detail::ScalingHelpers::scaledScreenPosToUnscaled (component, pos.toFloat()), hwnd);
  2996. auto getNewPositionIfNotRoundingError = [] (int posIn, float newPos)
  2997. {
  2998. return (std::abs ((float) posIn - newPos) >= 1.0f) ? roundToInt (newPos) : posIn;
  2999. };
  3000. wp.x = getNewPositionIfNotRoundingError (wp.x, physicalBounds.getX());
  3001. wp.y = getNewPositionIfNotRoundingError (wp.y, physicalBounds.getY());
  3002. wp.cx = getNewPositionIfNotRoundingError (wp.cx, physicalBounds.getWidth());
  3003. wp.cy = getNewPositionIfNotRoundingError (wp.cy, physicalBounds.getHeight());
  3004. }
  3005. }
  3006. if (((wp.flags & SWP_SHOWWINDOW) != 0 && ! component.isVisible()))
  3007. component.setVisible (true);
  3008. else if (((wp.flags & SWP_HIDEWINDOW) != 0 && component.isVisible()))
  3009. component.setVisible (false);
  3010. return 0;
  3011. }
  3012. enum class ForceRefreshDispatcher
  3013. {
  3014. no,
  3015. yes
  3016. };
  3017. void updateCurrentMonitorAndRefreshVBlankDispatcher (ForceRefreshDispatcher force = ForceRefreshDispatcher::no)
  3018. {
  3019. auto monitor = MonitorFromWindow (hwnd, MONITOR_DEFAULTTONULL);
  3020. if (std::exchange (currentMonitor, monitor) != monitor || force == ForceRefreshDispatcher::yes)
  3021. VBlankDispatcher::getInstance()->updateDisplay (*this, currentMonitor);
  3022. }
  3023. bool handlePositionChanged()
  3024. {
  3025. auto pos = getCurrentMousePos();
  3026. if (contains (pos.roundToInt(), false))
  3027. {
  3028. const ScopedValueSetter<bool> scope (inHandlePositionChanged, true);
  3029. if (! areOtherTouchSourcesActive())
  3030. doMouseEvent (pos, MouseInputSource::defaultPressure);
  3031. if (! isValidPeer (this))
  3032. return true;
  3033. }
  3034. handleMovedOrResized();
  3035. updateCurrentMonitorAndRefreshVBlankDispatcher();
  3036. return ! dontRepaint; // to allow non-accelerated openGL windows to draw themselves correctly.
  3037. }
  3038. //==============================================================================
  3039. LRESULT handleDPIChanging (int newDPI, RECT newRect)
  3040. {
  3041. // Sometimes, windows that should not be automatically scaled (secondary windows in plugins)
  3042. // are sent WM_DPICHANGED. The size suggested by the OS is incorrect for our unscaled
  3043. // window, so we should ignore it.
  3044. if (! isPerMonitorDPIAwareWindow (hwnd))
  3045. return 0;
  3046. const auto newScale = (double) newDPI / USER_DEFAULT_SCREEN_DPI;
  3047. if (approximatelyEqual (scaleFactor, newScale))
  3048. return 0;
  3049. scaleFactor = newScale;
  3050. {
  3051. const ScopedValueSetter<bool> setter (inDpiChange, true);
  3052. SetWindowPos (hwnd,
  3053. nullptr,
  3054. newRect.left,
  3055. newRect.top,
  3056. newRect.right - newRect.left,
  3057. newRect.bottom - newRect.top,
  3058. SWP_NOZORDER | SWP_NOACTIVATE);
  3059. }
  3060. // This is to handle reentrancy. If responding to a DPI change triggers further DPI changes,
  3061. // we should only notify listeners and resize windows once all of the DPI changes have
  3062. // resolved.
  3063. if (inDpiChange)
  3064. {
  3065. // Danger! Re-entrant call to handleDPIChanging.
  3066. // Please report this issue on the JUCE forum, along with instructions
  3067. // so that a JUCE developer can reproduce the issue.
  3068. jassertfalse;
  3069. return 0;
  3070. }
  3071. updateShadower();
  3072. InvalidateRect (hwnd, nullptr, FALSE);
  3073. scaleFactorListeners.call ([this] (ScaleFactorListener& l) { l.nativeScaleFactorChanged (scaleFactor); });
  3074. return 0;
  3075. }
  3076. //==============================================================================
  3077. void handleAppActivation (const WPARAM wParam)
  3078. {
  3079. modifiersAtLastCallback = -1;
  3080. updateKeyModifiers();
  3081. if (isMinimised())
  3082. {
  3083. component.repaint();
  3084. handleMovedOrResized();
  3085. if (! isValidPeer (this))
  3086. return;
  3087. }
  3088. auto* underMouse = component.getComponentAt (component.getMouseXYRelative());
  3089. if (underMouse == nullptr)
  3090. underMouse = &component;
  3091. if (underMouse->isCurrentlyBlockedByAnotherModalComponent())
  3092. {
  3093. if (LOWORD (wParam) == WA_CLICKACTIVE)
  3094. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  3095. else
  3096. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  3097. }
  3098. else
  3099. {
  3100. handleBroughtToFront();
  3101. }
  3102. }
  3103. void handlePowerBroadcast (WPARAM wParam)
  3104. {
  3105. if (auto* app = JUCEApplicationBase::getInstance())
  3106. {
  3107. switch (wParam)
  3108. {
  3109. case PBT_APMSUSPEND: app->suspended(); break;
  3110. case PBT_APMQUERYSUSPENDFAILED:
  3111. case PBT_APMRESUMECRITICAL:
  3112. case PBT_APMRESUMESUSPEND:
  3113. case PBT_APMRESUMEAUTOMATIC: app->resumed(); break;
  3114. default: break;
  3115. }
  3116. }
  3117. }
  3118. void handleLeftClickInNCArea (WPARAM wParam)
  3119. {
  3120. if (! sendInputAttemptWhenModalMessage())
  3121. {
  3122. switch (wParam)
  3123. {
  3124. case HTBOTTOM:
  3125. case HTBOTTOMLEFT:
  3126. case HTBOTTOMRIGHT:
  3127. case HTGROWBOX:
  3128. case HTLEFT:
  3129. case HTRIGHT:
  3130. case HTTOP:
  3131. case HTTOPLEFT:
  3132. case HTTOPRIGHT:
  3133. if (isConstrainedNativeWindow())
  3134. {
  3135. constrainerIsResizing = true;
  3136. constrainer->resizeStart();
  3137. }
  3138. break;
  3139. default:
  3140. break;
  3141. }
  3142. }
  3143. }
  3144. void initialiseSysMenu (HMENU menu) const
  3145. {
  3146. if (! hasTitleBar())
  3147. {
  3148. if (isFullScreen())
  3149. {
  3150. EnableMenuItem (menu, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  3151. EnableMenuItem (menu, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  3152. }
  3153. else if (! isMinimised())
  3154. {
  3155. EnableMenuItem (menu, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  3156. }
  3157. }
  3158. }
  3159. void doSettingChange()
  3160. {
  3161. forceDisplayUpdate();
  3162. if (fullScreen && ! isMinimised())
  3163. setWindowPos (hwnd, detail::ScalingHelpers::scaledScreenPosToUnscaled (component, Desktop::getInstance().getDisplays()
  3164. .getDisplayForRect (component.getScreenBounds())->userArea),
  3165. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  3166. auto* dispatcher = VBlankDispatcher::getInstance();
  3167. dispatcher->reconfigureDisplays();
  3168. updateCurrentMonitorAndRefreshVBlankDispatcher (ForceRefreshDispatcher::yes);
  3169. }
  3170. //==============================================================================
  3171. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  3172. void setModifierKeyProvider (ModifierKeyProvider* provider) override
  3173. {
  3174. modProvider = provider;
  3175. }
  3176. void removeModifierKeyProvider() override
  3177. {
  3178. modProvider = nullptr;
  3179. }
  3180. #endif
  3181. public:
  3182. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  3183. {
  3184. // Ensure that non-client areas are scaled for per-monitor DPI awareness v1 - can't
  3185. // do this in peerWindowProc as we have no window at this point
  3186. if (message == WM_NCCREATE && enableNonClientDPIScaling != nullptr)
  3187. enableNonClientDPIScaling (h);
  3188. if (auto* peer = getOwnerOfWindow (h))
  3189. {
  3190. jassert (isValidPeer (peer));
  3191. return peer->peerWindowProc (h, message, wParam, lParam);
  3192. }
  3193. return DefWindowProcW (h, message, wParam, lParam);
  3194. }
  3195. private:
  3196. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  3197. {
  3198. auto& mm = *MessageManager::getInstance();
  3199. if (mm.currentThreadHasLockedMessageManager())
  3200. return callback (userData);
  3201. return mm.callFunctionOnMessageThread (callback, userData);
  3202. }
  3203. static POINT getPOINTFromLParam (LPARAM lParam) noexcept
  3204. {
  3205. return { GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam) };
  3206. }
  3207. Point<float> getPointFromLocalLParam (LPARAM lParam) noexcept
  3208. {
  3209. auto p = pointFromPOINT (getPOINTFromLParam (lParam));
  3210. if (isPerMonitorDPIAwareWindow (hwnd))
  3211. {
  3212. // LPARAM is relative to this window's top-left but may be on a different monitor so we need to calculate the
  3213. // physical screen position and then convert this to local logical coordinates
  3214. auto r = getWindowScreenRect (hwnd);
  3215. return globalToLocal (Desktop::getInstance().getDisplays().physicalToLogical (pointFromPOINT ({ r.left + p.x + roundToInt (windowBorder.getLeft() * scaleFactor),
  3216. r.top + p.y + roundToInt (windowBorder.getTop() * scaleFactor) })).toFloat());
  3217. }
  3218. return p.toFloat();
  3219. }
  3220. Point<float> getCurrentMousePos() noexcept
  3221. {
  3222. return globalToLocal (convertPhysicalScreenPointToLogical (pointFromPOINT (getPOINTFromLParam ((LPARAM) GetMessagePos())), hwnd).toFloat());
  3223. }
  3224. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  3225. {
  3226. switch (message)
  3227. {
  3228. //==============================================================================
  3229. case WM_NCHITTEST:
  3230. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  3231. return HTTRANSPARENT;
  3232. if (! hasTitleBar())
  3233. return HTCLIENT;
  3234. break;
  3235. //==============================================================================
  3236. case WM_PAINT:
  3237. handlePaintMessage();
  3238. return 0;
  3239. case WM_NCPAINT:
  3240. handlePaintMessage(); // this must be done, even with native titlebars, or there are rendering artifacts.
  3241. if (hasTitleBar())
  3242. break; // let the DefWindowProc handle drawing the frame.
  3243. return 0;
  3244. case WM_ERASEBKGND:
  3245. case WM_NCCALCSIZE:
  3246. if (hasTitleBar())
  3247. break;
  3248. return 1;
  3249. //==============================================================================
  3250. case WM_POINTERUPDATE:
  3251. if (handlePointerInput (wParam, lParam, false, false))
  3252. return 0;
  3253. break;
  3254. case WM_POINTERDOWN:
  3255. if (handlePointerInput (wParam, lParam, true, false))
  3256. return 0;
  3257. break;
  3258. case WM_POINTERUP:
  3259. if (handlePointerInput (wParam, lParam, false, true))
  3260. return 0;
  3261. break;
  3262. //==============================================================================
  3263. case WM_MOUSEMOVE: doMouseMove (getPointFromLocalLParam (lParam), false); return 0;
  3264. case WM_POINTERLEAVE:
  3265. case WM_MOUSELEAVE: doMouseExit(); return 0;
  3266. case WM_LBUTTONDOWN:
  3267. case WM_MBUTTONDOWN:
  3268. case WM_RBUTTONDOWN: doMouseDown (getPointFromLocalLParam (lParam), wParam); return 0;
  3269. case WM_LBUTTONUP:
  3270. case WM_MBUTTONUP:
  3271. case WM_RBUTTONUP: doMouseUp (getPointFromLocalLParam (lParam), wParam); return 0;
  3272. case WM_POINTERWHEEL:
  3273. case 0x020A: /* WM_MOUSEWHEEL */ doMouseWheel (wParam, true); return 0;
  3274. case WM_POINTERHWHEEL:
  3275. case 0x020E: /* WM_MOUSEHWHEEL */ doMouseWheel (wParam, false); return 0;
  3276. case WM_CAPTURECHANGED: doCaptureChanged(); return 0;
  3277. case WM_NCPOINTERUPDATE:
  3278. case WM_NCMOUSEMOVE:
  3279. if (hasTitleBar())
  3280. break;
  3281. return 0;
  3282. case WM_TOUCH:
  3283. if (getTouchInputInfo != nullptr)
  3284. return doTouchEvent ((int) wParam, (HTOUCHINPUT) lParam);
  3285. break;
  3286. case 0x119: /* WM_GESTURE */
  3287. if (doGestureEvent (lParam))
  3288. return 0;
  3289. break;
  3290. //==============================================================================
  3291. case WM_SIZING: return handleSizeConstraining (*(RECT*) lParam, wParam);
  3292. case WM_WINDOWPOSCHANGING: return handlePositionChanging (*(WINDOWPOS*) lParam);
  3293. case 0x2e0: /* WM_DPICHANGED */ return handleDPIChanging ((int) HIWORD (wParam), *(RECT*) lParam);
  3294. case WM_WINDOWPOSCHANGED:
  3295. {
  3296. const WINDOWPOS& wPos = *reinterpret_cast<WINDOWPOS*> (lParam);
  3297. if ((wPos.flags & SWP_NOMOVE) != 0 && (wPos.flags & SWP_NOSIZE) != 0)
  3298. startTimer (100);
  3299. else
  3300. if (handlePositionChanged())
  3301. return 0;
  3302. }
  3303. break;
  3304. //==============================================================================
  3305. case WM_KEYDOWN:
  3306. case WM_SYSKEYDOWN:
  3307. if (doKeyDown (wParam))
  3308. return 0;
  3309. forwardMessageToParent (message, wParam, lParam);
  3310. break;
  3311. case WM_KEYUP:
  3312. case WM_SYSKEYUP:
  3313. if (doKeyUp (wParam))
  3314. return 0;
  3315. forwardMessageToParent (message, wParam, lParam);
  3316. break;
  3317. case WM_CHAR:
  3318. if (doKeyChar ((int) wParam, lParam))
  3319. return 0;
  3320. forwardMessageToParent (message, wParam, lParam);
  3321. break;
  3322. case WM_APPCOMMAND:
  3323. if (doAppCommand (lParam))
  3324. return TRUE;
  3325. break;
  3326. case WM_MENUCHAR: // triggered when alt+something is pressed
  3327. return MNC_CLOSE << 16; // (avoids making the default system beep)
  3328. //==============================================================================
  3329. case WM_SETFOCUS:
  3330. /* When the HWND receives Focus from the system it sends a
  3331. UIA_AutomationFocusChangedEventId notification redirecting the focus to the HWND
  3332. itself. This is a built-in behaviour of the HWND.
  3333. This means that whichever JUCE managed provider was active before the entire
  3334. window lost and then regained the focus, loses its focused state, and the
  3335. window's root element will become focused under which all JUCE managed providers
  3336. can be found.
  3337. This needs to be reflected on currentlyFocusedHandler so that the JUCE
  3338. accessibility mechanisms can detect that the root window got the focus, and send
  3339. another FocusChanged event to the system to redirect focus to a JUCE managed
  3340. provider if necessary.
  3341. */
  3342. AccessibilityHandler::clearCurrentlyFocusedHandler();
  3343. updateKeyModifiers();
  3344. handleFocusGain();
  3345. break;
  3346. case WM_KILLFOCUS:
  3347. if (hasCreatedCaret)
  3348. {
  3349. hasCreatedCaret = false;
  3350. DestroyCaret();
  3351. }
  3352. handleFocusLoss();
  3353. if (auto* modal = Component::getCurrentlyModalComponent())
  3354. if (auto* peer = modal->getPeer())
  3355. if ((peer->getStyleFlags() & ComponentPeer::windowIsTemporary) != 0)
  3356. sendInputAttemptWhenModalMessage();
  3357. break;
  3358. case WM_ACTIVATEAPP:
  3359. // Windows does weird things to process priority when you swap apps,
  3360. // so this forces an update when the app is brought to the front
  3361. if (wParam != FALSE)
  3362. juce_repeatLastProcessPriority();
  3363. else
  3364. Desktop::getInstance().setKioskModeComponent (nullptr); // turn kiosk mode off if we lose focus
  3365. detail::TopLevelWindowManager::checkCurrentlyFocusedTopLevelWindow();
  3366. modifiersAtLastCallback = -1;
  3367. return 0;
  3368. case WM_ACTIVATE:
  3369. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  3370. {
  3371. handleAppActivation (wParam);
  3372. return 0;
  3373. }
  3374. break;
  3375. case WM_NCACTIVATE:
  3376. // while a temporary window is being shown, prevent Windows from deactivating the
  3377. // title bars of our main windows.
  3378. if (wParam == 0 && ! shouldDeactivateTitleBar)
  3379. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  3380. break;
  3381. case WM_POINTERACTIVATE:
  3382. case WM_MOUSEACTIVATE:
  3383. if (! component.getMouseClickGrabsKeyboardFocus())
  3384. return MA_NOACTIVATE;
  3385. break;
  3386. case WM_SHOWWINDOW:
  3387. if (wParam != 0)
  3388. {
  3389. component.setVisible (true);
  3390. handleBroughtToFront();
  3391. }
  3392. break;
  3393. case WM_CLOSE:
  3394. if (! component.isCurrentlyBlockedByAnotherModalComponent())
  3395. handleUserClosingWindow();
  3396. return 0;
  3397. #if JUCE_REMOVE_COMPONENT_FROM_DESKTOP_ON_WM_DESTROY
  3398. case WM_DESTROY:
  3399. getComponent().removeFromDesktop();
  3400. return 0;
  3401. #endif
  3402. case WM_QUERYENDSESSION:
  3403. if (auto* app = JUCEApplicationBase::getInstance())
  3404. {
  3405. app->systemRequestedQuit();
  3406. return MessageManager::getInstance()->hasStopMessageBeenSent();
  3407. }
  3408. return TRUE;
  3409. case WM_POWERBROADCAST:
  3410. handlePowerBroadcast (wParam);
  3411. break;
  3412. case WM_SYNCPAINT:
  3413. return 0;
  3414. case WM_DISPLAYCHANGE:
  3415. InvalidateRect (h, nullptr, 0);
  3416. // intentional fall-through...
  3417. JUCE_FALLTHROUGH
  3418. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  3419. doSettingChange();
  3420. break;
  3421. case WM_INITMENU:
  3422. initialiseSysMenu ((HMENU) wParam);
  3423. break;
  3424. case WM_SYSCOMMAND:
  3425. switch (wParam & 0xfff0)
  3426. {
  3427. case SC_CLOSE:
  3428. if (sendInputAttemptWhenModalMessage())
  3429. return 0;
  3430. if (hasTitleBar())
  3431. {
  3432. PostMessage (h, WM_CLOSE, 0, 0);
  3433. return 0;
  3434. }
  3435. break;
  3436. case SC_KEYMENU:
  3437. #if ! JUCE_WINDOWS_ALT_KEY_TRIGGERS_MENU
  3438. // This test prevents a press of the ALT key from triggering the ancient top-left window menu.
  3439. // By default we suppress this behaviour because it's unlikely that more than a tiny subset of
  3440. // our users will actually want it, and it causes problems if you're trying to use the ALT key
  3441. // as a modifier for mouse actions. If you really need the old behaviour, then just define
  3442. // JUCE_WINDOWS_ALT_KEY_TRIGGERS_MENU=1 in your app.
  3443. if ((lParam >> 16) <= 0) // Values above zero indicate that a mouse-click triggered the menu
  3444. return 0;
  3445. #endif
  3446. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very obscure
  3447. // situations that can arise if a modal loop is started from an alt-key keypress).
  3448. if (hasTitleBar() && h == GetCapture())
  3449. ReleaseCapture();
  3450. break;
  3451. case SC_MAXIMIZE:
  3452. if (! sendInputAttemptWhenModalMessage())
  3453. setFullScreen (true);
  3454. return 0;
  3455. case SC_MINIMIZE:
  3456. if (sendInputAttemptWhenModalMessage())
  3457. return 0;
  3458. if (! hasTitleBar())
  3459. {
  3460. setMinimised (true);
  3461. return 0;
  3462. }
  3463. break;
  3464. case SC_RESTORE:
  3465. if (sendInputAttemptWhenModalMessage())
  3466. return 0;
  3467. if (hasTitleBar())
  3468. {
  3469. if (isFullScreen())
  3470. {
  3471. setFullScreen (false);
  3472. return 0;
  3473. }
  3474. }
  3475. else
  3476. {
  3477. if (isMinimised())
  3478. setMinimised (false);
  3479. else if (isFullScreen())
  3480. setFullScreen (false);
  3481. return 0;
  3482. }
  3483. break;
  3484. }
  3485. break;
  3486. case WM_NCPOINTERDOWN:
  3487. case WM_NCLBUTTONDOWN:
  3488. handleLeftClickInNCArea (wParam);
  3489. break;
  3490. case WM_NCRBUTTONDOWN:
  3491. case WM_NCMBUTTONDOWN:
  3492. sendInputAttemptWhenModalMessage();
  3493. break;
  3494. case WM_IME_SETCONTEXT:
  3495. imeHandler.handleSetContext (h, wParam == TRUE);
  3496. lParam &= ~(LPARAM) ISC_SHOWUICOMPOSITIONWINDOW;
  3497. break;
  3498. case WM_IME_STARTCOMPOSITION: imeHandler.handleStartComposition (*this); return 0;
  3499. case WM_IME_ENDCOMPOSITION: imeHandler.handleEndComposition (*this, h); break;
  3500. case WM_IME_COMPOSITION: imeHandler.handleComposition (*this, h, lParam); return 0;
  3501. case WM_GETDLGCODE:
  3502. return DLGC_WANTALLKEYS;
  3503. case WM_GETOBJECT:
  3504. {
  3505. if (static_cast<long> (lParam) == WindowsAccessibility::getUiaRootObjectId())
  3506. {
  3507. if (auto* handler = component.getAccessibilityHandler())
  3508. {
  3509. LRESULT res = 0;
  3510. if (WindowsAccessibility::handleWmGetObject (handler, wParam, lParam, &res))
  3511. {
  3512. isAccessibilityActive = true;
  3513. return res;
  3514. }
  3515. }
  3516. }
  3517. break;
  3518. }
  3519. default:
  3520. break;
  3521. }
  3522. return DefWindowProcW (h, message, wParam, lParam);
  3523. }
  3524. bool sendInputAttemptWhenModalMessage()
  3525. {
  3526. if (! component.isCurrentlyBlockedByAnotherModalComponent())
  3527. return false;
  3528. if (auto* current = Component::getCurrentlyModalComponent())
  3529. if (auto* owner = getOwnerOfWindow ((HWND) current->getWindowHandle()))
  3530. if (! owner->shouldIgnoreModalDismiss)
  3531. current->inputAttemptWhenModal();
  3532. return true;
  3533. }
  3534. //==============================================================================
  3535. struct IMEHandler
  3536. {
  3537. IMEHandler()
  3538. {
  3539. reset();
  3540. }
  3541. void handleSetContext (HWND hWnd, const bool windowIsActive)
  3542. {
  3543. if (compositionInProgress && ! windowIsActive)
  3544. {
  3545. if (HIMC hImc = ImmGetContext (hWnd))
  3546. {
  3547. ImmNotifyIME (hImc, NI_COMPOSITIONSTR, CPS_COMPLETE, 0);
  3548. ImmReleaseContext (hWnd, hImc);
  3549. }
  3550. // If the composition is still in progress, calling ImmNotifyIME may call back
  3551. // into handleComposition to let us know that the composition has finished.
  3552. // We need to set compositionInProgress *after* calling handleComposition, so that
  3553. // the text replaces the current selection, rather than being inserted after the
  3554. // caret.
  3555. compositionInProgress = false;
  3556. }
  3557. }
  3558. void handleStartComposition (ComponentPeer& owner)
  3559. {
  3560. reset();
  3561. if (auto* target = owner.findCurrentTextInputTarget())
  3562. target->insertTextAtCaret (String());
  3563. }
  3564. void handleEndComposition (ComponentPeer& owner, HWND hWnd)
  3565. {
  3566. if (compositionInProgress)
  3567. {
  3568. // If this occurs, the user has cancelled the composition, so clear their changes..
  3569. if (auto* target = owner.findCurrentTextInputTarget())
  3570. {
  3571. target->setHighlightedRegion (compositionRange);
  3572. target->insertTextAtCaret (String());
  3573. compositionRange.setLength (0);
  3574. target->setHighlightedRegion (Range<int>::emptyRange (compositionRange.getEnd()));
  3575. target->setTemporaryUnderlining ({});
  3576. }
  3577. if (auto hImc = ImmGetContext (hWnd))
  3578. {
  3579. ImmNotifyIME (hImc, NI_CLOSECANDIDATE, 0, 0);
  3580. ImmReleaseContext (hWnd, hImc);
  3581. }
  3582. }
  3583. reset();
  3584. }
  3585. void handleComposition (ComponentPeer& owner, HWND hWnd, const LPARAM lParam)
  3586. {
  3587. if (auto* target = owner.findCurrentTextInputTarget())
  3588. {
  3589. if (auto hImc = ImmGetContext (hWnd))
  3590. {
  3591. if (compositionRange.getStart() < 0)
  3592. compositionRange = Range<int>::emptyRange (target->getHighlightedRegion().getStart());
  3593. if ((lParam & GCS_RESULTSTR) != 0) // (composition has finished)
  3594. {
  3595. replaceCurrentSelection (target, getCompositionString (hImc, GCS_RESULTSTR),
  3596. Range<int>::emptyRange (-1));
  3597. reset();
  3598. target->setTemporaryUnderlining ({});
  3599. }
  3600. else if ((lParam & GCS_COMPSTR) != 0) // (composition is still in-progress)
  3601. {
  3602. replaceCurrentSelection (target, getCompositionString (hImc, GCS_COMPSTR),
  3603. getCompositionSelection (hImc, lParam));
  3604. target->setTemporaryUnderlining (getCompositionUnderlines (hImc, lParam));
  3605. compositionInProgress = true;
  3606. }
  3607. moveCandidateWindowToLeftAlignWithSelection (hImc, owner, target);
  3608. ImmReleaseContext (hWnd, hImc);
  3609. }
  3610. }
  3611. }
  3612. private:
  3613. //==============================================================================
  3614. Range<int> compositionRange; // The range being modified in the TextInputTarget
  3615. bool compositionInProgress;
  3616. //==============================================================================
  3617. void reset()
  3618. {
  3619. compositionRange = Range<int>::emptyRange (-1);
  3620. compositionInProgress = false;
  3621. }
  3622. String getCompositionString (HIMC hImc, const DWORD type) const
  3623. {
  3624. jassert (hImc != HIMC{});
  3625. const auto stringSizeBytes = ImmGetCompositionString (hImc, type, nullptr, 0);
  3626. if (stringSizeBytes > 0)
  3627. {
  3628. HeapBlock<TCHAR> buffer;
  3629. buffer.calloc ((size_t) stringSizeBytes / sizeof (TCHAR) + 1);
  3630. ImmGetCompositionString (hImc, type, buffer, (DWORD) stringSizeBytes);
  3631. return String (buffer.get());
  3632. }
  3633. return {};
  3634. }
  3635. int getCompositionCaretPos (HIMC hImc, LPARAM lParam, const String& currentIMEString) const
  3636. {
  3637. jassert (hImc != HIMC{});
  3638. if ((lParam & CS_NOMOVECARET) != 0)
  3639. return compositionRange.getStart();
  3640. if ((lParam & GCS_CURSORPOS) != 0)
  3641. {
  3642. const int localCaretPos = ImmGetCompositionString (hImc, GCS_CURSORPOS, nullptr, 0);
  3643. return compositionRange.getStart() + jmax (0, localCaretPos);
  3644. }
  3645. return compositionRange.getStart() + currentIMEString.length();
  3646. }
  3647. // Get selected/highlighted range while doing composition:
  3648. // returned range is relative to beginning of TextInputTarget, not composition string
  3649. Range<int> getCompositionSelection (HIMC hImc, LPARAM lParam) const
  3650. {
  3651. jassert (hImc != HIMC{});
  3652. int selectionStart = 0;
  3653. int selectionEnd = 0;
  3654. if ((lParam & GCS_COMPATTR) != 0)
  3655. {
  3656. // Get size of attributes array:
  3657. const int attributeSizeBytes = ImmGetCompositionString (hImc, GCS_COMPATTR, nullptr, 0);
  3658. if (attributeSizeBytes > 0)
  3659. {
  3660. // Get attributes (8 bit flag per character):
  3661. HeapBlock<char> attributes (attributeSizeBytes);
  3662. ImmGetCompositionString (hImc, GCS_COMPATTR, attributes, (DWORD) attributeSizeBytes);
  3663. selectionStart = 0;
  3664. for (selectionStart = 0; selectionStart < attributeSizeBytes; ++selectionStart)
  3665. if (attributes[selectionStart] == ATTR_TARGET_CONVERTED || attributes[selectionStart] == ATTR_TARGET_NOTCONVERTED)
  3666. break;
  3667. for (selectionEnd = selectionStart; selectionEnd < attributeSizeBytes; ++selectionEnd)
  3668. if (attributes[selectionEnd] != ATTR_TARGET_CONVERTED && attributes[selectionEnd] != ATTR_TARGET_NOTCONVERTED)
  3669. break;
  3670. }
  3671. }
  3672. return Range<int> (selectionStart, selectionEnd) + compositionRange.getStart();
  3673. }
  3674. void replaceCurrentSelection (TextInputTarget* const target, const String& newContent, Range<int> newSelection)
  3675. {
  3676. if (compositionInProgress)
  3677. target->setHighlightedRegion (compositionRange);
  3678. target->insertTextAtCaret (newContent);
  3679. compositionRange.setLength (newContent.length());
  3680. if (newSelection.getStart() < 0)
  3681. newSelection = Range<int>::emptyRange (compositionRange.getEnd());
  3682. target->setHighlightedRegion (newSelection);
  3683. }
  3684. Array<Range<int>> getCompositionUnderlines (HIMC hImc, LPARAM lParam) const
  3685. {
  3686. Array<Range<int>> result;
  3687. if (hImc != HIMC{} && (lParam & GCS_COMPCLAUSE) != 0)
  3688. {
  3689. auto clauseDataSizeBytes = ImmGetCompositionString (hImc, GCS_COMPCLAUSE, nullptr, 0);
  3690. if (clauseDataSizeBytes > 0)
  3691. {
  3692. const auto numItems = (size_t) clauseDataSizeBytes / sizeof (uint32);
  3693. HeapBlock<uint32> clauseData (numItems);
  3694. if (ImmGetCompositionString (hImc, GCS_COMPCLAUSE, clauseData, (DWORD) clauseDataSizeBytes) > 0)
  3695. for (size_t i = 0; i + 1 < numItems; ++i)
  3696. result.add (Range<int> ((int) clauseData[i], (int) clauseData[i + 1]) + compositionRange.getStart());
  3697. }
  3698. }
  3699. return result;
  3700. }
  3701. void moveCandidateWindowToLeftAlignWithSelection (HIMC hImc, ComponentPeer& peer, TextInputTarget* target) const
  3702. {
  3703. if (auto* targetComp = dynamic_cast<Component*> (target))
  3704. {
  3705. auto area = peer.getComponent().getLocalArea (targetComp, target->getCaretRectangle());
  3706. CANDIDATEFORM pos = { 0, CFS_CANDIDATEPOS, { area.getX(), area.getBottom() }, { 0, 0, 0, 0 } };
  3707. ImmSetCandidateWindow (hImc, &pos);
  3708. }
  3709. }
  3710. JUCE_DECLARE_NON_COPYABLE (IMEHandler)
  3711. };
  3712. void timerCallback() override
  3713. {
  3714. handlePositionChanged();
  3715. stopTimer();
  3716. }
  3717. static bool isAncestor (HWND outer, HWND inner)
  3718. {
  3719. if (outer == nullptr || inner == nullptr)
  3720. return false;
  3721. if (outer == inner)
  3722. return true;
  3723. return isAncestor (outer, GetAncestor (inner, GA_PARENT));
  3724. }
  3725. void windowShouldDismissModals (HWND originator)
  3726. {
  3727. if (shouldIgnoreModalDismiss)
  3728. return;
  3729. if (isAncestor (originator, hwnd))
  3730. sendInputAttemptWhenModalMessage();
  3731. }
  3732. // Unfortunately SetWindowsHookEx only allows us to register a static function as a hook.
  3733. // To get around this, we keep a static list of listeners which are interested in
  3734. // top-level window events, and notify all of these listeners from the callback.
  3735. class TopLevelModalDismissBroadcaster
  3736. {
  3737. public:
  3738. TopLevelModalDismissBroadcaster()
  3739. : hook (SetWindowsHookEx (WH_CALLWNDPROC,
  3740. callWndProc,
  3741. (HINSTANCE) juce::Process::getCurrentModuleInstanceHandle(),
  3742. GetCurrentThreadId()))
  3743. {}
  3744. ~TopLevelModalDismissBroadcaster() noexcept
  3745. {
  3746. UnhookWindowsHookEx (hook);
  3747. }
  3748. private:
  3749. static void processMessage (int nCode, const CWPSTRUCT* info)
  3750. {
  3751. if (nCode < 0 || info == nullptr)
  3752. return;
  3753. constexpr UINT events[] { WM_MOVE,
  3754. WM_SIZE,
  3755. WM_WINDOWPOSCHANGING,
  3756. WM_NCPOINTERDOWN,
  3757. WM_NCLBUTTONDOWN,
  3758. WM_NCRBUTTONDOWN,
  3759. WM_NCMBUTTONDOWN };
  3760. if (std::find (std::begin (events), std::end (events), info->message) == std::end (events))
  3761. return;
  3762. if (info->message == WM_WINDOWPOSCHANGING)
  3763. {
  3764. const auto* windowPos = reinterpret_cast<const WINDOWPOS*> (info->lParam);
  3765. const auto windowPosFlags = windowPos->flags;
  3766. constexpr auto maskToCheck = SWP_NOMOVE | SWP_NOSIZE;
  3767. if ((windowPosFlags & maskToCheck) == maskToCheck)
  3768. return;
  3769. }
  3770. // windowMayDismissModals could affect the number of active ComponentPeer instances
  3771. for (auto i = ComponentPeer::getNumPeers(); --i >= 0;)
  3772. if (i < ComponentPeer::getNumPeers())
  3773. if (auto* hwndPeer = dynamic_cast<HWNDComponentPeer*> (ComponentPeer::getPeer (i)))
  3774. hwndPeer->windowShouldDismissModals (info->hwnd);
  3775. }
  3776. static LRESULT CALLBACK callWndProc (int nCode, WPARAM wParam, LPARAM lParam)
  3777. {
  3778. processMessage (nCode, reinterpret_cast<CWPSTRUCT*> (lParam));
  3779. return CallNextHookEx ({}, nCode, wParam, lParam);
  3780. }
  3781. HHOOK hook;
  3782. };
  3783. SharedResourcePointer<TopLevelModalDismissBroadcaster> modalDismissBroadcaster;
  3784. IMEHandler imeHandler;
  3785. bool shouldIgnoreModalDismiss = false;
  3786. RectangleList<int> deferredRepaints;
  3787. ScopedSuspendResumeNotificationRegistration suspendResumeRegistration;
  3788. std::optional<SimpleTimer> monitorUpdateTimer;
  3789. //==============================================================================
  3790. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HWNDComponentPeer)
  3791. };
  3792. MultiTouchMapper<DWORD> HWNDComponentPeer::currentTouches;
  3793. ModifierKeys HWNDComponentPeer::modifiersAtLastCallback;
  3794. ComponentPeer* Component::createNewPeer (int styleFlags, void* parentHWND)
  3795. {
  3796. return new HWNDComponentPeer (*this, styleFlags, (HWND) parentHWND, false);
  3797. }
  3798. JUCE_API ComponentPeer* createNonRepaintingEmbeddedWindowsPeer (Component& component, void* parentHWND);
  3799. JUCE_API ComponentPeer* createNonRepaintingEmbeddedWindowsPeer (Component& component, void* parentHWND)
  3800. {
  3801. return new HWNDComponentPeer (component, ComponentPeer::windowIgnoresMouseClicks,
  3802. (HWND) parentHWND, true);
  3803. }
  3804. JUCE_IMPLEMENT_SINGLETON (HWNDComponentPeer::WindowClassHolder)
  3805. //==============================================================================
  3806. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  3807. {
  3808. auto k = (SHORT) keyCode;
  3809. if ((keyCode & extendedKeyModifier) == 0)
  3810. {
  3811. if (k >= (SHORT) 'a' && k <= (SHORT) 'z')
  3812. k += (SHORT) 'A' - (SHORT) 'a';
  3813. // Only translate if extendedKeyModifier flag is not set
  3814. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  3815. (SHORT) '+', VK_OEM_PLUS,
  3816. (SHORT) '-', VK_OEM_MINUS,
  3817. (SHORT) '.', VK_OEM_PERIOD,
  3818. (SHORT) ';', VK_OEM_1,
  3819. (SHORT) ':', VK_OEM_1,
  3820. (SHORT) '/', VK_OEM_2,
  3821. (SHORT) '?', VK_OEM_2,
  3822. (SHORT) '[', VK_OEM_4,
  3823. (SHORT) ']', VK_OEM_6 };
  3824. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  3825. if (k == translatedValues[i])
  3826. k = translatedValues[i + 1];
  3827. }
  3828. return HWNDComponentPeer::isKeyDown (k);
  3829. }
  3830. //==============================================================================
  3831. static DWORD getProcess (HWND hwnd)
  3832. {
  3833. DWORD result = 0;
  3834. GetWindowThreadProcessId (hwnd, &result);
  3835. return result;
  3836. }
  3837. /* Returns true if the viewComponent is embedded into a window
  3838. owned by the foreground process.
  3839. */
  3840. bool detail::WindowingHelpers::isEmbeddedInForegroundProcess (Component* c)
  3841. {
  3842. if (c == nullptr)
  3843. return false;
  3844. auto* peer = c->getPeer();
  3845. auto* hwnd = peer != nullptr ? static_cast<HWND> (peer->getNativeHandle()) : nullptr;
  3846. if (hwnd == nullptr)
  3847. return true;
  3848. const auto fgProcess = getProcess (GetForegroundWindow());
  3849. const auto ownerProcess = getProcess (GetAncestor (hwnd, GA_ROOTOWNER));
  3850. return fgProcess == ownerProcess;
  3851. }
  3852. bool JUCE_CALLTYPE Process::isForegroundProcess()
  3853. {
  3854. if (auto fg = GetForegroundWindow())
  3855. return getProcess (fg) == GetCurrentProcessId();
  3856. return true;
  3857. }
  3858. // N/A on Windows as far as I know.
  3859. void JUCE_CALLTYPE Process::makeForegroundProcess() {}
  3860. void JUCE_CALLTYPE Process::hide() {}
  3861. //==============================================================================
  3862. bool detail::MouseInputSourceList::addSource()
  3863. {
  3864. auto numSources = sources.size();
  3865. if (numSources == 0 || canUseMultiTouch())
  3866. {
  3867. addSource (numSources, numSources == 0 ? MouseInputSource::InputSourceType::mouse
  3868. : MouseInputSource::InputSourceType::touch);
  3869. return true;
  3870. }
  3871. return false;
  3872. }
  3873. bool detail::MouseInputSourceList::canUseTouch() const
  3874. {
  3875. return canUseMultiTouch();
  3876. }
  3877. Point<float> MouseInputSource::getCurrentRawMousePosition()
  3878. {
  3879. POINT mousePos;
  3880. GetCursorPos (&mousePos);
  3881. auto p = pointFromPOINT (mousePos);
  3882. if (isPerMonitorDPIAwareThread())
  3883. p = Desktop::getInstance().getDisplays().physicalToLogical (p);
  3884. return p.toFloat();
  3885. }
  3886. void MouseInputSource::setRawMousePosition (Point<float> newPosition)
  3887. {
  3888. auto newPositionInt = newPosition.roundToInt();
  3889. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  3890. if (isPerMonitorDPIAwareThread())
  3891. newPositionInt = Desktop::getInstance().getDisplays().logicalToPhysical (newPositionInt);
  3892. #endif
  3893. auto point = POINTFromPoint (newPositionInt);
  3894. SetCursorPos (point.x, point.y);
  3895. }
  3896. //==============================================================================
  3897. class ScreenSaverDefeater : public Timer
  3898. {
  3899. public:
  3900. ScreenSaverDefeater()
  3901. {
  3902. startTimer (10000);
  3903. timerCallback();
  3904. }
  3905. void timerCallback() override
  3906. {
  3907. if (Process::isForegroundProcess())
  3908. {
  3909. INPUT input = {};
  3910. input.type = INPUT_MOUSE;
  3911. input.mi.mouseData = MOUSEEVENTF_MOVE;
  3912. SendInput (1, &input, sizeof (INPUT));
  3913. }
  3914. }
  3915. };
  3916. static std::unique_ptr<ScreenSaverDefeater> screenSaverDefeater;
  3917. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  3918. {
  3919. if (isEnabled)
  3920. screenSaverDefeater = nullptr;
  3921. else if (screenSaverDefeater == nullptr)
  3922. screenSaverDefeater.reset (new ScreenSaverDefeater());
  3923. }
  3924. bool Desktop::isScreenSaverEnabled()
  3925. {
  3926. return screenSaverDefeater == nullptr;
  3927. }
  3928. //==============================================================================
  3929. void LookAndFeel::playAlertSound()
  3930. {
  3931. MessageBeep (MB_OK);
  3932. }
  3933. //==============================================================================
  3934. void SystemClipboard::copyTextToClipboard (const String& text)
  3935. {
  3936. if (OpenClipboard (nullptr) != 0)
  3937. {
  3938. if (EmptyClipboard() != 0)
  3939. {
  3940. auto bytesNeeded = CharPointer_UTF16::getBytesRequiredFor (text.getCharPointer()) + 4;
  3941. if (bytesNeeded > 0)
  3942. {
  3943. if (auto bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE | GMEM_ZEROINIT, bytesNeeded + sizeof (WCHAR)))
  3944. {
  3945. if (auto* data = static_cast<WCHAR*> (GlobalLock (bufH)))
  3946. {
  3947. text.copyToUTF16 (data, bytesNeeded);
  3948. GlobalUnlock (bufH);
  3949. SetClipboardData (CF_UNICODETEXT, bufH);
  3950. }
  3951. }
  3952. }
  3953. }
  3954. CloseClipboard();
  3955. }
  3956. }
  3957. String SystemClipboard::getTextFromClipboard()
  3958. {
  3959. String result;
  3960. if (OpenClipboard (nullptr) != 0)
  3961. {
  3962. if (auto bufH = GetClipboardData (CF_UNICODETEXT))
  3963. {
  3964. if (auto* data = (const WCHAR*) GlobalLock (bufH))
  3965. {
  3966. result = String (data, (size_t) (GlobalSize (bufH) / sizeof (WCHAR)));
  3967. GlobalUnlock (bufH);
  3968. }
  3969. }
  3970. CloseClipboard();
  3971. }
  3972. return result;
  3973. }
  3974. //==============================================================================
  3975. void Desktop::setKioskComponent (Component* kioskModeComp, bool enableOrDisable, bool /*allowMenusAndBars*/)
  3976. {
  3977. if (auto* tlw = dynamic_cast<TopLevelWindow*> (kioskModeComp))
  3978. tlw->setUsingNativeTitleBar (! enableOrDisable);
  3979. if (kioskModeComp != nullptr && enableOrDisable)
  3980. kioskModeComp->setBounds (getDisplays().getDisplayForRect (kioskModeComp->getScreenBounds())->totalArea);
  3981. }
  3982. void Desktop::allowedOrientationsChanged() {}
  3983. //==============================================================================
  3984. static const Displays::Display* getCurrentDisplayFromScaleFactor (HWND hwnd)
  3985. {
  3986. Array<const Displays::Display*> candidateDisplays;
  3987. const auto scaleToLookFor = [&]
  3988. {
  3989. if (auto* peer = HWNDComponentPeer::getOwnerOfWindow (hwnd))
  3990. return peer->getPlatformScaleFactor();
  3991. return getScaleFactorForWindow (hwnd);
  3992. }();
  3993. auto globalScale = Desktop::getInstance().getGlobalScaleFactor();
  3994. for (auto& d : Desktop::getInstance().getDisplays().displays)
  3995. if (approximatelyEqual (d.scale / globalScale, scaleToLookFor))
  3996. candidateDisplays.add (&d);
  3997. if (candidateDisplays.size() > 0)
  3998. {
  3999. if (candidateDisplays.size() == 1)
  4000. return candidateDisplays[0];
  4001. const auto bounds = [&]
  4002. {
  4003. if (auto* peer = HWNDComponentPeer::getOwnerOfWindow (hwnd))
  4004. return peer->getComponent().getTopLevelComponent()->getBounds();
  4005. return Desktop::getInstance().getDisplays().physicalToLogical (rectangleFromRECT (getWindowScreenRect (hwnd)));
  4006. }();
  4007. const Displays::Display* retVal = nullptr;
  4008. int maxArea = -1;
  4009. for (auto* d : candidateDisplays)
  4010. {
  4011. auto intersection = d->totalArea.getIntersection (bounds);
  4012. auto area = intersection.getWidth() * intersection.getHeight();
  4013. if (area > maxArea)
  4014. {
  4015. maxArea = area;
  4016. retVal = d;
  4017. }
  4018. }
  4019. if (retVal != nullptr)
  4020. return retVal;
  4021. }
  4022. return Desktop::getInstance().getDisplays().getPrimaryDisplay();
  4023. }
  4024. //==============================================================================
  4025. struct MonitorInfo
  4026. {
  4027. MonitorInfo (bool main, RECT totalArea, RECT workArea, double d) noexcept
  4028. : isMain (main),
  4029. totalAreaRect (totalArea),
  4030. workAreaRect (workArea),
  4031. dpi (d)
  4032. {
  4033. }
  4034. bool isMain;
  4035. RECT totalAreaRect, workAreaRect;
  4036. double dpi;
  4037. };
  4038. static BOOL CALLBACK enumMonitorsProc (HMONITOR hm, HDC, LPRECT, LPARAM userInfo)
  4039. {
  4040. MONITORINFO info = {};
  4041. info.cbSize = sizeof (info);
  4042. GetMonitorInfo (hm, &info);
  4043. auto isMain = (info.dwFlags & 1 /* MONITORINFOF_PRIMARY */) != 0;
  4044. auto dpi = 0.0;
  4045. if (getDPIForMonitor != nullptr)
  4046. {
  4047. UINT dpiX = 0, dpiY = 0;
  4048. if (SUCCEEDED (getDPIForMonitor (hm, MDT_Default, &dpiX, &dpiY)))
  4049. dpi = (dpiX + dpiY) / 2.0;
  4050. }
  4051. ((Array<MonitorInfo>*) userInfo)->add ({ isMain, info.rcMonitor, info.rcWork, dpi });
  4052. return TRUE;
  4053. }
  4054. void Displays::findDisplays (float masterScale)
  4055. {
  4056. setDPIAwareness();
  4057. Array<MonitorInfo> monitors;
  4058. EnumDisplayMonitors (nullptr, nullptr, &enumMonitorsProc, (LPARAM) &monitors);
  4059. auto globalDPI = getGlobalDPI();
  4060. if (monitors.size() == 0)
  4061. {
  4062. auto windowRect = getWindowScreenRect (GetDesktopWindow());
  4063. monitors.add ({ true, windowRect, windowRect, globalDPI });
  4064. }
  4065. // make sure the first in the list is the main monitor
  4066. for (int i = 1; i < monitors.size(); ++i)
  4067. if (monitors.getReference (i).isMain)
  4068. monitors.swap (i, 0);
  4069. for (auto& monitor : monitors)
  4070. {
  4071. Display d;
  4072. d.isMain = monitor.isMain;
  4073. d.dpi = monitor.dpi;
  4074. if (approximatelyEqual (d.dpi, 0.0))
  4075. {
  4076. d.dpi = globalDPI;
  4077. d.scale = masterScale;
  4078. }
  4079. else
  4080. {
  4081. d.scale = (d.dpi / USER_DEFAULT_SCREEN_DPI) * (masterScale / Desktop::getDefaultMasterScale());
  4082. }
  4083. d.totalArea = rectangleFromRECT (monitor.totalAreaRect);
  4084. d.userArea = rectangleFromRECT (monitor.workAreaRect);
  4085. displays.add (d);
  4086. }
  4087. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  4088. if (isPerMonitorDPIAwareThread())
  4089. updateToLogical();
  4090. else
  4091. #endif
  4092. {
  4093. for (auto& d : displays)
  4094. {
  4095. d.totalArea /= masterScale;
  4096. d.userArea /= masterScale;
  4097. }
  4098. }
  4099. }
  4100. //==============================================================================
  4101. static auto extractFileHICON (const File& file)
  4102. {
  4103. WORD iconNum = 0;
  4104. WCHAR name[MAX_PATH * 2];
  4105. file.getFullPathName().copyToUTF16 (name, sizeof (name));
  4106. return IconConverters::IconPtr { ExtractAssociatedIcon ((HINSTANCE) Process::getCurrentModuleInstanceHandle(),
  4107. name,
  4108. &iconNum) };
  4109. }
  4110. Image detail::WindowingHelpers::createIconForFile (const File& file)
  4111. {
  4112. if (const auto icon = extractFileHICON (file))
  4113. return IconConverters::createImageFromHICON (icon.get());
  4114. return {};
  4115. }
  4116. //==============================================================================
  4117. class MouseCursor::PlatformSpecificHandle
  4118. {
  4119. public:
  4120. explicit PlatformSpecificHandle (const MouseCursor::StandardCursorType type)
  4121. : impl (makeHandle (type)) {}
  4122. explicit PlatformSpecificHandle (const detail::CustomMouseCursorInfo& info)
  4123. : impl (makeHandle (info)) {}
  4124. static void showInWindow (PlatformSpecificHandle* handle, ComponentPeer* peer)
  4125. {
  4126. SetCursor ([&]
  4127. {
  4128. if (handle != nullptr && handle->impl != nullptr && peer != nullptr)
  4129. return handle->impl->getCursor (*peer);
  4130. return LoadCursor (nullptr, IDC_ARROW);
  4131. }());
  4132. }
  4133. private:
  4134. struct Impl
  4135. {
  4136. virtual ~Impl() = default;
  4137. virtual HCURSOR getCursor (ComponentPeer&) = 0;
  4138. };
  4139. class BuiltinImpl : public Impl
  4140. {
  4141. public:
  4142. explicit BuiltinImpl (HCURSOR cursorIn)
  4143. : cursor (cursorIn) {}
  4144. HCURSOR getCursor (ComponentPeer&) override { return cursor; }
  4145. private:
  4146. HCURSOR cursor;
  4147. };
  4148. class ImageImpl : public Impl
  4149. {
  4150. public:
  4151. explicit ImageImpl (const detail::CustomMouseCursorInfo& infoIn) : info (infoIn) {}
  4152. HCURSOR getCursor (ComponentPeer& peer) override
  4153. {
  4154. JUCE_ASSERT_MESSAGE_THREAD;
  4155. static auto getCursorSize = getCursorSizeForPeerFunction();
  4156. const auto size = getCursorSize (peer);
  4157. const auto iter = cursorsBySize.find (size);
  4158. if (iter != cursorsBySize.end())
  4159. return iter->second.get();
  4160. const auto logicalSize = info.image.getScaledBounds();
  4161. const auto scale = (float) size / (float) unityCursorSize;
  4162. const auto physicalSize = logicalSize * scale;
  4163. const auto& image = info.image.getImage();
  4164. const auto rescaled = image.rescaled (roundToInt ((float) physicalSize.getWidth()),
  4165. roundToInt ((float) physicalSize.getHeight()));
  4166. const auto effectiveScale = rescaled.getWidth() / logicalSize.getWidth();
  4167. const auto hx = jlimit (0, rescaled.getWidth(), roundToInt ((float) info.hotspot.x * effectiveScale));
  4168. const auto hy = jlimit (0, rescaled.getHeight(), roundToInt ((float) info.hotspot.y * effectiveScale));
  4169. return cursorsBySize.emplace (size, CursorPtr { IconConverters::createHICONFromImage (rescaled, false, hx, hy) }).first->second.get();
  4170. }
  4171. private:
  4172. struct CursorDestructor
  4173. {
  4174. void operator() (HCURSOR ptr) const { if (ptr != nullptr) DestroyCursor (ptr); }
  4175. };
  4176. using CursorPtr = std::unique_ptr<std::remove_pointer_t<HCURSOR>, CursorDestructor>;
  4177. const detail::CustomMouseCursorInfo info;
  4178. std::map<int, CursorPtr> cursorsBySize;
  4179. };
  4180. static auto getCursorSizeForPeerFunction() -> int (*) (ComponentPeer&)
  4181. {
  4182. static const auto getDpiForMonitor = []() -> GetDPIForMonitorFunc
  4183. {
  4184. constexpr auto library = "SHCore.dll";
  4185. LoadLibraryA (library);
  4186. if (auto* handle = GetModuleHandleA (library))
  4187. return (GetDPIForMonitorFunc) GetProcAddress (handle, "GetDpiForMonitor");
  4188. return nullptr;
  4189. }();
  4190. static const auto getSystemMetricsForDpi = []() -> GetSystemMetricsForDpiFunc
  4191. {
  4192. constexpr auto library = "User32.dll";
  4193. LoadLibraryA (library);
  4194. if (auto* handle = GetModuleHandleA (library))
  4195. return (GetSystemMetricsForDpiFunc) GetProcAddress (handle, "GetSystemMetricsForDpi");
  4196. return nullptr;
  4197. }();
  4198. if (getDpiForMonitor == nullptr || getSystemMetricsForDpi == nullptr)
  4199. return [] (ComponentPeer&) { return unityCursorSize; };
  4200. return [] (ComponentPeer& p)
  4201. {
  4202. const ScopedThreadDPIAwarenessSetter threadDpiAwarenessSetter { p.getNativeHandle() };
  4203. UINT dpiX = 0, dpiY = 0;
  4204. if (auto* monitor = MonitorFromWindow ((HWND) p.getNativeHandle(), MONITOR_DEFAULTTONULL))
  4205. if (SUCCEEDED (getDpiForMonitor (monitor, MDT_Default, &dpiX, &dpiY)))
  4206. return getSystemMetricsForDpi (SM_CXCURSOR, dpiX);
  4207. return unityCursorSize;
  4208. };
  4209. }
  4210. static constexpr auto unityCursorSize = 32;
  4211. static std::unique_ptr<Impl> makeHandle (const detail::CustomMouseCursorInfo& info)
  4212. {
  4213. return std::make_unique<ImageImpl> (info);
  4214. }
  4215. static std::unique_ptr<Impl> makeHandle (const MouseCursor::StandardCursorType type)
  4216. {
  4217. LPCTSTR cursorName = IDC_ARROW;
  4218. switch (type)
  4219. {
  4220. case NormalCursor:
  4221. case ParentCursor: break;
  4222. case NoCursor: return std::make_unique<BuiltinImpl> (nullptr);
  4223. case WaitCursor: cursorName = IDC_WAIT; break;
  4224. case IBeamCursor: cursorName = IDC_IBEAM; break;
  4225. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  4226. case CrosshairCursor: cursorName = IDC_CROSS; break;
  4227. case LeftRightResizeCursor:
  4228. case LeftEdgeResizeCursor:
  4229. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  4230. case UpDownResizeCursor:
  4231. case TopEdgeResizeCursor:
  4232. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  4233. case TopLeftCornerResizeCursor:
  4234. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  4235. case TopRightCornerResizeCursor:
  4236. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  4237. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  4238. case DraggingHandCursor:
  4239. {
  4240. static const unsigned char dragHandData[]
  4241. { 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,
  4242. 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,
  4243. 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 };
  4244. return makeHandle ({ ScaledImage (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData))), { 8, 7 } });
  4245. }
  4246. case CopyingCursor:
  4247. {
  4248. static const unsigned char copyCursorData[]
  4249. { 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,
  4250. 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,
  4251. 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,
  4252. 5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  4253. return makeHandle ({ ScaledImage (ImageFileFormat::loadFrom (copyCursorData, sizeof (copyCursorData))), { 1, 3 } });
  4254. }
  4255. case NumStandardCursorTypes: JUCE_FALLTHROUGH
  4256. default:
  4257. jassertfalse; break;
  4258. }
  4259. return std::make_unique<BuiltinImpl> ([&]
  4260. {
  4261. if (auto* c = LoadCursor (nullptr, cursorName))
  4262. return c;
  4263. return LoadCursor (nullptr, IDC_ARROW);
  4264. }());
  4265. }
  4266. std::unique_ptr<Impl> impl;
  4267. };
  4268. //==============================================================================
  4269. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  4270. //==============================================================================
  4271. JUCE_COMCLASS (JuceIVirtualDesktopManager, "a5cd92ff-29be-454c-8d04-d82879fb3f1b") : public IUnknown
  4272. {
  4273. public:
  4274. virtual HRESULT STDMETHODCALLTYPE IsWindowOnCurrentVirtualDesktop(
  4275. __RPC__in HWND topLevelWindow,
  4276. __RPC__out BOOL * onCurrentDesktop) = 0;
  4277. virtual HRESULT STDMETHODCALLTYPE GetWindowDesktopId(
  4278. __RPC__in HWND topLevelWindow,
  4279. __RPC__out GUID * desktopId) = 0;
  4280. virtual HRESULT STDMETHODCALLTYPE MoveWindowToDesktop(
  4281. __RPC__in HWND topLevelWindow,
  4282. __RPC__in REFGUID desktopId) = 0;
  4283. };
  4284. JUCE_COMCLASS (JuceVirtualDesktopManager, "aa509086-5ca9-4c25-8f95-589d3c07b48a");
  4285. } // namespace juce
  4286. #ifdef __CRT_UUID_DECL
  4287. __CRT_UUID_DECL (juce::JuceIVirtualDesktopManager, 0xa5cd92ff, 0x29be, 0x454c, 0x8d, 0x04, 0xd8, 0x28, 0x79, 0xfb, 0x3f, 0x1b)
  4288. __CRT_UUID_DECL (juce::JuceVirtualDesktopManager, 0xaa509086, 0x5ca9, 0x4c25, 0x8f, 0x95, 0x58, 0x9d, 0x3c, 0x07, 0xb4, 0x8a)
  4289. #endif
  4290. bool juce::detail::WindowingHelpers::isWindowOnCurrentVirtualDesktop (void* x)
  4291. {
  4292. if (x == nullptr)
  4293. return false;
  4294. static auto* desktopManager = []
  4295. {
  4296. JuceIVirtualDesktopManager* result = nullptr;
  4297. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wlanguage-extension-token")
  4298. if (SUCCEEDED (CoCreateInstance (__uuidof (JuceVirtualDesktopManager), nullptr, CLSCTX_ALL, IID_PPV_ARGS (&result))))
  4299. return result;
  4300. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  4301. return static_cast<JuceIVirtualDesktopManager*> (nullptr);
  4302. }();
  4303. BOOL current = false;
  4304. if (auto* dm = desktopManager)
  4305. if (SUCCEEDED (dm->IsWindowOnCurrentVirtualDesktop (static_cast<HWND> (x), &current)))
  4306. return current != false;
  4307. return true;
  4308. }