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.

5331 lines
189KB

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